Read an active-low button
A button wired to ground reads 0 when pressed. Report it as pressed. An easy embedded C problem (GPIO), run and graded in the browser.
easy · GPIO · gpio · input · active-low
A button connects a pin to ground when it is pressed, and an internal pull-up holds the pin high otherwise, so the input is active low: the pin reads 0 while the button is pressed.
Write button_pressed(pins, pin), which returns true when the button on pin is pressed, given the input register value pins.
Starter code
bool button_pressed(uint8_t pins, uint8_t pin) {
return (pins >> pin) & 1u;
}Example tests
Pin low means pressed
show(button_pressed(0xFB, 2));Expected output:
pressedPin high means released
show(button_pressed(0xFF, 2));Expected output:
releasedLearn 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.
- 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.
- Smart doorbell: one ring per press · Debounce a bouncing button sampled every millisecond, so one press rings once.