Configure pin modes
Set the direction and pull-up bits for one pin as input, input with pull-up or output. A medium embedded C problem (GPIO), run and graded in the browser.
medium · GPIO · gpio · direction · pull-up · registers
A port has a direction register ddr (1 = output, 0 = input) and an output register port. On this part, writing 1 to the output bit of an input pin turns on its pull-up.
Write gpio_configure(ddr, port, pin, mode):
| mode | ddr bit | port bit |
|---|---|---|
MODE_INPUT | 0 | 0 (no pull-up) |
MODE_INPUT_PULLUP | 0 | 1 |
MODE_OUTPUT | 1 | unchanged |
Only the bits of pin may change.
Starter code
void gpio_configure(volatile uint8_t *ddr, volatile uint8_t *port, uint8_t pin, pin_mode_t mode) {
*ddr = 0;
*port = 0;
}Example tests
Output
uint8_t ddr = 0x00, port = 0x00;
gpio_configure(&ddr, &port, 5, MODE_OUTPUT);
show(ddr, port);Expected output:
ddr=0x20 port=0x00Input with pull-up
uint8_t ddr = 0xFF, port = 0x00;
gpio_configure(&ddr, &port, 0, MODE_INPUT_PULLUP);
show(ddr, port);Expected output:
ddr=0xFE port=0x01Learn 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.
- 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.