m5stack / M5Unified

Unified library for M5Stack series
MIT License
302 stars 54 forks source link

How to use StickC Plus beeper buzzer #112

Closed patfelst closed 4 months ago

patfelst commented 4 months ago

Hi there, on M5StickC Plus, how do I use the built in buzzer? It is connected to GPIO2.

I tried using the speaker code example however no sound was made. This is the code I tried:

void setup(void) {
  auto cfg = M5.config();

  cfg.serial_baudrate = 115200;  // default=115200. if "Serial" is not needed, set it to 0.
  cfg.clear_display = true;      // default=true. clear the screen when begin.
  cfg.output_power = true;       // default=true. use external port 5V output.
  cfg.internal_imu = true;       // default=true. use internal IMU.
  cfg.internal_rtc = true;       // default=true. use internal RTC.
  cfg.internal_spk = true;       // default=true. use internal speaker.
  cfg.internal_mic = false;      // default=true. use internal microphone.
  cfg.led_brightness = 0;        // default= 0. system LED brightness (0=off / 255=max) (※ not NeoPixel)

  M5.begin(cfg);

  M5.Speaker.begin();
  M5.Speaker.setVolume(64);
  /// The setAllChannelVolume function can be set the all virtual channel volume in the range of 0-255. (default : 255)
  M5.Speaker.setAllChannelVolume(255);
  /// The setChannelVolume function can be set the specified virtual channel volume in the range of 0-255. (default : 255)
  M5.Speaker.setChannelVolume(0, 255);
  /// play 2000Hz tone sound, 500 msec.
  M5.Speaker.tone(2000, 500);
  M5.delay(100);
  // play 1000Hz tone sound, 100 msec.
  M5.Speaker.tone(1000, 100);
  M5.delay(100);
  M5.Speaker.stop();
}

Thank you for any suggestions.

lovyan03 commented 4 months ago

Hello, @patfelst The buzzer built into the StickCPlus is very small, so it doesn't make a loud sound

It may be easier to see how it works by playing it repeatedly in a loop. Try the following code:

#include <M5Unified.h>

void setup() {
  M5.begin();
  M5.Speaker.setVolume(255);
}

void loop()
{
  for (int i = 1000; i < 8000; ++i) {
    M5.Speaker.tone(i, 100,0);
    M5.Display.drawNumber(i, 0, 0);
  }
}
patfelst commented 4 months ago

Yes that solved the problem, thank you so much. It is very quiet like you say. Have a nice day @lovyan03.