মূল বিষয়বস্তুতে যান
Learn/Digital inputs/Debouncing and edge detection
Digital inputs · Lesson
10 min read

Debouncing and edge detection

Count presses correctly by detecting the moment a button changes.

What You Will Learn

  • Detect a press (edge) instead of a level
  • Debounce with a short delay or millis()

Metal contacts bounce for a few milliseconds when pressed, producing several quick HIGH/LOW changes. If you count every change, one press can count as five.

Arduino C++
bool last = HIGH;
unsigned long lastChange = 0;
int presses = 0;

void loop() {
  bool now = digitalRead(2);
  if (now != last && millis() - lastChange > 30) {
    lastChange = millis();
    if (now == LOW) {
      presses++;
      Serial.println(presses);
    }
    last = now;
  }
}

The idea: remember the previous reading, react only when it changes (an edge), and ignore changes that come too soon after the last one.

The simulator's buttons don't bounce, so presses here are always clean. Real buttons do — keep the debounce in code that goes onto hardware.
ESP32: button toggles a relayesp32-devkit-v1
Open in Lab
ESP32-WROOM-32: The metal can holds the ESP32 chip, 4 MB flash and the 40 MHz crystal. The top part is the PCB antenna — keep it clear of metal.ESP32-WROOM-32Antenna: Printed Wi-Fi/Bluetooth antenna.Micro-USB: Upload sketches, open the Serial Monitor and power the board (5 V).USB-UART: CP2102 or CH340 chip that turns USB into the ESP32's serial port.EN: Reset button (pulls EN low).BOOT: Holds GPIO0 low; press it while uploading if the upload tool can't enter boot mode.LED (GPIO2): Built-in blue LED on GPIO2 on most DevKit V1 boards.3.3 V regulator: AMS1117 regulator: 5 V → 3.3 V.RELAYVCCGNDINCOMNONC330 Ω+
Note: Edge detection on an ESP32: each press toggles the relay once.

Check Your Understanding

Test what you learned in this lesson

1Why do we debounce buttons?