Everybody wants to push the button - nobody wants to think about what’s inside the switch!
Reading the input from a pushbutton switch is probably the second thing most people do with a microcontroller, after blinking an LED.
It seems simple… but if you want to do it right, it’ll take you on a tour of the entire hardware stack!
-> embedded software
-> microcontroller architecture
-> digital logic gates
-> analog circuit analysis
-> mechanics of the switch
Spoiler
Which will lead to questions like:
“Is anything in your computer really a
1or a0?”Spoiler
Which will lead to questions like:
The problem with switches
There’s a metal contact inside the switch and it literally bounces.
Without debouncing, you might count multiple press and release events in quick succession (lasting about 10 ms), even though the button was only “pressed” once.
If the switch is connected to a light bulb, you won’t see anything wrong. Your eye doesn’t respond fast enough to see the changes.
But an interrupt-driven microcontroller may pick up state changes in the sub-microsecond range.
The Fixes
A few common ways to debounce in hardware are to use
- a double-throw switch and two input pins
- a Schmitt trigger input buffer
- or an RC circuit
An example of debouncing in software is to:
- read inputs with a timer tick every 5 ms
- if it goes high and stays high for 10ms (2 ticks) → button pressed event
or, if it goes low and stays low for 50ms (10 ticks) → button released event
The tradeoff: the more delay added to prevent switch bounce, the slower the response to user input.
Hardware and software approaches can be combined for more robust designs.
Tip: Measure the bounce time with an oscilloscope! That way you’ll know what you’re up against.
Readings & resources
Jack Ganssle: A Guide to Debouncing: Part 1
Jack Ganssle: A Guide to Debouncing: Part 2