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:
1A 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:
1Learn it first
- GPIO · Pin modes, push-pull versus open-drain, pulls, edge interrupts and debouncing.
More GPIO problems
- Update several pins at once · Write new levels to the pins selected by a mask and leave every other pin alone.
- Toggle an LED · Flip one pin with a single XOR, whatever its current level.
- Read an active-low button · A button wired to ground reads 0 when pressed. Report it as pressed.
- Configure pin modes · Set the direction and pull-up bits for one pin as input, input with pull-up or output.
- Driver: drive an LED through GPIO registers · Make a pin an output without disturbing its neighbours, then set, clear and toggle it atomically.
- Driver: a debounced button on PC13 · Configure an input with its pull-up, then report each press once, ignoring contact bounce.
- Fix: the debugger cannot connect any more · Configuring one pin overwrites the mode of every other pin of the port, the debug pins included.