The idea: a button bounces, so look at it slowly

A push button is two metal contacts and a spring. When you press it, the contacts hit, spring apart and hit again several times before they stay closed. When you let go, they bounce again. This is contact bounce, and it lasts a few milliseconds (4 ms on the page). On the page the button pulls pin PA0 of an STM32 to ground, and a pull-up resistor holds the pin at 1 otherwise: 1 = released, 0 = pressed. During the bounce the pin flips between 0 and 1. The fix is to sample the pin only every 10 ms, longer than any bounce, and to believe a new value only when two samples in a row agree. A small state machine in C does this, one step per 10 ms tick.

Time line of one 150 ms push. The raw pin falls at 3 ms and bounces until 7 ms, rises at 153 ms and bounces until 157 ms. A naive falling-edge counter counts 3 edges in the press bounce and 2 in the release bounce: 5 presses. The 10 ms samples read 1 at 0 ms, 0 at 10 and 20 ms, then 1 at 160 and 170 ms. The state machine goes RELEASED, MAYBE_PRESSED at 10 ms, PRESSED at 20 ms with on_press, MAYBE_RELEASED at 160 ms, RELEASED at 170 ms with on_release: one press
The edge counter sees every bounce (5 presses); the 10 ms samples need two equal readings and see one press.

Why counting edges fails

The quickest code you could write puts an EXTI interrupt on the falling edge of the pin and adds 1 to a counter in it. How to set up pins and interrupts is on embedded I/O. The hardware is fast: it catches every 1 → 0 flip, including those of the bounce. On the page's seeded bounce, one short push gives 3 falling edges when the contacts close (at 3, 5.5 and 7 ms) and 2 more when they open (at 154 and 156 ms): 5 presses for one push (Demo: naive edge counter: 5 presses for one push). The zoom next to the trace shows the last edge 40 times wider, with each counted edge numbered. A real bounce is random, so the count changes from push to push; the page uses a seeded pattern so every run is the same.

The 4-state debouncer as a switch

The debouncer keeps one variable, state, between calls. Each tick, button_task() reads the pin once with HAL_GPIO_ReadPin and runs one switch (state):

statepin 0 (down)pin 1 (up)
RELEASED→ MAYBE_PRESSEDstay
MAYBE_PRESSED→ PRESSED, call on_press()→ RELEASED (it was noise)
PRESSEDstay→ MAYBE_RELEASED
MAYBE_RELEASED→ PRESSED (it was noise)→ RELEASED, call on_release()

The two MAYBE states are the memory of "the last sample was different". A press is accepted only after two 0 samples 10 ms apart. In the first demo the contacts close at 3 ms; the 10 ms sample reads 0 (MAYBE_PRESSED) and the 20 ms sample reads 0 again (PRESSED, on_press()) (Demo: one push, sample by sample). The code on the right of the diagram is the whole debouncer; the line that runs is lit at each step. The general theory of state machines, Moore and Mealy outputs and state encodings is on finite state machines; the same idea written as a hardware circuit is on the sequence detector FSM.

The MAYBE states also filter noise that is not bounce at all. A 3 ms spike that pulls the pin to 0 right across the 10 ms sample gives one 0 reading; the 20 ms sample reads 1, so the machine goes back from MAYBE_PRESSED to RELEASED and never calls on_press(). The edge counter counts 1 press that never happened (Demo: a 3 ms glitch is filtered).

How slow is slow enough

The rule is simple: the sample period must be longer than the longest bounce. Then at most one sample can fall inside a bounce, and whatever it reads, the next one is steady. In Demo: bounce lands on a sample the contacts close at 8 ms, so the 10 ms sample is 2 ms into the bounce and reads 1, the old value. The machine just stays in RELEASED; the 20 ms and 30 ms samples read 0 and the press is accepted at 30 ms instead of 20 ms. It is still exactly one press. The cost is latency: a press is seen 10 to 20 ms after the contacts close, sometimes 30 ms. People do not notice delays below about 50 ms, so this is fine for a button. Switches with bounce longer than 10 ms need a longer period or more equal samples in a row.

The page's input menu has 6 inputs. A new input starts after the last one has ended; Next Tick runs one 10 ms tick in detail, and Run to Idle runs until both machines are idle and the pin is quiet.

Click, double click, long press

The debouncer gives clean on_press() and on_release() events. They set the flags pressed and released, and a second machine, click_task(), runs right after it in the same tick. It counts ticks to tell three gestures apart:

  • Long press: in DOWN, ++hold == 100 (100 ticks = 1 s) calls long_press() while the button is still down, then WAIT_RELEASE waits for the release.
  • Double click: after a release, WAIT_SECOND waits up to 30 ticks (300 ms). A press in that time calls double_click().
  • Single click: when ++gap == 30 with no second press, it calls single_click(). So a single click is known only 300 ms after the release: the price of also having double clicks.

The gestures drive an LED mode: a click toggles OFF and ON, a double click makes the LED blink at 2 Hz (it toggles every 25 ticks), a long press turns it OFF. With a 150 ms gap between two 100 ms pushes, the second press comes 14 ticks after the first release: a double click at 270 ms (Demo: double click → LED blinks at 2 Hz). With a 400 ms gap the window has closed at tick 42, so the page sees two single clicks, ON and then OFF (Demo: two slow clicks (gap 400 ms)). Holding the button for 1.3 s fires long_press() 100 ticks after the press was accepted (Demo: long press 1 s → LED off).

Three time lines in 10 ms ticks. Double click: press at tick 2, release at tick 12 opens a 30-tick window, the second press at tick 27 falls inside it, so double_click fires at tick 27. Slow clicks: release at tick 12, the window closes at tick 42 with single_click, the second press at tick 52 starts a new click, single_click again at tick 92. Long press: press at tick 39, hold counts to 100, long_press fires at tick 139 while the button is still down; release at tick 169
Two windows decide the gesture: 30 ticks after a release for a double click, 100 ticks of holding for a long press.

It is a 10 ms task

Neither function waits or loops. Each call reads one sample, takes at most one arrow, and returns in a few microseconds; the state lives in static variables between calls. That is what makes it fit a time-triggered scheduler: SCH_Add_Task(button_task, 0, 1) runs it every 10 ms SysTick tick, with click_task after it, and the rest of the program never blocks on the button. Some designs call the same code from the SysTick interrupt itself; then it must stay short, and the order of that interrupt against others is on interrupt priority and nesting. The same "state in a variable, one step per event" shape in object-oriented code is the State pattern.

This is not the browser's debounce. Debounce and throttle in JavaScript wait for a pause in a burst of events with a timer; here the input is a level that is polled at a fixed rate, and the machine needs two equal samples, not silence.

See also embedded software architectures for the four ways a program can call a button handler like this one: polled in a super loop, flagged by an ISR, queued, or run as an RTOS task.

See also driving loads from an MCU pin for the pull-up or pull-down resistor that gives the button input a defined level.

What the page leaves out

Real bounce is random and differs per switch and per press; the page draws one seeded pattern, 4 ms long, at 0.5 ms steps. Hardware debouncing (an RC filter with a Schmitt-trigger input) and the common shift-register debouncer that keeps the last 8 samples in a byte are not drawn. The pin setup (MX_GPIO_Init, the pull-up), the EXTI handler of the naive counter, the LED pin code and the 2 Hz blink as a separate task are left out. Several buttons need one state variable each (an array of structs), and flags shared between an interrupt and the main loop need volatile; neither is shown.

On the mind map

Open the Computer Architecture mind mapComputerArchitectureAbstraction and numbers: layers and bit patternsAbstraction and numbersCombinational logic: output depends only on inputsCombinational logicSequential logic: state held by a clockSequential logicMIPS software: how C becomes machine wordsMIPS softwareThe processor: datapath plus controlThe processorPipelines and parallelism: more instructions at oncePipelines and parallelismMemory and I/O: small fast near, big slow farMemory and I/OMemory arraysMemory arraysdecoder picks wordline, bitlines readCPU cacheCPU cachetag, index, offset; hit or missCache address breakdownCache address breakdownsets = lines/ways; tag = rest of addressCache Write PoliciesCache Write PoliciesWrite-back sends dirty lines at evictionLoop tiling and interchangeLoop tiling and interchangeWalk rows; tile so reused data fitsMemory hierarchyMemory hierarchyAMAT = hit time + miss rate × penaltyDRAM timingDRAM timingopen row is fast, row change is slowMESI and false sharingMESI and false sharinga write invalidates other copiesVirtual memoryVirtual memoryTLB caches the page tableEmbedded I/OEmbedded I/Odevices are addresses; poll or interruptMCU startup to mainMCU startup to mainCopy .data, zero .bss, then mainButton debounce FSMTwo equal 10 ms samples = one pressI2C BusI2C BusWired-AND bus: ACK, stretch, arbitrateUSB enumerationUSB enumerationAddress 0, descriptors, SET_CONFIGURATIONCAN bus arbitrationCAN bus arbitrationDominant 0 wins: lowest ID sends unharmedModbus RTU and TCPModbus RTU and TCPone master asks; bad CRC means silenceTDMA time-triggered busTDMA time-triggered busFixed slots; FTA drops extremes, averagesAMBA AXI, AHB, APBAMBA AXI, AHB, APBVALID and READY both 1 on the edgePCIe TLPsPCIe TLPsRequests by address, completions by IDBus vs Crossbar vs NoCBus vs Crossbar vs NoCBus: one at a time; NoC: links in parallelADC and PWMADC and PWMSAR = binary search; duty = OC1RS/(PR2+1)PID ControlPID ControlI removes error; clamp stops windupOpen the Computer Architecture mind mapComputer Architecturesmall fast near, big slow farMemory and I/OMemory arraysMemory arraysdecoder picks wordline, bitlines readCPU cacheCPU cachetag, index, offset; hit or missCache address breakdownCache address breakdownsets = lines/ways; tag = rest of addressCache Write PoliciesCache Write PoliciesWrite-back sends dirty lines at evictionLoop tiling and interchangeLoop tiling and interchangeWalk rows; tile so reused data fitsMemory hierarchyMemory hierarchyAMAT = hit time + miss rate × penaltyDRAM timingDRAM timingopen row is fast, row change is slowMESI and false sharingMESI and false sharinga write invalidates other copiesVirtual memoryVirtual memoryTLB caches the page tableEmbedded I/OEmbedded I/Odevices are addresses; poll or interruptMCU startup to mainMCU startup to mainCopy .data, zero .bss, then mainButton debounce FSMTwo equal 10 ms samples = one pressI2C BusI2C BusWired-AND bus: ACK, stretch, arbitrateUSB enumerationUSB enumerationAddress 0, descriptors, SET_CONFIGURATIONCAN bus arbitrationCAN bus arbitrationDominant 0 wins: lowest ID sends unharmedModbus RTU and TCPModbus RTU and TCPone master asks; bad CRC means silenceTDMA time-triggered busTDMA time-triggered busFixed slots; FTA drops extremes, averagesAMBA AXI, AHB, APBAMBA AXI, AHB, APBVALID and READY both 1 on the edgePCIe TLPsPCIe TLPsRequests by address, completions by IDBus vs Crossbar vs NoCBus vs Crossbar vs NoCBus: one at a time; NoC: links in parallelADC and PWMADC and PWMSAR = binary search; duty = OC1RS/(PR2+1)PID ControlPID ControlI removes error; clamp stops windup
This page on the Computer Architecture mind map · 79 pages in 7 branches · open it to see the whole map and test yourself in recall mode.