melodie.ino

M5Stack Core (ESP32) — Basic / Gray family (K001 / K002) · File : melodie.ino · Language : Arduino · Use case : Jouer des notes avec le haut-parleur interne

The case's tiny I2S amp plays square tones: frequency + duration and the melody comes out. Press C to trigger — the perfect audio feedback for an alarm or menu.

Hardware required

An M5Stack Core Basic/Gray (ESP32 in an enclosure with a 320×240 TFT, A/B/C buttons, speaker, microSD slot, 110 mAh battery). None.

Wiring

No wiring; the 1 W speaker is clipped inside the case. Volume via M5.Speaker.setVolume (0-255).

How it works

M5.Speaker.tone generates the square wave in the I2S driver; duration is in ms. The short gap between notes keeps DMA buffer frames from merging. In the Arduino IDE (esp32 package), board « M5Stack-Core-ESP32 »; install the « M5Stack » (or M5Unified) library from the Library Manager, then Upload.

Going further

A temperature chime (frequency = value), or playing an 8-bit port as a scale for audio debugging.

melodie.ino

// Buzzer/speaker 3 W via I2S (NS4168) — bibliotheque M5Stack.
#include <M5Stack.h>

struct Note { uint16_t freq; uint16_t duree; };
Note melody[] = {
  {523, 200}, {659, 200}, {784, 200}, {1047, 400},   // do mi sol do'
  {784, 150}, {659, 150}, {523, 300}, {0, 200},       // descente + pause
};
const int NB = sizeof(melody) / sizeof(Note);

void setup() {
  M5.begin(true, false, true, false);   // lcd, sd, speaker, power
  M5.Power.setSpeakerMute(false);
  Serial.begin(115200);
}

void loop() {
  M5.update();
  if (M5.BtnC.wasPressed()) {
    Serial.println("Joue la melodie");
    for (int i = 0; i < NB; i++) {
      if (melody[i].freq) M5.Speaker.tone(melody[i].freq, melody[i].duree);
      else delay(melody[i].duree);
      delay(20);                        // laisse la trame I2S partir
    }
  }
  delay(10);
}

← Back to the board