Simvik

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_SAMPLES samples. Report BTN_LONG once, while it is still held; its release reports nothing.
  • Click: a short press, released, and no second press within GAP_SAMPLES samples. Report BTN_CLICK when that gap has passed.
  • Double-click: a short press, released, then a second short press that starts within the gap. Report BTN_DOUBLE when 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:

C

A double-click

feed("10d10u10d50u");

Expected output:

D

A long press

feed("150d20u");

Expected output:

L

Learn it first

More State machines problems