简体中文
English
简体中文
日本語

Arduino 上手教程

2. 设备开发 & 案例程序

5. 扩展模块

6. 应用案例

Chain Captain Speaker 扬声器

Chain Captain 扬声器相关 API 与案例程序。

案例程序

编译要求

  • M5Stack 板管理版本 >= 3.3.10-a
  • 开发板选项 = M5ChainCaptain
  • M5Unified 库版本 >= 0.3.0
  • M5GFX 库版本 >= 0.3.0

Chain Captain 功放使能引脚为 G21,音频电源由 M5IOE1 IO5 控制,M5Unified 在调用 M5.Speaker.begin() 后会配置对应的 I2S 引脚和功放使能。

cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#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 可停止当前声音。

API

Chain Captain 扬声器部分使用 M5Unified 库中的 Speaker_Class,更多相关 API 可以参考下方文档:

Page Tools
PDF
On This Page