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
Note: Edge detection on an ESP32: each press toggles the relay once.
Check Your Understanding
Test what you learned in this lesson