Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 37 ยท Debugging, Testing and Low Power

Testing Embedded Code

Learn how to test firmware without hardware: separate logic from hardware, write host-side unit tests, use a fake HAL to test drivers, and know when to use simulators and hardware-in-the-loop.

"It works on my desk" is not a test plan. Firmware bugs reach customers in devices that are hard or impossible to update, so testing matters even more than for a web page. The trouble is that flashing a board, pressing a button and watching an LED is slow, manual and cannot be repeated in a continuous integration pipeline. The solution is to design the code so that most of it can be tested on your PC, in milliseconds, and to keep the part that really needs the hardware small.

This lesson shows how: separate logic from hardware, test with a tiny framework, replace the hardware with a fake, and then use higher test levels (simulators and hardware-in-the-loop) for what remains.

The test pyramid for firmware

flowchart TD
    A["Many: host unit tests (pure logic, state machines, parsers)"] --> B["Some: driver tests with a fake HAL"]
    B --> C["Fewer: simulator / emulator tests (QEMU, Renode)"]
    C --> D["Few: hardware-in-the-loop and system tests on the real board"]

Lower levels are fast and cheap. Push as much checking as possible toward the top.

The levels:

  1. Host unit tests. Compile your logic with a normal compiler (gcc, clang) and run it on the PC. Fast enough to run on every save.
  2. Driver tests with a fake HAL. The driver talks to an abstract hardware interface; the test supplies a fake one.
  3. Simulation. QEMU, Renode or a vendor simulator runs the real firmware binary on a virtual chip, including peripherals and sometimes multiple boards.
  4. Hardware-in-the-loop (HIL). The real board connects to a test rig that drives its inputs (voltages, buttons, serial data) and reads its outputs automatically. Slow and expensive, so reserve it for what only real hardware can show: timing, analog behavior, power.

Design for testability

Code is hard to test when main.c pokes registers everywhere. Three habits fix that:

  • Layers. Keep application logic (state machines, protocol parsers, control algorithms) free of hardware headers. Only a thin hardware abstraction layer (HAL) touches registers.
  • Dependencies passed in. A driver receives its I2C or time source as a parameter (a struct of function pointers) instead of calling a global function. In tests, you pass a fake.
  • Pure functions where possible. A function that depends only on its arguments and returns a value is the easiest thing to test: no setup, no cleanup.

A tiny test framework

You do not need a big framework to start; real ones (Unity, CppUTest, Ceedling, GoogleTest for C++) add features like test discovery and nicer reports, but the core is a few macros that count passes and failures and print the line of any failure.

The example tests an ADC scaling function. The first version contains a classic embedded bug: it multiplies a 16-bit value before dividing, and the intermediate result is truncated. The test suite catches it as soon as it checks a mid-range and a maximum value.

C A mini unit-test framework catches a truncation bug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first version's failures are intended: the point of a test is to fail loudly when the code is wrong. Without the test, the bug would show up as a display reading 3% instead of 100% on a bench, or worse, in the field. Good test practice for such functions includes the boundaries (0, the maximum, one below the maximum), typical values and invalid inputs.

Testing a driver with a fake HAL

A driver that reads a temperature sensor over I2C touches hardware, but the logic inside it (converting raw bytes into degrees, handling a failed read) is not hardware-specific. If the driver calls the bus through a function pointer, the test can substitute a fake that returns scripted bytes, simulates a NACK, and records which address and register were used (a spy).

C Test a temperature driver against a fake I2C bus

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

On the real board you would pass a hal_t whose i2c_read calls the vendor driver. The driver code is identical in both cases, so the logic you tested on the PC is the logic that runs on the chip. This idea (dependency injection through function pointers) is also how mocking frameworks like CMock work: they generate fake implementations of your headers.

Fake, stub, mock, spy. A stub returns canned values; a fake is a working simplified implementation (an in-memory flash); a mock checks that expected calls happened; a spy records calls for later checking. You rarely need to worry about the exact names, but know that you can test both what a function returns and what it does to its collaborators.

Things that need more than unit tests

  • Interrupts and concurrency. Test the logic of an ISR's work as a plain function; test races with stress tests, long soak runs and tools such as thread sanitizers on the host. Careful design (see volatile and shared data) is better than testing alone.
  • Timing. Use an oscilloscope or logic analyzer, a cycle counter, or HIL tests. Host tests can use a fake clock to make time-dependent code (timeouts, debouncing) deterministic: advance the clock by hand.
  • Analog behavior and power. Needs real measurements.
  • Integration. Test the whole firmware image on a simulator or the target; run the same suite for each release.

Static analysis, coverage and CI

  • Compile with -Wall -Wextra -Wconversion and fix warnings; use clang-tidy and cppcheck, and the sanitizers (-fsanitize=address,undefined) on host tests.
  • Measure code coverage (gcov) on host tests. Do not chase 100%, but look at uncovered branches in error handling: they are where bugs hide.
  • Run the host tests and static analysis in continuous integration on every commit. Build the firmware for the target in the same pipeline, so a change that compiles for the PC but breaks the board is caught.
  • Keep test hooks out of the way: avoid #ifdef TEST in production logic. Pass in dependencies instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of host-side unit tests for firmware?

    Logic compiled for the PC gives immediate, repeatable feedback and works in CI.
  2. 2. What does a fake HAL allow you to do?

    The test supplies scripted data and failures and can check which addresses and registers the driver used.
  3. 3. Why did the first percent function fail for 4095?

    409500 needs more than 16 bits; casting to uint16_t cut it down to a wrong value.
  4. 4. Which kind of problem is best found by hardware-in-the-loop tests rather than host tests?

    Host tests cannot see real signal timing or analog behavior; a physical rig can.

Summary

  • Separate hardware-independent logic from a thin HAL so most code builds and runs on the PC.
  • A few macros are enough to start unit testing; frameworks like Unity and CppUTest add structure.
  • Pass dependencies such as the bus or clock into drivers (function-pointer structs) so tests can substitute fakes, stubs, mocks and spies.
  • Use simulators and hardware-in-the-loop for integration, timing and analog behavior, and run static analysis, sanitizers and coverage in CI.

Next: Low-Power Design