Thursday, 12 June 2014

Fixing switch bounce in firmware

I have been involved in many products where a poor understanding of switch bounce has led to a design that had problems in the field. To learn how to deal with this the engineer has to understand exactly what switch bounce is. Although I refer to this as switch bounce, it relates to reading any input.
When a switch is pressed down, it does not go cleanly from an open state to a closed state. The mechanical components that carry out the switching usually has a settling time, which can vary from a few milliseconds up to almost 30 or 40 milliseconds in some cases. Below is a diagram of the waveform that can be seen when a switch is pressed.


Switch bounce

With microcontrollers running at faster and faster speeds, this switch will be read as being pressed many times, if switch bounce is not catered for. If the switch is used to toggle a parameter on and off on the product, then the microcontroller will detect this many times for just one key press.

If the switch normally has a pull up resistor and is used to take an input low when pressed, then the way to deal with bounce is as follows, for a switch that has a maximum bounce period of say 35 milli seconds.

If this input goes from high to low, then wait 40 milliseconds and check if input is still low. If yes, then switch is pressed and all bounce has finished so set switch pressed flag.

Remember that there will be bounce when the switch is released. So a similar procedure has to be followed to check for this. If this input goes from low to high, then wait 40 milliseconds and check if input is still high. If yes, then switch has been released.

Summary - This basic software solution is important to prevent microcontrollers reading an input many times when it actually has been actuated just once.

No comments:

Post a Comment