Debounce a button
Accept a new button state only after it has been stable for several samples. A medium embedded C problem (Timing, interrupts and concurrency), run and graded…
medium · Timing, interrupts and concurrency · debounce · gpio
A mechanical contact bounces for a few milliseconds each time it changes. Sample it on a timer and only believe a change that persists.
Each call supplies one raw sample. The debounced state changes to the raw value once threshold consecutive samples have differed from it; a sample that agrees with the debounced state resets the count. Return the debounced state after processing the sample.
Starter code
bool debounce_update(debounce_t *d, bool raw, uint8_t threshold) {
// Accepts every bounce: this is the behaviour to fix.
d->stable = raw;
return d->stable;
}Example tests
Press with bounce, then release
debounce_t d = { false, 0 };
feed(&d, "1101110001", 3);Expected output:
0000011100Short glitches are ignored
debounce_t d = { false, 0 };
feed(&d, "0100100", 3);Expected output:
0000000Learn it first
- Interrupts, timing and concurrency · How interrupts work on a Cortex-M, priorities, latency, races, rollover-safe time, non-blocking code and debouncing.
More Timing, interrupts and concurrency problems
- Elapsed time across rollover · Compute how many ticks have passed, even when the counter has wrapped.
- Rollover-safe timeout · Decide whether a timeout has expired without being fooled by wrap-around.
- Non-blocking blink · Derive an LED state from the current time instead of calling delay.
- Milliseconds to ticks · Convert a delay in milliseconds to RTOS ticks, rounding up.
- Periodic software timer · Fire once per period without drift and across counter rollover.
- Protect a shared variable · Make a read-modify-write safe from interrupts, and safe to nest.
- Cooperative scheduler · Run periodic tasks from a table, the core of a super-loop.
- Driver: measure worst-case time with the cycle counter · Enable the Cortex-M cycle counter and time a function across many runs, wraparound included.
- Smart lock: relock after 30 seconds · Relock automatically, with time arithmetic that survives the millisecond counter wrapping.