Click, double-click and long press
Turn a sampled button into click, double-click and long-press events with a state machine. A hard embedded C problem (State machines), run and graded in the…
hard · State machines · fsm · debounce · ui
One button, three gestures. btn_sample(b, pressed) is called every 10 ms with the debounced button level and returns at most one event:
- Long press: held for
LONG_SAMPLESsamples. ReportBTN_LONGonce, while it is still held; its release reports nothing. - Click: a short press, released, and no second press within
GAP_SAMPLESsamples. ReportBTN_CLICKwhen that gap has passed. - Double-click: a short press, released, then a second short press that starts within the gap. Report
BTN_DOUBLEwhen the second press is released.
A second press held for LONG_SAMPLES is a long press. Use the states in the prelude.
Starter code
int btn_sample(btn_t *b, bool pressed) {
return pressed ? BTN_CLICK : BTN_NONE;
}Example tests
A click
feed("10d50u");Expected output:
CA double-click
feed("10d10u10d50u");Expected output:
DA long press
feed("150d20u");Expected output:
LLearn it first
- State machine patterns in C · Switch, transition tables and state-function pointers compared.
More State machines problems
- Traffic light with a fault mode · Write the transition function for a light that cycles, flashes on a fault and resets.
- Table-driven state machine · Look up a transition in a table, run its action and return the next state.
- Keypad code lock · Implement a door lock that takes a 4-digit code, re-locks, and locks out after three failures.
- Garage door controller · Write the transition function of a garage door, including the obstacle safety reversal.
- Fix: the door opens by itself · A door controller skips its unlocking state.
- Washing machine: the cycle and the door · Run a wash cycle as a state machine that pauses safely when the door opens.