Simvik

An LED and a button, from the board schematic

The schematic decides which level lights the LED and which level means pressed. Write the three functions that hide it. An easy embedded C problem (Reading…

easy · Reading datasheets and schematics · schematics · gpio · driver

Board revision B has a status LED and a user button. Working from the Datasheet excerpt below, write:

  • io_init(), which makes the LED's pin an output with the LED off, and the button's pin an input. Change no other pin.
  • led_set(on), which lights the LED when on is 1 and turns it off when it is 0.
  • button_pressed(), which returns 1 while SW1 is held down and 0 otherwise.

Every change of an output pin shows up in the output as gpiob: pin 3 high.

Datasheet excerpt

Board schematic, sheet 3 (user I/O)

3V3 ──[R7 330 Ω]──►|── PB3        D2: green LED, anode towards R7
                   D2

3V3 ──[R9 10 kΩ]──┬── PB4
                  │
                  └──o  o── GND   SW1: push button, normally open

GPIO registers (reference manual)

OffsetRegisterPin y occupiesValues
0x00MODERbits 2y+1:2y00 input, 01 output
0x0CPUPDRbits 2y+1:2y00 none, 01 pull-up, 10 pull-down
0x10IDRbit ythe level on the pin (read-only)
0x18BSRRbit y sets pin y, bit y+16 clears itwrite-only

Starter code

void io_init(void) {
  GPIOB->MODER |= 1u << 6;    // PB3 output
}

void led_set(int on) {
  GPIOB->BSRR = on ? 1u << 3 : 1u << 19;
}

int button_pressed(void) {
  return (GPIOB->IDR >> 4) & 1;
}

Example tests

Press, light, release, dark

io_init();
button(0);
printf("%d\n", button_pressed());
led_set(1);
button(1);
printf("%d\n", button_pressed());
led_set(0);

Expected output:

gpiob: pin 3 high
0
gpiob: pin 3 low
1
gpiob: pin 3 high

Learn it first

More Reading datasheets and schematics problems