Once you’ve built a melody in the grid and tested it using the live audio preview, you can easily export it for use in your ESP32 sketch.
int melody[] = { NOTE_C4, NOTE_E4, 0, NOTE_G4 };
int noteDurations[] = { 250, 250, 250, 250 };
Copy and paste the generated arrays directly into your Arduino sketch. Then, loop through them using ledcWriteTone() like we did in the passive buzzer tutorial:
#include <Arduino.h>
#include "notes.h"
#define SPEAKER_PIN 19
#define CHANNEL 0
#define RESOLUTION 8
int melody[] = { NOTE_C4, NOTE_E4, 0, NOTE_G4 };
int noteDurations[] = { 250, 250, 250, 250 };
void setup() {
Serial.begin(9600);
ledcSetup(CHANNEL, 2000, RESOLUTION);
ledcAttachPin(SPEAKER_PIN, CHANNEL);
}
void loop() {
for (int i = 0; i < sizeof(melody) / sizeof(melody[0]); i++) {
int freq = melody[i];
int duration = noteDurations[i];
if (freq > 0) {
ledcWriteTone(CHANNEL, freq);
} else {
ledcWriteTone(CHANNEL, 0);
}
delay(duration);
ledcWriteTone(CHANNEL, 0);
}
delay(1000);
}
It’s the fastest way to go from “melody in your head” to “melody on your ESP32 buzzer.”