
Arduino 上手教程
Chain Captain 扬声器相关 API 与案例程序。
3.3.10-aM5ChainCaptain0.3.00.3.0Chain Captain 功放使能引脚为 G21,音频电源由 M5IOE1 IO5 控制,M5Unified 在调用 M5.Speaker.begin() 后会配置对应的 I2S 引脚和功放使能。
#include <M5Unified.h>
static const uint16_t NOTES[] = {
262, 294, 330, 349, 392, 440, 494, 523,
};
static const char* NOTE_NAMES[] = {
"C4", "D4", "E4", "F4", "G4", "A4", "B4", "C5",
};
static const size_t NOTE_COUNT = sizeof(NOTES) / sizeof(NOTES[0]);
static size_t noteIndex = 0;
static void drawNote()
{
M5.Display.startWrite();
M5.Display.fillScreen(TFT_BLACK);
M5.Display.setTextDatum(middle_center);
M5.Display.setFont(&fonts::FreeSansBold12pt7b);
M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
M5.Display.drawString("Speaker Test", 120, 34);
M5.Display.setFont(&fonts::FreeSansBold24pt7b);
M5.Display.drawString(NOTE_NAMES[noteIndex], 120, 108);
M5.Display.setFont(&fonts::FreeSans9pt7b);
M5.Display.drawString("A: stop B: prev C: next", 120, 184);
M5.Display.endWrite();
}
static void playNote()
{
drawNote();
// tone() is non-blocking; the note stops automatically.
M5.Speaker.tone(NOTES[noteIndex], 350);
Serial.printf("Play %s: %u Hz\n", NOTE_NAMES[noteIndex], NOTES[noteIndex]);
}
void setup()
{
delay(500);
auto cfg = M5.config();
cfg.serial_baudrate = 115200;
M5.begin(cfg);
M5.Display.setRotation(0);
M5.Display.setBrightness(128);
M5.Speaker.begin();
M5.Speaker.setVolume(100);
drawNote();
}
void loop()
{
M5.update();
if (M5.BtnB.wasClicked()) {
noteIndex = (noteIndex + NOTE_COUNT - 1) % NOTE_COUNT;
playNote();
}
if (M5.BtnC.wasClicked()) {
noteIndex = (noteIndex + 1) % NOTE_COUNT;
playNote();
}
if (M5.BtnA.wasClicked()) {
M5.Speaker.stop();
Serial.println("Speaker stopped");
}
delay(20);
}上传后,按动 KEYB / KEYC 可播放上一个 / 下一个音阶,屏幕同步显示当前音名;按动 KEYA 可停止当前声音。
Chain Captain 扬声器部分使用 M5Unified 库中的 Speaker_Class,更多相关 API 可以参考下方文档: