Skip to main content

Subsection 2.1.3 Contact Bounce

Even with a stable pull-up, mechanical buttons introduce a second problem: contact bounce. The metal contacts inside a switch are tiny springy leaves. When you press or release the button, they do not make clean, instantaneous contact: they collide, rebound, collide again, and chatter back and forth for anywhere from a few hundred microseconds to a few milliseconds before settling. During this chatter, the pin toggles between 0 and 1 dozens of times in rapid succession.
To a human finger, a press and release takes tens of milliseconds, plenty of time to do something once. But to a microcontroller running at 12 MHz, those milliseconds contain hundreds of thousands of clock cycles. If your code detects a rising or falling edge on the pin, it may see 50 edges in the time your finger takes to press once. Depending on what action each edge triggers (incrementing a counter, toggling an LED, sending a message), this can cause serious errors.
Bounce is eliminated either in hardware or in software, and we’ll do both.
Hardware debouncing adds an RC filter (a resistor and capacitor) that smooths out the fast chatter. The capacitor cannot charge or discharge instantaneously, so the rapid bounces are averaged away before they reach the pin.
Software debouncing ignores the pin for a short time after detecting the first edge, letting the bounce die out before sampling again. A simple approach waits a fixed delay (say, 20 ms) after the first transition and then reads the pin’s stable final state. More robust approaches use a state machine that requires the pin to hold a consistent value for several consecutive samples before accepting it as a real transition.