Working with vendor SDKs and HALs
SDK layers, generated code, HAL handles, status codes and callbacks, and when to go below the HAL.
Most firmware is built on someone else's code
Very few products write every driver from the register level. A job usually starts with the silicon vendor's SDK: STM32Cube for ST, ESP-IDF for Espressif, the nRF Connect SDK (built on Zephyr) for Nordic, MCUXpresso for NXP, the Pico SDK for Raspberry Pi. Knowing how these are put together, what the generated code does and where the traps are is as much part of the job as knowing C.
The layers of an SDK
| Layer | What it is | Example |
|---|---|---|
| CMSIS-Core | Arm's core definitions: NVIC, SysTick, intrinsics such as __disable_irq() | core_cm4.h |
| Device header | Every peripheral register as a struct, every bit as a macro | stm32f4xx.h, nrf52840.h |
| Low-level drivers (LL) | Thin inline functions, one or two register accesses each | LL_GPIO_SetOutputPin() |
| HAL | Portable, handle-based drivers with blocking, interrupt and DMA variants | HAL_UART_Transmit_DMA() |
| Middleware | USB stacks, file systems, TCP/IP, RTOS, crypto | TinyUSB, FatFs, lwIP, FreeRTOS, mbedTLS |
| Configuration | A tool that picks pins and clocks and generates init code | STM32CubeMX, idf.py menuconfig, devicetree and Kconfig |
Use the highest layer that meets your timing and size needs, and drop to LL or registers only where it does not: a 1 MHz control loop or an interrupt handler that the HAL makes too slow.
Generated code
Configuration tools write main.c and init files for you. In STM32CubeMX projects, code between /* USER CODE BEGIN */ and /* USER CODE END */ markers survives regeneration; anything outside them is overwritten the next time someone changes a pin. Common practices:
- Commit the configuration file (
.ioc) and the generated code, and regenerate only deliberately, reviewing the diff. - Keep your own code in your own files and call it from the user sections, so the generated files stay thin.
- Never hand-edit a generated clock or pin setting without changing the configuration file too; the next regeneration silently reverts it.
How a HAL is used
A HAL driver works on a handle, a struct holding the peripheral's base address, its configuration and its state, and every call returns a status:
UART_HandleTypeDef huart2; /* filled in by the generated MX_USART2_UART_Init() */
if (HAL_UART_Transmit(&huart2, msg, len, 100) != HAL_OK) { /* 100 ms timeout */
/* HAL_ERROR, HAL_BUSY or HAL_TIMEOUT: decide what to do, do not ignore it */
}
Most drivers come in three forms: blocking with a timeout (HAL_UART_Receive), interrupt (_IT) and DMA (_DMA). The non-blocking forms report completion through callbacks that the HAL declares as weak functions; you override them by defining a function with the same name:
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
/* runs in interrupt context: store the byte, re-arm reception, return */
}
The status codes have to be mapped onto your application's own errors somewhere. Doing it in one wrapper keeps HAL types out of the rest of the code and makes it testable on a PC:
#include <stdio.h>
#include <stdint.h>
/* The shape of a vendor HAL's status codes. */
typedef enum { HAL_OK = 0, HAL_ERROR = 1, HAL_BUSY = 2, HAL_TIMEOUT = 3 } HAL_StatusTypeDef;
/* The application's own errors: what the rest of the firmware sees. */
typedef enum { APP_OK, APP_RETRY_LATER, APP_NO_DEVICE, APP_FAULT } app_err_t;
static app_err_t from_hal(HAL_StatusTypeDef s) {
switch (s) {
case HAL_OK: return APP_OK;
case HAL_BUSY: return APP_RETRY_LATER; /* the peripheral is mid-transfer */
case HAL_TIMEOUT: return APP_NO_DEVICE; /* nothing answered in time */
case HAL_ERROR: return APP_FAULT; /* bus error, NACK, overrun... */
default: return APP_FAULT; /* never trust an enum from outside */
}
}
int main(void) {
const char *names[] = { "ok", "retry later", "no device", "fault" };
for (int s = 0; s <= 4; s++) printf("HAL status %d -> %s\n", s, names[from_hal((HAL_StatusTypeDef)s)]);
return 0;
}
The same applies to ESP-IDF's esp_err_t (use ESP_ERROR_CHECK, which aborts, only for start-up code that cannot fail gracefully) and to Zephyr's negative errno returns, where a driver's device_is_ready() must be checked before use.
The traps
- Peripheral clocks. On STM32, nothing works until its clock is on (
__HAL_RCC_GPIOA_CLK_ENABLE()); writes to an unclocked peripheral are silently ignored. Generated code does this; hand-written code often forgets. - Callbacks run in interrupt context. No
HAL_Delay, no blocking calls, no long work. A receive callback must usually re-arm the next reception, or only the first byte ever arrives. HAL_Delayand the tick. The HAL's millisecond tick comes from an interrupt (SysTick or a timer). CallingHAL_Delayfrom an interrupt of equal or higher priority waits forever, because the tick cannot advance.- Locking is not thread safety. The HAL's internal
__HAL_LOCKonly rejects overlapping calls withHAL_BUSY; it is not an RTOS mutex. Two tasks sharing a handle still need a mutex around it. HAL_MAX_DELAYas a timeout means "block forever if the hardware never answers". Use real timeouts outside start-up code.- Errata. The chip's errata sheet lists hardware bugs and workarounds. Check it when a peripheral misbehaves, and check whether the SDK version you use already applies the workaround.
Pin the SDK version, read its source when its behaviour surprises you (it is just C), and treat an SDK upgrade as a planned change with its own testing.
Pitfall: Debugging for a day why a peripheral "does nothing", when its clock was never enabled, or its pins were never switched to the alternate function. Check clocks and pin muxing first.
Interview question: When would you use the vendor HAL, and when would you go to the register level?
Answer: Use the HAL by default: it is tested, portable across the vendor's chip families, handles many errata and gets a product working quickly. Go to LL functions or registers where the HAL costs too much: tight loops and fast interrupt handlers where its overhead and generality add latency, very small flash budgets, or features the HAL does not expose. Even then, wrap that code behind the same driver interface as the rest, and keep the HAL for initialisation if it helps. Reading the HAL's source is the quickest way to see which registers it actually touches.
Build it: keep the vendor's SDK out of the application
This is step 4 of the module project. The sensor uses the chip vendor's HAL to talk to its accelerometer. Next year the board moves to a cheaper chip from another vendor. If HAL types and status codes are spread through the application, that move means a rewrite. So the HAL is wrapped once, in a thin adapter, and nothing else includes it.
Lab: A thin adapter over a vendor HAL
The vendor's I2C call is provided (a fake that plays the bus):
HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *h, uint16_t dev_addr, uint16_t reg, uint16_t reg_size, uint8_t *data, uint16_t size, uint32_t timeout_ms);
Two of its quirks are classic: dev_addr is the 7-bit address shifted left by one, and it returns HAL_BUSY when the bus is still in use by an earlier transfer, which usually clears if you simply try again.
Write the application's own interface on top of it:
sensor_bus_read(addr7, reg, buf, n)readsnbytes using the one handlehi2c1, a 1-byte register address and a 10 ms timeout. It retries aHAL_BUSYresult up to 2 more times (3 attempts in all), and maps the result to the application's own codes:HAL_OK→BUS_OK,HAL_TIMEOUT→BUS_TIMEOUT,HAL_BUSY(still, after the retries) →BUS_BUSY, and anything else →BUS_ERROR. Out-of-range arguments (addr7above0x7F,nof 0) returnBUS_ERRORwithout calling the HAL.bus_error_name(e)returns the code's name for logs:"ok","timeout","busy","error", or"?"for an unknown value.
Going deeper
Interview question: How would you use a chip vendor's SDK for a Wi-Fi plug without being trapped by its bugs?
Answer: Use the SDK for what it does well (Wi-Fi stack, drivers), but wrap it behind your own interfaces so the application never calls it directly. Pin its version, track its errata and issues, keep your patches in your repository, and keep the option of moving to another chip.
Interview question: A UART receives exactly one byte using HAL_UART_Receive_IT, then nothing more. What is wrong?
Answer: HAL_UART_Receive_IT arms reception for a fixed number of bytes; when they arrive the HAL disables the receive interrupt and calls HAL_UART_RxCpltCallback. If the callback does not call HAL_UART_Receive_IT again to re-arm, no further bytes are received. The fix is to store the byte in a buffer and re-arm in the callback, and also to handle HAL_UART_ErrorCallback, since an overrun or framing error stops reception too and must be re-armed after clearing the error.
Interview question: How do you keep a vendor HAL from spreading through your whole codebase?
Answer: Put a thin layer of your own driver interfaces between the application and the HAL: functions or ops tables named for what the product needs (sensor_read, uart_send), using your own types and error codes. Only the implementation files include HAL headers and convert HAL status codes. The application and its tests then compile on a PC against fakes, and moving to another chip or SDK changes only that layer. Keep the layer thin; the point is a boundary, not a second HAL.
Explain it: In your own words, explain the layers of a typical vendor SDK and how you decide which to use.
Answer: At the bottom, CMSIS gives the processor core definitions and the device header names every register. Above it, low-level drivers wrap single register operations, and the HAL offers portable, handle-based drivers with blocking, interrupt and DMA versions that report through status codes and callbacks. Middleware adds stacks such as USB, file systems and TCP/IP, and a configuration tool generates the init code for pins and clocks. I use the highest layer that meets the timing and size needs, drop lower only for hot paths, and keep everything behind my own interfaces so the application does not depend on the vendor's types.