---
title: "Embedded lab: registers and timing"
heading: Register fields, timer settings, baud rates, debouncing and capture, in C and Python
eyebrow: C12 · Lesson 15 · Embedded lab
xp: 50
---

::: hook
Firmware engineers write a surprising amount of code that never runs on the target: scripts that work out timer settings, check baud-rate errors, decode register dumps, and replay captured signals through the same logic the firmware uses, to see what it would have done. This lab writes those tools in Python for the first part of the course (register fields, timers, the UART's divisor, debouncing and input capture) and then measures a button press on the board itself in C.
:::

::: play
- The board measures how long the button on P4 is held, timing the press with the free-running cycle counter, and prints it in milliseconds.
- The button is pressed from 0.1 s to 0.35 s, and the program prints 250.
- The timeline shows the pin going low and high again; the print happens at the release.
:::

```sim board
lang: c
attach: button P4 | press 0.1..0.35 s
scope: P4
run: 0.5 s
code:
#include "board.h"

int main(void) {
    GPIO_PULLUP = 1 << 4;
    while (GPIO_IN & (1 << 4)) ;        // wait for the press (active low)
    uint32_t t0 = SYS_CYCLES;
    while (!(GPIO_IN & (1 << 4))) ;     // wait for the release
    uint32_t t1 = SYS_CYCLES;
    print((t1 - t0 + 5000) / 10000);    // cycles to milliseconds, rounded
    return 0;
}
```

::: predict
## The program above times a press with a 32-bit cycle counter at 10 MHz. What's the longest press it can time correctly?

- [ ] 65.5 ms
- [ ] 6.55 s
- [x] About 7 minutes
- [ ] Any length

::: reveal
$2^{32}$ cycles at 10 MHz is 429 s, about 7 minutes. Unsigned subtraction gives the right answer across one wrap of the counter, but not two. A 16-bit timer at 10 MHz would wrap every 6.55 ms, far too short for a person.
:::
:::

::: nameit
## The tools

| Task | Inputs | Output |
|---|---|---|
| Register fields | a register value, a field's position and width | the field, or the register with a new field |
| Timer settings | a wanted frequency | PRESCALE, TOP and the frequency they really give |
| Baud rates | the wanted rates | BAUDDIV and each rate's error |
| Debouncing | sampled pin levels | the presses a counter debouncer accepts |
| Capture | captured 16-bit counts | the periods between them |

Each is a few lines of Python, and each mirrors code from the earlier lessons, so the same logic can be checked on a laptop before it's trusted on the board.
:::

::: check
kind: python

## Write `get_field(reg, pos, width)` and `set_field(reg, pos, width, value)` for 32-bit registers. `set_field` replaces the field and leaves every other bit alone, and raises `ValueError` if the value doesn't fit in the field.

```python starter
def get_field(reg, pos, width):
    return 0

def set_field(reg, pos, width, value):
    return reg
```

```python solution
def get_field(reg, pos, width):
    return (reg >> pos) & ((1 << width) - 1)

def set_field(reg, pos, width, value):
    if value < 0 or value >= (1 << width):
        raise ValueError('value does not fit')
    mask = ((1 << width) - 1) << pos
    return (reg & ~mask & 0xFFFFFFFF) | (value << pos)
```

```python tests
assert get_field(0x3A54, 4, 4) == 5, "Bits 4 to 7 of 0x3A54 are 0101."
assert set_field(0x3A54, 4, 4, 0xC) == 0x3AC4, "Replace them with 1100: 0x3AC4."
assert set_field(0xFFFFFFFF, 28, 4, 0) == 0x0FFFFFFF, "Clear the top nibble only."
assert get_field(0x80000000, 31, 1) == 1, "The top bit."
try:
    set_field(0, 0, 3, 8)
    assert False, "8 doesn't fit in 3 bits: raise ValueError."
except ValueError:
    pass
```

::: right
Right. Checking the value's range catches a whole class of bugs where a too-large value spills into the neighboring field.
:::
:::

::: check
kind: python

## Write `timer_settings(f, f_clk=10_000_000)`: the timer wraps at $f_\text{clk}/((P + 1)(T + 1))$, with PRESCALE P and TOP T each from 0 to 65535. Return (P, T, actual frequency) for the settings closest to f, choosing the smallest P among equally close ones (it gives the finest resolution).

```python starter
def timer_settings(f, f_clk=10_000_000):
    return (0, 0, 0.0)
```

```python solution
def timer_settings(f, f_clk=10_000_000):
    best = None
    for p in range(65536):
        t1 = round(f_clk / ((p + 1) * f))
        if t1 < 1:
            break
        if t1 > 65536:
            continue
        actual = f_clk / ((p + 1) * t1)
        err = abs(actual - f)
        if best is None or err < best[2] - 1e-12:
            best = (p, t1 - 1, err, actual)
    return (best[0], best[1], best[3])
```

```python tests
assert timer_settings(1000)[:2] == (0, 9999), "1 kHz: no prescaler, TOP = 9999."
assert timer_settings(1)[:2] == (159, 62499), "1 Hz needs a prescaler: 160 × 62,500."
assert timer_settings(50)[:2] == (3, 49999), "50 Hz: the smallest exact prescaler is 4."
p, t, a = timer_settings(440)
assert (p, t) == (0, 22726) and abs(a - 440.0053) < 1e-3, "440 Hz can't be exact: 22,727 cycles give 440.005 Hz."
```

::: right
Right. A search over the prescaler is quick, and it finds the exact settings whenever they exist.
:::
:::

::: check
kind: python

## Write `baud_table(rates, f_clk=10_000_000)`: for each rate, BAUDDIV = the nearest whole number to $f_\text{clk}/\text{rate}$. Return a list of (rate, BAUDDIV, error in percent), where the error is (actual − wanted)/wanted × 100.

```python starter
def baud_table(rates, f_clk=10_000_000):
    return []
```

```python solution
def baud_table(rates, f_clk=10_000_000):
    out = []
    for b in rates:
        div = round(f_clk / b)
        out.append((b, div, (f_clk / div - b) / b * 100))
    return out
```

```python tests
t = baud_table([9600, 115200, 921600])
assert [r[1] for r in t] == [1042, 87, 11], "Divisors 1042, 87 and 11."
assert abs(t[1][2] - (-0.2235)) < 1e-3, "115,200 baud is 0.22% slow."
assert abs(t[2][2] - (-1.357)) < 1e-3, "921,600 baud is 1.36% slow, inside the 2% budget but with little margin."
```

::: right
Right. At high rates the divisor is small, so each step of it is a large change in rate, and the error grows.
:::
:::

::: check
kind: python

## Write `debounce(samples, n)`: `samples` are a button's levels (1 released, 0 pressed) read at a fixed rate. The debouncer's state starts at the first sample and changes only after `n` samples in a row differ from it. Return how many presses (changes of state to 0) it accepts.

```python starter
def debounce(samples, n):
    return samples.count(0)
```

```python solution
def debounce(samples, n):
    state, run, presses = samples[0], 0, 0
    for s in samples[1:]:
        if s != state:
            run += 1
            if run >= n:
                state, run = s, 0
                if state == 0:
                    presses += 1
        else:
            run = 0
    return presses
```

```python tests
clean = [1] * 10 + [0] * 10 + [1] * 10
assert debounce(clean, 3) == 1, "One clean press."
bouncy = [1] * 10 + [0, 1, 0, 1, 0] + [0] * 10 + [1, 0, 1] + [1] * 10 + [0, 1] + [0] * 8 + [1] * 8
assert debounce(bouncy, 3) == 2, "Two real presses, however much they bounce."
assert debounce(bouncy, 1) == 6, "With n = 1 every bounce counts."
assert debounce([1, 0, 0, 1, 1, 0, 0, 1], 3) == 0, "Glitches shorter than n samples are ignored."
```

::: right
Right. This is the same counter debouncer as the lesson's, so recorded pin data can be replayed through it off the board.
:::
:::

::: check
kind: python

## Write `periods(captures, f_clk, bits=16)`: `captures` are successive values of a `bits`-bit capture register on the same edge. Return the periods between them in seconds, allowing for the counter wrapping between captures.

```python starter
def periods(captures, f_clk, bits=16):
    return [(b - a) / f_clk for a, b in zip(captures, captures[1:])]
```

```python solution
def periods(captures, f_clk, bits=16):
    m = 1 << bits
    return [((b - a) % m) / f_clk for a, b in zip(captures, captures[1:])]
```

```python tests
p = periods([65000, 100, 2600], 1e6)
assert abs(p[0] - 636e-6) < 1e-12, "65000 to 100 wraps: 636 counts, 636 µs."
assert abs(p[1] - 2.5e-3) < 1e-12, "100 to 2600: 2.5 ms."
assert periods([0, 255, 254], 1e3, bits=8) == [0.255, 0.255], "An 8-bit counter wraps at 256."
```

::: right
Right. Modular subtraction is the whole trick; it's what `(uint16_t)(b - a)` does in C.
:::
:::

::: check
kind: c
given: S = 0.1 | 0.2; D = 50 | 250 | 400; let E = S + D/1000
attach: button P4 | press {S}..{E} s
run: 0.7
expect: print = D

## The button on P4 (to ground) is pressed once, for {D} ms. Print how long it was held, in whole milliseconds (rounded), using the free-running `SYS_CYCLES` counter at 10 MHz.

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

int main(void) {
    GPIO_PULLUP = 1 << 4;
    print(0);
    return 0;
}
```

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

int main(void) {
    GPIO_PULLUP = 1 << 4;
    while (GPIO_IN & (1 << 4)) ;
    uint32_t t0 = SYS_CYCLES;
    while (!(GPIO_IN & (1 << 4))) ;
    uint32_t t1 = SYS_CYCLES;
    print((t1 - t0 + 5000) / 10000);
    return 0;
}
```

::: right
Right. Polling resolves the edges to a few cycles, and the unsigned subtraction survives the counter wrapping.
:::
:::

::: explain
## Why is it worth writing Python versions of firmware logic such as a debouncer, rather than only testing on the board?

::: model
On the board, a test depends on what the button, the wiring and the timing happen to do that day, and a rare bounce pattern or wrap of a counter may never show up. A Python copy of the same logic can be fed exactly the inputs you choose: recorded samples from a real button, worst cases built by hand, or millions of random sequences. The results are repeatable and fast, so bugs in the logic itself are found and fixed before the hardware is involved. Then the board test only has to confirm the hardware and timing, which is a much smaller question.
:::
:::
