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. Declareled_state_t, an enum withLED_OFF(0) andLED_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 includesled.hand 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
0Learn it first
- Driver design: HAL versus bare metal · Layering a driver so it is testable, portable and still fast.
More Driver design: HAL versus bare metal problems
- One interface, two sensors · Put two temperature sensor drivers behind one ops table so the application does not care which chip is fitted.
- A non-blocking driver · Start a conversion and poll for it, with a timeout, instead of waiting in a loop.
- Retries, backoff and bus recovery · Decide which bus errors to retry, how long to wait, and when to recover a stuck bus.