Simvik

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:

0xFFFFF7FF

Alternate function on PA0

GPIOA->MODER = 0x00000000;
gpio_set_mode(GPIOA, 0, 2);
printf("0x%08X\n", GPIOA->MODER);

Expected output:

0x00000002

Learn 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