Configure a pin mode
Write a 2-bit mode field for one pin of a port. A medium embedded C problem (Registers and memory-mapped I/O), run and graded in the browser.
medium · Registers and memory-mapped I/O · gpio · fields
MODER holds a 2-bit mode for each pin: pin n uses bits 2n+1 and 2n. The modes are 0 = input, 1 = output, 2 = alternate function, 3 = analog.
Set the mode of pin pin (0 to 15) to the low two bits of mode. The modes of all other pins must not change.
Starter code
void gpio_set_mode(gpio_t *port, uint8_t pin, uint8_t mode) {
// Replace the 2-bit field for `pin` in port->MODER.
}Example tests
Make PA5 an output
GPIOA->MODER = 0xFFFFFFFF;
gpio_set_mode(GPIOA, 5, 1);
printf("0x%08X\n", GPIOA->MODER);Expected output:
0xFFFFF7FFAlternate function on PA0
GPIOA->MODER = 0x00000000;
gpio_set_mode(GPIOA, 0, 2);
printf("0x%08X\n", GPIOA->MODER);Expected output:
0x00000002Learn it first
- Registers, volatile and const · How C talks to hardware: memory-mapped registers, what volatile and const promise, register structs and read-modify-write.
More Registers and memory-mapped I/O problems
- Drive a GPIO pin · Set or clear one pin in a port's output data register.
- Read a GPIO pin · Report the level on one input pin.
- Atomic pin write · Change a pin with a single write to the bit set/reset register.
- Hygienic register macros · Fix four bit-manipulation macros that break on compound arguments.
- Clear a write-1-to-clear flag · Acknowledge one interrupt flag without wiping the others.
- Poll with a timeout · Wait for a status bit, but never forever.
- UART baud-rate divisor · Compute the divisor that gives the closest baud rate.
- PWM compare value · Convert a duty cycle in percent to a timer compare value.
- Lay out a register map · Declare a peripheral struct whose members land on the right offsets.
- ADC conversion sequence · Write a 5-bit channel number into a computed slot of a register.
- Read a split counter · Read a 32-bit count from two 16-bit halves that keep changing.
- Fix: disabling one interrupt silences the timers · Clearing one bit of an interrupt-enable register clears every bit below it as well.
- Infusion pump: read the pressure, with a timeout · Start a conversion, poll its done flag, and give up safely if the converter never answers.