Simvik

A driver and its interface: led.h and led.c

Split an LED driver into the header the application includes and the source file that keeps the register work to itself. A medium embedded C problem (Driver…

medium · Driver design: HAL versus bare metal · driver · gpio · headers

A board's status LED is on PA5, lit while the pin is high. Write its driver as two files, the way a firmware project keeps one:

  • led.h, the interface: everything the application may use, and nothing else. Declare led_state_t, an enum with LED_OFF (0) and LED_ON (1), and these functions:
  • void led_init(void): makes PA5 an output with the LED off, changing no other pin.
  • void led_set(led_state_t state)
  • void led_toggle(void)
  • led_state_t led_get(void): what the LED shows now.
  • led.c, the implementation, which includes led.h and does the register work.

The tests include led.h and call only what it declares, so anything else in led.c stays private to it. The application includes led.h from more than one of its own headers, so it needs an include guard.

Every change of an output pin shows up in the output as gpioa: pin 5 high.

Starter code

// ===== led.h =====
// led.h: the LED driver's interface.
// Declare led_state_t and the four functions the application calls, inside an include guard.

// ===== led.c =====
#include "led.h"

// The LED driver. PA5 drives the LED; high is on.

Example tests

On, then toggled off

led_init();
led_set(LED_ON);
printf("%d\n", led_get());
led_toggle();
printf("%d\n", led_get());

Expected output:

gpioa: pin 5 high
1
gpioa: pin 5 low
0

Learn it first

More Driver design: HAL versus bare metal problems