Modular Driver Architecture in Firmware: A How-To Guide
In this article
To implement a modular driver architecture in your firmware, define a hardware abstraction layer (HAL) interface for each peripheral class, implement each driver as a self-contained module that registers itself with a central driver manager, and keep all hardware-specific details behind that interface so the core application never touches registers directly. This achieves portability across boards, easier testing, and the ability to add or swap drivers without rewriting application code. Before starting, you need a working firmware project with a build system (Make, CMake, or your IDE's project), a basic understanding of function pointers and structs in C or C++, and at least two target boards or a board plus a simulator to validate portability.
What You'll Need
- A C or C++ firmware project that compiles and runs on at least one target.
- A build system that supports per-module compilation (Make, CMake, or vendor IDE).
- Version control (Git) to track changes safely.
- Datasheets or reference manuals for each peripheral you will abstract.
- A second board or a host-based simulator for testing portability.
- Optional: a unit-test framework that runs on your host PC (e.g., Unity, CMocka).
Step-by-Step
- Inventory your hardware dependencies. List every direct register access, vendor HAL call, and pin definition in your current code. Group them by peripheral: GPIO, UART, SPI, I2C, ADC, timers, flash, etc. This list becomes your interface specification.
- Define a HAL interface for each peripheral class. Create a header file per class, e.g.,
hal_uart.h. Inside, declare an opaque handle type and a struct of function pointers for operations: init, write, read, and any control functions. Example:typedef struct { int (*init)(void *ctx, uint32_t baud); int (*write)(void *ctx, const uint8_t *data, size_t len); } hal_uart_ops_t;. Keep the interface minimal—only what the application actually uses. - Implement a driver module for each hardware variant. For each board or chip, create a source file that implements the function pointers using the vendor's HAL or direct registers. The module should expose a single registration function, e.g.,
uart_stm32f4_register(void), that fills in the ops struct and stores it in a global driver table. Do not expose hardware details in the header. - Create a driver manager. Write a small central file that holds an array or linked list of registered drivers per peripheral class. Provide functions like
hal_uart_get(uint8_t instance)that return the ops struct for a given instance. The manager should support static registration at compile time (via linker sections) or dynamic registration at startup. - Refactor application code to use the HAL. Replace all direct hardware calls with calls through the ops struct. For example, instead of
HAL_UART_Transmit(&huart1, ...), callhal_uart_get(0)->write(ctx, data, len). Pass the driver's context pointer (which can hold the vendor handle) as the first argument. - Add a board support package (BSP) layer. Create a
bsp.cfor each board that calls the registration functions for the drivers that board uses and configures pins and clocks. The application main should callbsp_init()before using any HAL functions. This keeps board-specific setup out of the application. - Set up conditional compilation or build flags. Use your build system to include only the driver modules needed for a given target. For example, in CMake, add source files per target:
target_sources(firmware PRIVATE drivers/uart_stm32f4.c). Avoid#ifdefspaghetti in shared code; keep selection in the build. - Write tests for the HAL interfaces. Create mock implementations of the ops structs that record calls or return canned data. Use these to unit-test application logic on your host PC without hardware. This is where the modular design pays off—you can test without a board.
- Validate on hardware. Build for each target, flash, and run a smoke test that exercises each peripheral. Check that the correct driver is selected (e.g., print the driver name at startup). Compare behavior against the pre-refactor firmware.
- Document the interface and registration process. Write a short README for each HAL class explaining how to add a new driver: implement the ops struct, write a register function, add the source file to the build, and call the register function from the BSP. This ensures future maintainers follow the pattern.
Common Mistakes
- Leaking hardware details into the interface. If your HAL header includes vendor headers or exposes register addresses, you have not abstracted anything. Keep the interface pure C types and opaque pointers.
- Over-abstracting. Creating a generic interface for every possible feature leads to bloated ops structs and complex code. Start with the operations you need today; add more when required.
- Forgetting the context pointer. Each driver instance needs its own state (e.g., which UART peripheral). Pass a
void *ctxto every operation and store per-instance data in a struct that the driver casts. - Static registration without a fallback. If a driver fails to register, the application may crash on a null pointer. Add a check in the driver manager that returns an error or a default no-op driver.
- Mixing board setup with application logic. Pin configuration and clock enabling belong in the BSP, not in
main(). Otherwise, porting to a new board requires editing application code. - Ignoring build system integration. Manually adding files to an IDE project works until you switch environments. Use a portable build system and keep driver selection in build files.
Tips
- Start with one peripheral class (e.g., GPIO) to prove the pattern, then expand.
- Use a consistent naming convention:
hal_<class>_<operation>for interface functions,<class>_<platform>_<operation>for driver implementations. - Keep the driver manager small—it should only store and retrieve ops structs, not contain logic.
- Use linker sections for automatic registration if your toolchain supports it; this avoids manual registration lists.
- Write a mock driver for each interface and use it in unit tests and on host builds.
- Version your HAL interfaces; when you change an interface, update all drivers in the same commit.
Troubleshooting
- Driver not found at runtime. Check that the registration function is called from the BSP and that the driver source is included in the build for that target. Add a startup log that prints registered drivers.
- Hardware behaves differently after refactor. Compare the driver implementation against the original code line by line. Common issues: wrong clock enable, missing volatile qualifier on registers, or incorrect context pointer casting.
- Build fails with multiple definitions. Ensure each driver's registration function has a unique name and that headers only declare, not define, variables. Use
staticfor internal functions. - Unit tests pass but hardware fails. The mock may not replicate timing or hardware quirks. Add integration tests on hardware and check for race conditions in the driver manager if used from interrupts.
- Porting to a new board is still hard. If you find yourself editing application code, the abstraction is incomplete. Identify the leaked hardware dependency and move it behind the HAL.
Frequently Asked Questions
Do I need C++ to implement a modular driver architecture?
No. The pattern works in plain C using structs of function pointers and opaque handles. C++ can offer virtual interfaces, but it is not required and may add overhead on small MCUs.
How do I handle interrupts in a modular design?
Keep interrupt service routines (ISRs) in the driver module. The driver can call a callback registered by the application through the HAL interface, or set a flag that the application polls. Avoid calling application code directly from the ISR unless it is designed for it.
Can I use this architecture with an RTOS?
Yes. The HAL interface is independent of the scheduling model. Drivers can block, use semaphores, or be non-blocking; document the behavior in the interface. The driver manager should be thread-safe if accessed from multiple tasks.
What if my vendor HAL already provides abstraction?
Vendor HALs abstract registers but not boards or chips from different vendors. Your modular layer sits on top, allowing you to swap vendor HALs or write bare-metal drivers without changing application code.
How many drivers should I register at once?
Register only the drivers needed for the current board configuration. Unused drivers waste flash and RAM. Use build flags to include only what is necessary.
Is it worth modularizing a small project?
If the project will ever run on more than one board or be maintained long-term, yes. The upfront cost is small compared to the rework saved when hardware changes.