boutons.ino

M5Stack Core (ESP32) — Basic / Gray family (K001 / K002) · File : boutons.ino · Language : Arduino · Use case : Utiliser les trois boutons du boîtier

The case's three wired buttons (GPIO39/38/12) become a menu: wasPressed for events, isHeld for long-press. M5.update() is the reflex to keep at the top of loop.

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. Button C (GPIO12) sits on the module's GPIO12 strap: holding it at start-up changes the flash mode.

How it works

The library debounces and latches edges; wasPressed returns true once per press. Power.sleep puts the case to sleep, woken by button C. In the Arduino IDE (esp32 package), board « M5Stack-Core-ESP32 »; install the « M5Stack » (or M5Unified) library from the Library Manager, then Upload.

Going further

Add double-click (wasDoubleClicked on recent versions), or scroll a graph with A/B.

boutons.ino

// Boutons A (39), B (38), C (12) — bibliotheque M5Stack.
#include <M5Stack.h>

int choix = 0;
const char *MENU[] = {"LED", "SON", "RESEAU", "BATTERIE"};

void setup() {
  M5.begin();
  M5.Lcd.setTextSize(2);
}

void loop() {
  M5.update();                          // rafraichit l'etat des boutons
  if (M5.BtnA.wasPressed()) choix = (choix + 3) % 4;   // precedent
  if (M5.BtnB.wasPressed()) choix = (choix + 1) % 4;   // suivant
  if (M5.BtnC.wasPressed()) {                          // selectionne
    M5.Lcd.fillScreen(TFT_BLACK);
    M5.Lcd.setCursor(10, 100);
    M5.Lcd.printf(">> %s <<", MENU[choix]);
    M5.Speaker.tone(880, 80);
  }
  if (M5.BtnA.isHeld() || M5.BtnB.isHeld() || M5.BtnC.isHeld()) {
    M5.Power.sleep();                   // maintenu = veille (retour C)
  }
  delay(20);
}

← Back to the board