🛠 Lire un bouton poussoir avec anti-rebond

ESP32-S2 · debutant · Schéma : IMG-esp32-s2-debutant-2-esp32-s2-bouton-anti-rebond.svg — Bouton poussoir entre le GPIO4 et le GND, résistance de pull-up interne activée par le programme sur la carte ESP32-S2.

Objectives

Learn digital input reading on the ESP32-S2: enable an internal pull-up resistor, read the state of a button, and filter mechanical bouncing using a software delay.

Hardware

Full code

// Bouton avec anti-rebond logiciel sur ESP32-S2
const uint8_t BTN_PIN = 4;
const uint8_t LED_PIN = 2;
const unsigned long DEBOUNCE_MS = 50;

bool etatLed = false;
bool dernierEtatBtn = HIGH;
unsigned long dernierBordMs = 0;

void setup {
  pinMode(BTN_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);
}

void loop {
  bool etatBtn = digitalRead(BTN_PIN);
  unsigned long maintenant = millis;
  if (etatBtn != dernierEtatBtn &&
      maintenant - dernierBordMs >= DEBOUNCE_MS) {
    dernierBordMs = maintenant;
    dernierEtatBtn = etatBtn;
    if (etatBtn == LOW) {          // bouton enfoncé (logique inversée)
      etatLed = !etatLed;
      digitalWrite(LED_PIN, etatLed ? HIGH : LOW);
      Serial.println(etatLed ? "LED ON" : "LED OFF");
    }
  }
}

Expected verification

Each press of the button toggles the LED and displays "LED ON" or "LED OFF" on the serial monitor at 115200 bauds. A single firm press results in only one state change.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials