🛠 Lire un bouton poussoir avec anti-rebond
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
- ESP32-S2 board
- 1 push button
- 1 LED with a 330 Ω resistor (optional, for the indicator)
- Dupont cables
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
- Forgetting
INPUT_PULLUP: the input floats and the state changes without pressing the button. - Misunderstanding inverted logic: with a pull-up, the GPIO reads LOW when the button is pressed.
- Debounce time too short: some presses are counted twice; increase
DEBOUNCE_MS. - Button wired to a pin occupied by flash or PSRAM: consult the board schematic before choosing the pin.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinorespiration.inoArduinodht22.inoArduinooled-i2c.inoArduinoserveur-web.inoArduino