Toggle an LED
Flip one pin with a single XOR, whatever its current level. An easy embedded C problem (GPIO), run and graded in the browser.
easy · GPIO · gpio · output · xor
Write gpio_toggle(port, pin): flip the level of one pin and leave the others alone, without reading the pin first to decide.
Calling it twice must restore the original value.
Starter code
void gpio_toggle(volatile uint8_t *port, uint8_t pin) {
*port |= (uint8_t)(1u << pin);
}Example tests
Off to on
uint8_t port = 0x00;
gpio_toggle(&port, 2);
show(port);Expected output:
0x04On to off
uint8_t port = 0x04;
gpio_toggle(&port, 2);
show(port);Expected output:
0x00Learn 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.
- 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.
- Smart doorbell: one ring per press · Debounce a bouncing button sampled every millisecond, so one press rings once.