English
English
简体中文
日本語

Arduino Quick Start

2. Devices & Examples

5. Extensions

6. Applications

Chain Captain Speaker

Chain Captain speaker related APIs and sample programs.

Example

Compilation Requirements

  • M5Stack Board Manager Version >= 3.3.10-a
  • Board Option = M5ChainCaptain
  • M5Unified Library Version >= 0.3.0
  • M5GFX Library Version >= 0.3.0

The Chain Captain amplifier enable pin is G21, and the audio power is controlled by M5IOE1 IO5. After M5.Speaker.begin() is called, M5Unified configures the corresponding I2S pins and the amplifier enable.

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);
}

After uploading, press KEYB / KEYC to play the previous / next note; the current note name is shown on the screen in sync. Press KEYA to stop the current sound.

API

The Chain Captain speaker section uses the Speaker_Class from the M5Unified library. For more related APIs, refer to the following document:

Page Tools
PDF
On This Page