Monday, October 8, 2018

Switch debounce library



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 seems that it is pressed many times, even if it is pressed once, and that's should became a problem.

To solve this issue there are two way:
  • Hardware
  • Software
The usual hardware way is to build a low pass filter. Sometimes you will find a Schmitt-trigger after the RC filter, to avoid hysteresis.
The limitation of the hardware way is that you have to implement it on your board, to select the correct component values, and to use more hardware.
A software solution may help us, providing a malleable way to solve this issue.

An interesting reading about this topic is the Jack Ganssle's article "A Guide to Debouncing" http://www.ganssle.com/debouncing.htm

Also, I suggest you to take a read at the two articles series by Elliott Williams, he explains this issue very well and also propose a few hardware and software solutions:
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/Button_Debouncer that is an implementation of the Jack Ganssle article posted above.

What it pratically 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 analyse 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 problem.

The library works by byte status, it means it can debounce multiples of 8 buttons at time, one for each bit. Therefore a 2 byte implementation can debounce 16 buttons.

There are function for 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

Notes
  • read risk disclaimer
  • excuse my bad english