🛠 Réagir aux boutons A et B
Objectives
Read the three buttons on the M5StickC Plus2: A = G37 (front), B = G39 (side), C = G35 (also the power button/wake source). Count presses, reset with B, and understand why C is a button to handle with caution.
Hardware
- 1× M5StickC Plus2 (v2)
- USB-C cable + CH9102 driver
- Arduino IDE (esp32 package) or PlatformIO, M5Unified library
Complete code
// Boutons A/B/C — broches INPUT ONLY G37/G39/G35 (jamais en sortie !)
#include <M5Unified.h>
uint32_t compteur = 0;
void setup {
auto cfg = M5.config;
M5.begin(cfg);
M5.Display.setRotation(1);
M5.Display.fillScreen(TFT_BLACK);
// M5Unified configure les broches en entrée avec pull-up interne
// (en écriture directe : pinMode(37, INPUT_PULLUP), etc.)
}
void loop {
M5.update;
if (M5.BtnA.wasPressed) { // bouton A = G37
compteur++;
M5.Speaker.tone(2093, 80); // bip court : buzzer passif sur G2 (PWM)
}
if (M5.BtnB.wasPressed) { // bouton B = G39
compteur = 0;
M5.Speaker.tone(440, 80);
}
if (M5.BtnC.wasPressed) { // C = G35 = aussi la touche power !
M5.Display.fillScreen(TFT_BLACK); // appui long > 6 s = extinction (sans USB)
}
M5.Display.setCursor(20, 50);
M5.Display.setTextSize(4);
M5.Display.setTextColor(TFT_YELLOW, TFT_BLACK);
M5.Display.printf("%-6lu", (unsigned long)compteur);
vTaskDelay(10 / portTICK_PERIOD_MS);
}
Expected verification
Each press on A increments the large yellow counter and makes the passive buzzer (G2, PWM tone output only) "beep". B resets the counter to zero. A short press on C clears the screen; holding it for more than 6 seconds without USB completely turns off the device.
Common errors
- Treating G37/G39/G35 as outputs: these are input-only pins, no current can flow out.
- Confusing short press and long press on C: beyond 6 seconds without USB, the machine turns off (with USB, only the screen turns off — power remains active, hence "it doesn't turn off / the battery drains while charging").
- Forgetting
M5.update:wasPressednever triggers. - Reading buttons with
digitalReadwithoutINPUT_PULLUP: floating state and ghost presses. - The buttons are tiny (known ergonomic drawback): account for debounce times, M5Unified already filters them.
Other tutorials for this board
Code examples for this board
hello-stick.inoArduinoboutons.inoArduinobuzzer.inoArduinoinclinometre.inoArduinohorloge.inoArduinoir-tv.inoArduino