Pushbutton Event Handler: Part 1

Project Design

Pushbuttons or tactile switches are most popular input devices. But properly handling them is not so trivial. Let us check out what do we need to consider for the implementation.

(Chattering and Debouncing) Most type of mechanical contact switches produce contact bouncing effect. Following snapshot of an oscilloscope taken from Wikipedia illustrates this phenomenon well.

Actual situation varies a lot depending on the type of switch however. In a certain way chattering like above is quite exceptional, since it lasts only 2-3msec. Such short chattering can be dealt with simple hardware like R-C filter. More typically however chattering can last more than 100msec easily.

Robust implementation of pushbutton input handler thus requires polling of the switch state with a regular interval, eliminating erroneous input caused by momentary glitches.

(Short Click, Long Click and Multiple Click) Sometimes you want to assign a multiple functions on a single switch. You may want to distinguish between short click and long click or you may want to assign different tasks for single click, double click, triple click and so on.

This requires an algorithm that keeps track of the state of the button in time. For example when a single click is detected, it should be able to determine whether it has to wait certain amount of time for the next click or it can declare the single click event now. The timer based pushbutton state polling routine is well suited for this purpose.

(Event Generation and Handling) Finally, there is a situation when you want to divide one task into at least two parts, one part that needs to be executed in very short duration of time, usually much less than a millisecond, and the other part that has no particular time limit and that can be interrupted at any moment.

Instead of having a single routine that (1) polls states of pushbuttons regularly (2) determines the type of the button action based on the history, (3) then run certain tasks depending on the result of (2), you can divide them into two parts, i.e. fast processing part (1+2) and slow processing part (3). The fast processing part can be implemented as a interrupt callback function since it takes only a few microseconds at most. Then it generates an event when valid input is detected. The slow processing part can be called in a main loop checking the event, runs dedicated function if necessary, with no particular time constraint.

In the following posts, we will implement basic structure on a STM32 platform.

Leave a comment