Try Embedded

Driver design: HAL versus bare metal

Layering a driver so it is testable, portable and still fast.

Two ways to talk to a peripheral

Bare metal means writing the peripheral's registers yourself, from the reference manual. A HAL (hardware abstraction layer) is a library, usually from the vendor (STM32 HAL, nRF SDK/nrfx, MCUXpresso SDK), that wraps the registers in functions such as HAL_UART_Transmit().

Bare metalVendor HAL
Speed of writingSlow: you read the manualFast: call a function
Code size and cyclesMinimalLarger; generic code checks many cases
ControlTotalWhat the API exposes
Portability across vendorsNoneNone (each vendor's HAL differs)
Portability within a familyLowGood
BugsYoursSometimes the vendor's, and harder to see

In practice, products mix them: the HAL or vendor LL (low-layer) drivers for set-up and rarely-used peripherals, and direct register access in the few hot paths (a fast ISR, a bit-banged protocol). What matters more than the choice is your own layering above it.

Layering

+-------------------------------------------+
| Application: what the product does        |
+-------------------------------------------+
| Device drivers: TMP117, W25Q flash, LCD   |  talk to chips, using...
+-------------------------------------------+
| Peripheral interface: i2c_*, spi_*, gpio_* |  your small, stable API
+-------------------------------------------+
| Vendor HAL / LL / registers               |  replaceable
+-------------------------------------------+

The key line is the peripheral interface: a small API you own. The temperature-sensor driver calls i2c_write_read(), not HAL_I2C_Mem_Read(). Then:

  • moving to another MCU means rewriting one thin layer, not every device driver
  • device drivers can be unit-tested on a PC against a fake I2C implementation
  • the vendor HAL's quirks are contained in one place

A peripheral interface in C

An interface can be a set of functions (chosen at link time) or a struct of function pointers (chosen at run time). The function-pointer form allows several buses and easy test doubles:

#include <stdio.h>
#include <stdint.h>

/* The interface: what a sensor driver needs from an I2C bus. */
typedef struct i2c_bus {
  int (*write_read)(struct i2c_bus *bus, uint8_t addr,
                    const uint8_t *tx, int tx_len, uint8_t *rx, int rx_len);
  void *ctx;
} i2c_bus_t;

/* A device driver written only against the interface. */
#define TMP117_ADDR   0x48
#define TMP117_TEMP   0x00
static int tmp117_read_centi(i2c_bus_t *bus, int32_t *out) {
  uint8_t reg = TMP117_TEMP, raw[2];
  int err = bus->write_read(bus, TMP117_ADDR, &reg, 1, raw, 2);
  if (err) return err;
  int16_t counts = (int16_t)((raw[0] << 8) | raw[1]);
  *out = (int32_t)counts * 78125 / 100000;     /* 7.8125 m°C per LSB, in centi-degrees */
  return 0;
}

/* A fake bus for testing on a PC: returns canned bytes. */
static int fake_write_read(i2c_bus_t *bus, uint8_t addr,
                           const uint8_t *tx, int tx_len, uint8_t *rx, int rx_len) {
  (void)bus; (void)tx; (void)tx_len; (void)rx_len;
  if (addr != TMP117_ADDR) return -1;          /* NACK */
  rx[0] = 0x0C; rx[1] = 0x80;                  /* 0x0C80 = 3200 counts = 25.00 °C */
  return 0;
}

int main(void) {
  i2c_bus_t fake = { fake_write_read, NULL };
  int32_t centi;
  if (tmp117_read_centi(&fake, &centi) == 0)
    printf("temperature = %d.%02d C\n", centi / 100, centi % 100);
  return 0;
}

On the target, a second write_read implementation wraps the HAL or the registers. The TMP117 driver does not change.

Driver design checklist

  • Init separate from construction. An explicit xxx_init() called in a known order, after clocks are up.
  • Return status, never hang. Every wait on hardware has a timeout. A missing sensor must not freeze the product.
  • Non-blocking where it matters. Offer an interrupt- or DMA-driven API with a completion callback for anything slow; a blocking 10 ms flash erase in the main loop stalls everything else.
  • Thread safety stated. Either the driver takes a mutex internally, or the documentation says the caller must serialise access. Shared buses (I2C, SPI) are the usual source of trouble.
  • No hidden global state. Instance data in a struct passed to every call, so two identical sensors on two buses work.
  • Power states. suspend() and resume() for low-power modes.
  • Error counters. NACKs, timeouts and CRC failures counted per instance, readable for diagnostics.

Register access done well

When you go bare metal, use the vendor's CMSIS device header for register definitions rather than hand-typed addresses, and keep read-modify-write explicit:

/* Configure PA5 as an output: MODER field 5 = 01 */
GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER5_Msk) | (1u << GPIO_MODER_MODER5_Pos);

/* Set and clear atomically through BSRR: no read-modify-write, safe from interrupts */
GPIOA->BSRR = GPIO_BSRR_BS5;     /* set */
GPIOA->BSRR = GPIO_BSRR_BR5;     /* reset */

Many vendors also offer an "LL" (low-layer) API: static inline functions that compile to the same single register access but with readable names. They are a good middle ground.

Pitfall: A HAL's blocking calls often have a "timeout" parameter in milliseconds that relies on SysTick. Calling them from an interrupt with a higher priority than SysTick means the tick never advances and the timeout never expires.

Interview question: HAL or bare metal for a new product: what would you choose and why?

Answer: Usually both, deliberately. Use the vendor HAL or LL drivers to get peripherals working quickly and for rarely-touched set-up code, but hide them behind a small peripheral interface the project owns, so device drivers and application code never include vendor headers. Drop to direct register access where profiling shows it matters, such as a high-rate ISR, or where the HAL lacks a feature. This gets the schedule benefits of the HAL while keeping portability, testability and control.

Interview question: How would you make a sensor driver unit-testable on a PC?

Answer: Write it against an abstract bus interface, either a struct of function pointers or a set of functions resolved at link time, that covers only what it needs (write, read, write-then-read). In the test build, link a fake implementation that records the bytes written and returns scripted responses, including errors such as NACKs and timeouts. Keep timing behind an interface too (a get_time and delay function the test controls). Then tests can check register sequences, conversions and error handling without hardware.

Build it: a temperature sensor driver you can unit-test

This is step 1 of the module project, a smart thermostat. Its temperature sensor driver will be reused on three boards with different I2C hardware, and it must be tested on a PC before any board exists. So the driver never touches registers: it talks to the bus through an interface it is given.

Lab: A sensor driver behind a bus interface

The sensor is a TMP117-style digital thermometer. The driver gets a bus_t: a function pointer that reads registers, plus a context pointer it passes back unchanged. On the thermostat it is the real I2C driver; in the checks it is a fake bus that plays the sensor, including its failures.

The sensor's registers:

RegisterContents
0x0F device ID2 bytes, must read 0x0117
0x00 temperature2 bytes, a signed 16-bit value, 7.8125 m°C per bit (1/128 °C)

All values arrive most significant byte first.

  • tmp_init(dev, bus) stores the bus in the device and reads the ID. It returns TMP_OK, TMP_ERR_BUS if the read fails, or TMP_ERR_ID if the ID is wrong. Only after TMP_OK is the device usable (dev->ready).
  • tmp_read_centi(dev, out) reads the temperature and stores it in hundredths of a degree, rounded toward zero: raw * 100 / 128. It returns TMP_ERR_NOT_READY on a device that was never initialised successfully, TMP_ERR_BUS if the read fails (leaving *out unchanged), else TMP_OK.

Going deeper

Interview question: How would you write a humidity sensor driver so the product can switch to a cheaper sensor later?

Answer: Give the application a small interface (init, start a measurement, read the result, report errors) and hide the bus, registers and conversions behind it. The new sensor is a new implementation of the same interface, chosen at build time or detected at start-up. Make the driver non-blocking and testable with a fake bus.

Interview question: How would you make one driver serve two identical peripherals, such as UART1 and UART2?

Answer: Keep all per-instance state in a struct (register base address, buffers, callbacks, error counters) and pass a pointer to it to every driver function, with the instance's interrupt handler forwarding to a common function with the right struct. Instances come from a static array or are provided by the caller. No driver state lives in file-scope globals except the instance table.

Interview question: Should a driver's API be blocking or non-blocking?

Answer: Offer both where it matters. A blocking call with a timeout is simplest for initialisation and for tasks in an RTOS, which can block cheaply. A non-blocking call that starts an interrupt- or DMA-driven transfer and reports completion through a callback, flag or semaphore is needed in super-loop firmware and for long operations, so other work continues. Document which context each function may be called from.

Explain it: In your own words, explain why device drivers should call your own peripheral interface rather than the vendor HAL directly.

Answer: If a sensor driver calls the vendor's HAL, it is tied to that vendor's chip family and cannot run anywhere else, including on a PC for unit tests. Calling a small interface that the project owns, such as i2c_write_read, means only one thin layer touches vendor code. Moving to a different MCU means rewriting that layer, the sensor drivers can be tested on a PC against a fake bus, and quirks of the vendor library stay contained in one place.