Monday, May 28, 2012

Easy button debouncing technique for STM32

Yesterday I had to debounce a button on my STM32VL-Discovery. I did a quick search and found an amazing article on Hack A Day:

Debounce Code – one post to rule them all

This is a great collection of many approaches to button debounce. I didn't use any however (although I liked the integration technique very much) - I had just one button that may not even be pressed at all - so I didn't want to poll it or anything. Rather I went for external interrupt to detect the press itself.

Then I thought I would just mask the handling code for some time.
When the button is pressed, MCU enters the EXTI routine. But before doing anything in the routine, we are checking if TIM4 counter is zero (may well be any other TIM - TIM4 is just because I liked it most). Well, TIM4 is configured as one-shot timer with period of about 250 ms and if you didn't press the button for some time, it's counter definitely surely is zero. So we proceed to the routine itself and do all the necessary staff - blink leds, send text to console etc. Among this we fire up the TIM4.
For the next 250ms there will be a number of jitter on the EXTI line and each time it will cause interrupt handler to interfere and do it's job. However these times TIM4 counter is speeding up to its ARR value (so it's not anywhere close to zero) and thus interrupt handler will not do anything - it's masked out. Untill after 250ms passed and TIM4 rolls over. You don't even need an interrupt for TIM4, stop it or reload it - it automatically dies away after 250 untill fired up again by software, if the button is pressed again of course.
This technique is very simple, but it's also very limited. To handle two buttons you'll pay two timers. More buttons - higher the price. It also doesn't work for DOWN/HOLD/RELEASE detection - it can do nothing but a short button press.
But if you need just that - works very reliably.

No comments: