EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 31
Debouncing Buttons
Mechanical contacts bounce.
When a switch closes, the contacts chatter for a few milliseconds, producing several fake presses. A fast MCU will count them all.
Software fix: accept a new state only after the input has stayed the same for around 20 ms. Hardware fix: add a small resistor and capacitor to smooth the edge.
A timer interrupt that samples the pin every few milliseconds is a clean, non-blocking approach.
EXAMPLE
uint8_t stable = 0, count = 0;
/* call every 5 ms */
uint8_t debounce(uint8_t raw) {
if (raw == stable) { count = 0; }
else if (++count >= 4) { stable = raw; count = 0; }
return stable;
}