Objectives
- Read the three programmable front-panel buttons: A = GPIO39, B = GPIO38, C = GPIO37.
- Use M5.update and the wasPressed / wasReleased methods from M5Unified.
- Make the 1 W speaker wired to the DAC output GPIO25 sound (tone, beep, mute).
- Display a press counter for each button on the screen.
Hardware
- 1 M5Stack Core (Basic or Gray).
- Nothing external: buttons and speaker are built-in.
- Note: GPIO39/38/37 are input-only pins (no internal pull-down) — perfect for buttons, unusable as outputs.
Complete code
#include <M5Unified.h>
uint32_t nbA = 0, nbB = 0, nbC = 0;
void setup {
auto cfg = M5.config;
M5.begin(cfg);
M5.Speaker.setVolume(180);
M5.Display.setTextSize(2);
M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
M5.Display.println("Boutons A / B / C");
}
void loop {
M5.update; // indispensable avant wasPressed
if (M5.BtnA.wasPressed) {
nbA++;
M5.Speaker.tone(2200, 100); // 2,2 kHz pendant 100 ms
}
if (M5.BtnB.wasPressed) {
nbB++;
M5.Speaker.beep;
}
if (M5.BtnC.wasPressed) {
nbC++;
M5.Speaker.mute;
}
M5.Display.fillRect(0, 50, 320, 90, TFT_BLACK);
M5.Display.setCursor(10, 55);
M5.Display.printf("A : %lu\n", nbA);
M5.Display.printf("B : %lu\n", nbB);
M5.Display.printf("C : %lu\n", nbC);
vTaskDelay(5 / portTICK_PERIOD_MS);
}
Expected verification
- Each press of A increments the A counter and emits a high-pitched beep; B emits a standard beep; C mutes the sound.
- The counters remain consistent (one press = +1, no visible bouncing thanks to M5Unified).
- The serial monitor is not necessary: all feedback is on the screen.
Common errors
- Forgetting M5.update in loop: wasPressed never returns true.
- Expecting buttons to work with pinMode(INPUT_PULLDOWN): GPIO37-39 pins have no internal pull-down; let M5Unified handle it.
- Using GPIO39/38/37 to control a component: these are input-only pins.
- Confusing the front-panel buttons with the red side button: the latter controls power via the IP5306 (double-click = shutdown), it is not readable by the program.
- Volume too low: call M5.Speaker.setVolume before any tone/beep.