Debouncing a digital input such as a button
When a button is pressed, the digital input to a microcontroller may “bounce” between high and low until it finally settles to a valid state (see this Wikipedia entry)
Here is a complete, standalone Atmel Studio example project called debounce_example that demonstrates the usage of the included debounce module (debounce.h, debounce.c and debounce_cfg.h). The debounce module is is able to “debounce” a digital input by looking at successive values and deciding if it is a valid low or high state. It is also able to register and remember a rising edge event (e.g. key pressed) and falling edge event (e.g. key released).
It uses a simple binary state machine, counter and edge event flags to keep track of the debounced state of each digital input. It works by incrementing a counter each time the current digital input state is HI. If the counter reaches the high watermark threshold, the debounced state is considered HI. Conversely, the counter is decremented each time the current digital input state is LO. If the counter reaches the low watermark threshold, the debounced state is considered LO. The minimum counter value is 0 and the maximum value is DEBOUNCE_CFG_COUNT_MAX. This scheme provides sufficient hysteresis to debounce a noisy digital input.
If no hysteresis is required, then DEBOUNCE_CFG_THRESHOLD_LO can be set to 0 and DEBOUNCE_CFG_THRESHOLD_HI can be set to DEBOUNCE_CFG_COUNT_MAX.
The debounce module has been added to the piconomic-fwlib and the documentation is here.
Enjoy!
Leave a Reply
Want to join the discussion?Feel free to contribute!