Contact bounce (ref. https://en.wikipedia.org/wiki/Switch#Contact_bounce) is a common problem with mechanical switches and relays. Switch and relay contacts are usually made of springy metals. When the contacts strike together, their momentum and elasticity act together to cause them to bounce apart one or more times before making steady contact.
You can find below a sample of a bouncy button press. You can see the typical ripples of the bounce button press.
If you use a microcontroller to read the button status, depending on the speed you read the button it may seem that it is pressed many times, even if it is pressed once, and that’s should become a problem.
To solve this issue there is two way:
- Hardware
- Software
An interesting reading about this topic is Jack Ganssle‘s article “A Guide to Debouncing” http://www.ganssle.com/debouncing.htm
Also, I suggest you take a read at the two articles series by Elliott Williams, he explains this issue very well and also proposes a few hardware and software solutions:
- Embed with Elliot: debounce your noisy buttons, part I: https://hackaday.com/2015/12/09/embed-with-elliot-debounce-your-noisy-buttons-part-i/
- Embed with Elliot: debounce your noisy buttons, part II: https://hackaday.com/2015/12/10/embed-with-elliot-debounce-your-noisy-buttons-part-ii/
The library I propose here is, of course, a software solution developed on ATmega microcontroller but portable to many other micros.
It is based on the Trent Cleghorn code you can find it here: https://github.com/tcleg that is an implementation of the Jack Ganssle article posted above.
What it practically does is to read the button status a bounch of time, and set the final status button only if all the times the reading was done is the same.
Ganssle by experiments analyzes that a value from 10ms to 20ms is enough to consider stable a button output. In my example, I read 8 times the button each 10ms, but one can also use less time without a problem.
The library works by byte status, it means it can debounce multiples of 8 buttons at the time, one for each bit. Therefore a 2-byte implementation can debounce 16 buttons.
There is a function to get the press and release button, and the current status. Press and release functions also are implemented in such a way that one can read that function and arm back that function status only after it is read.
Code
Read More Detail: Switch debounce library