---
title: Testing embedded code
heading: Checking firmware without waiting for the hardware
eyebrow: C12 · Lesson 50 · Testing embedded code
xp: 40
---

::: hook
Firmware is hard to test the obvious way: the hardware may not exist yet, a bug might take a week of field use to appear, and watching LEDs by eye catches only the crudest failures. Professional embedded teams test most of their code without any hardware at all. They keep the logic (debouncing, parsing, control math, state machines) apart from the few lines that touch registers, so the logic can be run thousands of times with chosen inputs, on a computer or on the board itself, and checked automatically. What's left for the real hardware is a thin layer, and a final test with the device in the loop.
:::

::: play
- The program is its own test suite: a tiny `CHECK` macro runs each test case and records failures, then the program prints the number of tests and the number that failed.
- The functions under test never touch a register: `clamp`, a checksum, and a debouncer that takes one raw sample at a time and returns the accepted level. That's what makes them testable with made-up inputs.
- Break one: change `clamp`'s `<` to `<=`, or the debouncer's `3` to `2`, and run again. The failing tests print their numbers.
:::
:::

```sim board
lang: c
run: 10 ms
code:
#include "board.h"

// ---- the logic under test: no registers anywhere
int clamp(int x, int lo, int hi) {
    if (x < lo) return lo;
    if (x > hi) return hi;
    return x;
}

uint8_t checksum(const uint8_t *data, int n) {
    uint8_t sum = 0;
    for (int i = 0; i < n; i++) sum += data[i];
    return sum;
}

// Accept a new level after 3 equal samples in a row.
struct debouncer { int stable, candidate, count; };
int debounce(struct debouncer *d, int raw) {
    if (raw == d->stable) { d->count = 0; return d->stable; }
    if (raw != d->candidate) { d->candidate = raw; d->count = 0; }
    if (++d->count >= 3) { d->stable = raw; d->count = 0; }
    return d->stable;
}

// ---- a tiny test framework
int tests = 0, failures = 0;
#define CHECK(id, cond) do { tests++; if (!(cond)) { failures++; print(-(id)); } } while (0)

int main(void) {
    CHECK(1, clamp(5, 0, 10) == 5);
    CHECK(2, clamp(-3, 0, 10) == 0);
    CHECK(3, clamp(10, 0, 10) == 10);
    CHECK(4, clamp(11, 0, 10) == 10);

    uint8_t frame[4] = {200, 100, 50, 6};
    CHECK(5, checksum(frame, 4) == 100);      // 356 wraps to 100
    CHECK(6, checksum(frame, 0) == 0);

    struct debouncer d = {1, 1, 0};
    int bounce[8] = {0, 1, 0, 0, 0, 1, 1, 1};
    int seen[8];
    for (int i = 0; i < 8; i++) seen[i] = debounce(&d, bounce[i]);
    CHECK(7, seen[1] == 1 && seen[3] == 1);  // not yet: no 3 in a row
    CHECK(8, seen[4] == 0);                   // three 0s: accepted
    CHECK(9, seen[7] == 1);                   // three 1s: back up

    print(tests);
    print(failures);
    return 0;
}
```

::: predict
## A function has two independent `if` statements, each of which can go either way. How many different paths through it does a thorough test cover?

- [ ] 2
- [ ] 3
- [x] 4
- [ ] 8

::: reveal
4: each `if` doubles the paths, $2^2$. With k independent decisions there are $2^k$ paths, which is why testing every path quickly becomes impossible and why tests concentrate on boundaries and on each decision going both ways.
:::
:::

::: nameit
## Separate logic from hardware

Write the decisions and calculations as plain functions that take values and return values. A thin **hardware layer** reads the pins and registers and calls them. The logic can then be tested:

- on a computer, compiled for it, with a normal test framework, in milliseconds;
- on the board, as the play does, with no peripherals involved;
- with **fakes**: stand-ins for the hardware layer that return scripted values and record what was written.

## Choosing test cases

- **Typical** values, to show it works at all.
- **Boundaries:** for a range lo..hi, test lo − 1, lo, hi and hi + 1, where off-by-one errors live.
- **Each decision both ways**, and each state machine transition (every state × event pair, lesson 36).
- **Errors:** empty input, overflow (the checksum's wrap), a missing device.
- **Regressions:** each fixed bug gets a test, so it stays fixed.

## The rest

**Hardware-in-the-loop** tests run the real firmware on a real board, driven by a test fixture that simulates the world (buttons, sensors, a serial terminal) and checks the outputs; this course's board and its scripted devices work exactly that way. And `assert`-style checks left in the firmware catch impossible conditions in the field, logging them before a watchdog reset.
:::

::: example
## Choose test inputs for `clamp(x, 0, 100)`.

::: solution
1. **A typical value.** 50.
2. **The boundaries.** −1, 0, 100 and 101.
3. **Far outside.** −30000 and 30000.
4. **Write down the expected results.**

| Input | Expected |
|---|---|
| 50 | 50 |
| −1 | 0 |
| 0 | 0 |
| 100 | 100 |
| 101 | 100 |
| −30000 | 0 |
| 30000 | 100 |

5. **What they catch.** Seven tests, each a single line, catch both the off-by-one and the wrong-direction comparison.

**Answer:** 50, −1, 0, 100, 101, −30000 and 30000, expecting 50, 0, 0, 100, 100, 0 and 100.
:::
:::

::: example
## A state machine has 5 states and 4 events. How many transition tests cover it fully, and how long do they take at 2 ms each?

::: solution
1. **Count the pairs.**
   $$5 \times 4 = 20$$
   (state, event) pairs, including the ones that should do nothing.
2. **Time them.**
   $$20 \times 2\ \text{ms} = 40\ \text{ms}$$
3. **Compare with doing it by hand.** Run on every build, that's free; done by hand on a board with buttons, it's a tedious afternoon.

**Answer:** 20 tests, taking 40 ms.
:::
:::

::: example
## Choose boundary tests for a function that converts a 12-bit ADC code to millivolts.

::: solution
1. **Pick the edges and their neighbors.** 0, 1, 2047, 2048, 4094 and 4095, plus a value or two in between.
2. **Overflow at the top.** Overflow bugs show up at 4095: does 4095 × 3300 fit in the arithmetic used?
3. **Off-by-one at the bottom.** Off-by-one errors show up at 0 and 1.
4. **Sign in the middle.** Sign mistakes show up around the middle if any signed arithmetic is involved.

**Answer:** 0, 1, 2047, 2048, 4094 and 4095, plus a value or two in between.
:::
:::

::: check
given: k = 3 | 4 | 5 | 8
answer: 2^k
tolerance: 0

## A function makes {k} independent yes-or-no decisions. How many paths does it have?

::: right
Right. $2^{\given{k}}$ = {answer}.
:::

::: misses
- [2*k] Each decision doubles the paths; it doesn't add two.
- [k + 1] That's how many tests it takes to make each decision go both ways (roughly), not the number of paths.
- [any] Not yet. $2^k$.
:::
:::

::: check
given: r = 1 | 2 | 3
answer: 4*r
tolerance: 0

## A function checks {r} separate ranges, and each needs the four boundary tests (lo − 1, lo, hi, hi + 1). How many boundary tests is that?

::: right
Right. {answer}.
:::

::: misses
- [any] Not yet. Four per range.
:::
:::

::: check
given: s = 4 | 6 | 10; e = 3 | 5
answer: s*e
tolerance: 0

## A state machine has {s} states and {e} events. How many tests cover every transition, including the ones that should do nothing?

::: right
Right. {answer}.
:::

::: misses
- [any] Not yet. One per (state, event) pair.
:::
:::

::: check
given: n = 200 | 1000 | 5000; t = 0.5 | 3 | 20
answer: n*t/1000
unit: s
tolerance: 0.5%

## A test suite has {n} tests taking {t} ms each. How long does it take to run?

::: right
Right. {answer} s.
:::

::: misses
- [any] Not yet. Tests times time each.
:::
:::

::: check
given: a = 30 | 45 | 80; b = 40 | 50
answer: 100*a/(a + b)
unit: %
tolerance: 0.5%

## Tests exercise {a} of a program's branches; {b} branches are never reached. What's the branch coverage?

::: right
Right. {answer}%.
:::

::: misses
- [100*a/b] Coverage is out of all the branches: covered plus missed.
- [any] Not yet. Covered over total.
:::
:::

::: check
kind: choice

## Why does the play's debouncer take one sample at a time and return a level, instead of reading the pin itself?

- [ ] It's faster
- [x] So tests can feed it any sequence of samples, without a real button
- [ ] Because C functions can't read registers
- [ ] To save memory

::: misses
- [1] Speed isn't the reason.
- [3] They can; the play's other code does.
- [4] It makes no difference to memory.
:::
:::

::: check
kind: c
run: 0.01
expect: print = 5, 0

## The tests below check an `average` of `uint8_t` values, and two fail. Fix `average` (not the tests) so all five pass; the program prints the number of tests and of failures.

```c starter
#include "board.h"

uint8_t average(const uint8_t *v, int n) {
    uint8_t sum = 0;
    for (int i = 0; i < n; i++) sum += v[i];
    return sum / n;
}

int tests = 0, failures = 0;
#define CHECK(cond) do { tests++; if (!(cond)) failures++; } while (0)

int main(void) {
    uint8_t a[3] = {10, 20, 30}, b[4] = {200, 220, 240, 250}, c[1] = {7}, d[2] = {255, 255}, e[2] = {1, 2};
    CHECK(average(a, 3) == 20);
    CHECK(average(b, 4) == 227);
    CHECK(average(c, 1) == 7);
    CHECK(average(d, 2) == 255);
    CHECK(average(e, 2) == 1);
    print(tests);
    print(failures);
    return 0;
}
```

```c solution
#include "board.h"

uint8_t average(const uint8_t *v, int n) {
    uint32_t sum = 0;
    for (int i = 0; i < n; i++) sum += v[i];
    return sum / n;
}

int tests = 0, failures = 0;
#define CHECK(cond) do { tests++; if (!(cond)) failures++; } while (0)

int main(void) {
    uint8_t a[3] = {10, 20, 30}, b[4] = {200, 220, 240, 250}, c[1] = {7}, d[2] = {255, 255}, e[2] = {1, 2};
    CHECK(average(a, 3) == 20);
    CHECK(average(b, 4) == 227);
    CHECK(average(c, 1) == 7);
    CHECK(average(d, 2) == 255);
    CHECK(average(e, 2) == 1);
    print(tests);
    print(failures);
    return 0;
}
```

::: right
Right: an 8-bit sum overflows; a 32-bit one doesn't. The tests found it before any hardware did.
:::
:::

::: check
kind: micropython
run: 0.01
expect: print = "6 passed"

## Write `in_range(x, lo, hi)`, true when lo ≤ x ≤ hi, so that the six tests pass.

```micropython starter
def in_range(x, lo, hi):
    return lo < x < hi

tests = [((5, 0, 10), True), ((0, 0, 10), True), ((10, 0, 10), True),
         ((-1, 0, 10), False), ((11, 0, 10), False), ((3, 4, 4), False)]
passed = sum(1 for args, want in tests if in_range(*args) == want)
print('%d passed' % passed)
```

```micropython solution
def in_range(x, lo, hi):
    return lo <= x <= hi

tests = [((5, 0, 10), True), ((0, 0, 10), True), ((10, 0, 10), True),
         ((-1, 0, 10), False), ((11, 0, 10), False), ((3, 4, 4), False)]
passed = sum(1 for args, want in tests if in_range(*args) == want)
print('%d passed' % passed)
```

::: right
Right. The boundary tests (0 and 10) are the ones the first version failed.
:::
:::

::: check
kind: parts
given: s = 3 | 5 | 8; e = 2 | 4 | 6; t = 2 | 10

## A state machine has {s} states and {e} events; each test takes {t} ms.

::: part
answer: s*e
tolerance: 0

### How many tests cover every state-event pair?

::: misses
- [any] States × events.
:::
:::

::: part
answer: s*e*t
unit: ms
tolerance: 0.5%

### How long do they take?

::: misses
- [any] Tests × time each.
:::
:::
:::

::: check
kind: parts
given: N = 8 | 10 | 12

## A function takes an {N}-bit unsigned input.

::: part
answer: 2^N
tolerance: 0

### How many inputs would an exhaustive test try?

::: misses
- [any] $2^N$.
:::
:::

::: part
answer: 2^N - 1
tolerance: 0

### What is the largest input, the one that most often reveals an overflow?

::: misses
- [any] $2^N - 1$.
:::
:::
:::

::: explain
## Why do embedded teams separate logic from hardware access, even though it adds a layer?

::: model
Code that reads registers can only be run on the real chip with the real devices attached, at the speed the world produces inputs, which makes it slow and awkward to test and nearly impossible to test exhaustively. When the decisions and calculations are plain functions of their inputs, they can be run thousands of times with chosen inputs (boundaries, rare sequences, errors) on a computer or on the board, checked automatically in seconds on every change. The hardware layer left over is thin and simple enough to check by hand and with a few hardware-in-the-loop tests. The extra function call costs a few cycles; finding a bug before it ships saves far more.
:::
:::

::: practice

::: check
given: k = 2..12 int
answer: 2^k
tolerance: 0

## Paths through {k} independent decisions?

::: misses
- [any] $2^k$.
:::
:::

::: check
given: s = 3 | 8; e = 2 | 7
answer: s*e
tolerance: 0

## Transition tests for {s} states and {e} events?

::: misses
- [any] s × e.
:::
:::

::: check
given: a = 60 | 90; b = 15 | 30
answer: 100*a/(a + b)
unit: %
tolerance: 0.5%

## Coverage with {a} branches hit and {b} missed?

::: misses
- [any] a / (a + b).
:::
:::
:::
