Simvik

Smart doorbell: one ring per press

Debounce a bouncing button sampled every millisecond, so one press rings once. A medium embedded C problem (GPIO), run and graded in the browser.

medium · GPIO · debounce · active-low · sampling · product

Product: Smart doorbell (Smart home)

Requirement. One press of the doorbell button rings the chime once and sends one phone notification. The button's contacts bounce for several milliseconds, and a cheap button can bounce on release too.

doorbell_poll runs every 1 ms with the raw pin level. The button pulls the pin low when pressed (raw_high is false). Accept a new state only after it has held for 20 consecutive samples. Return true exactly once per press: on the sample where the press is accepted.

Starter code

bool doorbell_poll(debounce_t *d, bool raw_high) {
  bool down = !raw_high;
  bool edge = down && !d->pressed;
  d->pressed = down;
  return edge;
}

Example tests

A clean press

debounce_t d = { 0, false };
int rings = 0;
for (int t = 0; t < 30; t++) rings += doorbell_poll(&d, false);
for (int t = 0; t < 30; t++) rings += doorbell_poll(&d, true);
printf("%d\n", rings);

Expected output:

1

A press that bounces

debounce_t d = { 0, false };
int rings = 0;
for (int i = 0; i < 10; i++) { rings += doorbell_poll(&d, false); rings += doorbell_poll(&d, true); }
for (int t = 0; t < 25; t++) rings += doorbell_poll(&d, false);
for (int t = 0; t < 25; t++) rings += doorbell_poll(&d, true);
printf("%d\n", rings);

Expected output:

1

Learn it first

  • GPIO · Pin modes, push-pull versus open-drain, pulls, edge interrupts and debouncing.

More GPIO problems