Simvik

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:

0000011100

Short glitches are ignored

debounce_t d = { false, 0 };
feed(&d, "0100100", 3);

Expected output:

0000000

Learn it first

More Timing, interrupts and concurrency problems