---
title: "Embedded lab: systems that last"
heading: Battery budgets, control loops, flash wear and watchdogs, in Python and C
eyebrow: C12 · Lesson 47 · Embedded lab
xp: 50
---

::: hook
The last part of the course is about devices that keep working: for a year on a coin cell, through a power cut, with a loop that holds its set point and a watchdog that catches a hang. Each of those properties is a number you can compute before building anything: an average current, an overshoot, an erase count, a reset time. This lab writes the models in Python, and then runs the integer PI controller from the control lesson on the board to check that it behaves exactly like the model.
:::

::: play
- The curve is a PI loop's step response on the control lesson's plant (τ = 20 ms, gain 1) with $K_p$ = 2, computed in continuous time: $y = 1 - e^{-\sigma t}\left(\cos\omega_d t + \frac{\sigma - K_p/\tau}{\omega_d}\sin\omega_d t\right)$, with $\sigma = (1 + K_p)/2\tau$ and $\omega_d = \sqrt{K_i/\tau - \sigma^2}$.
- Raise $K_i$: the loop settles on the set point faster at first but overshoots more.
- The lab simulates the same loop sampled every millisecond. Its overshoot is larger (9.6% against 7.9% here at $K_i$ = 200, 24.5% against 19.6% at 400): the sample delay costs phase, just as the control lesson predicted.
:::

```sim plot
view: graph
x: t = 0..150 ms
y: y = 0..1.4
slider: K = 150..600 step 50 = 200
samples: 600
plot: 1 - exp(-75*t/1000)*(cos(sqrt(K/0.02 - 5625)*t/1000) + (75 - 100)/sqrt(K/0.02 - 5625)*sin(sqrt(K/0.02 - 5625)*t/1000)) | label: output
plot: 1 + 0*t | dashed | label: set point
```

::: predict
## A sensor node draws 2 µA asleep and wakes for 50 ms every 10 s at 2.05 mA. How long does a 220 mAh coin cell last?

- [ ] About 4 days
- [ ] About 3 months
- [x] About 2 years
- [ ] About 20 years

::: reveal
The average is $0.002 \times 9.95/10 + 2.05 \times 0.05/10 = 0.0122$ mA, so $220/0.0122 = 17\,970$ hours, about 749 days. The waking adds 84% of the average; shortening it matters more than lowering the sleep current further. (Real cells also self-discharge, about 1% a year for lithium coin cells, and lose capacity in the cold.)
:::
:::

::: nameit
## The models

| Property | Model |
|---|---|
| Battery life | average current = $\sum I_k t_k/\sum t_k$; life = capacity ÷ average |
| Loop response | $y_{n+1} = ay_n + bu_n$ with $a = e^{-T_s/\tau}$, $b = 1 - a$, under PI control with an output limit |
| Flash wear | a log moving through sectors, erasing each only when it's reused |
| Watchdog | a reset whenever the gap since the last kick exceeds the timeout |

Each takes a few lines, and each answers a question that would take days or months to answer by watching hardware.
:::

::: check
kind: python

## Write `battery_days(states, capacity_mah)`: `states` is a list of (current in mA, seconds) making up one repeating cycle. Return (average current in mA, life in days).

```python starter
def battery_days(states, capacity_mah):
    return (0.0, 0.0)
```

```python solution
def battery_days(states, capacity_mah):
    total = sum(t for _, t in states)
    avg = sum(i * t for i, t in states) / total
    return (avg, capacity_mah / avg / 24)
```

```python tests
avg, days = battery_days([(0.002, 9.95), (2.05, 0.05)], 220)
assert abs(avg - 0.01224) < 1e-6, "2 µA asleep, 2.05 mA for 50 ms of every 10 s: 12.2 µA."
assert abs(days - 748.9) < 0.1, "About 749 days on 220 mAh."
avg, days = battery_days([(0.5, 0.98), (5.0, 0.02)], 1000)
assert abs(avg - 0.59) < 1e-9 and abs(days - 70.62) < 0.01, "0.59 mA average: 70.6 days on 1000 mAh."
```

::: right
Right. Listing the states one by one is how real power budgets are built, usually in a spreadsheet with the datasheet's currents.
:::
:::

::: check
kind: python

## Write `simulate_pi(kp, ki, tau, ts, n, umax=None)`: a unit step into the plant $y_{n+1} = ay_n + bu_n$ ($a = e^{-T_s/\tau}$, $b = 1 - a$, y starting at 0) under PI control: $e = 1 - y$, $u = K_pe + I$, limited to `umax` if given; then $I \mathrel{+}= K_iT_se$, except when the output is limited and $e > 0$. Return the n outputs. Then `overshoot(ys)` in percent (0 if none) and `settle_index(ys, tol=0.02)`: the first index from which every output is within `tol` of 1, or `None`.

```python starter
import math

def simulate_pi(kp, ki, tau, ts, n, umax=None):
    return [1.0] * n

def overshoot(ys):
    return 0.0

def settle_index(ys, tol=0.02):
    return 0
```

```python solution
import math

def simulate_pi(kp, ki, tau, ts, n, umax=None):
    a = math.exp(-ts / tau)
    b = 1 - a
    y, integ, ys = 0.0, 0.0, []
    for _ in range(n):
        e = 1.0 - y
        u = kp * e + integ
        limited = umax is not None and u > umax
        if limited:
            u = umax
        if not (limited and e > 0):
            integ += ki * ts * e
        y = a * y + b * u
        ys.append(y)
    return ys

def overshoot(ys):
    return max(0.0, (max(ys) - 1) * 100)

def settle_index(ys, tol=0.02):
    for i in range(len(ys)):
        if all(abs(v - 1) <= tol for v in ys[i:]):
            return i
    return None
```

```python tests
ys = simulate_pi(2, 200, 0.02, 0.001, 400)
assert abs(overshoot(ys) - 9.615) < 0.01 and settle_index(ys) == 49, "Ki = 200: 9.6% overshoot, settled from sample 49."
ys = simulate_pi(2, 400, 0.02, 0.001, 400)
assert abs(overshoot(ys) - 24.52) < 0.01 and settle_index(ys) == 53, "Ki = 400: 24.5%, sample 53."
ys = simulate_pi(2, 400, 0.02, 0.001, 400, umax=1.5)
assert abs(overshoot(ys) - 7.165) < 0.01 and settle_index(ys) == 43, "Limited to 1.5 with conditional integration: 7.2%, sample 43."
```

::: right
Right. The limit with conditional integration overshoots far less than the unlimited loop: the integrator didn't wind up while the output was held.
:::
:::

::: check
kind: python

## Write `log_wear(saves, sectors, per_sector)`: records are appended to a log that starts in sector 0, all sectors erased. When the current sector is full, move to the next (wrapping to 0), erasing it first if it holds old records. Return each sector's erase count after `saves` records.

```python starter
def log_wear(saves, sectors, per_sector):
    return [saves // per_sector] * sectors
```

```python solution
def log_wear(saves, sectors, per_sector):
    erases = [0] * sectors
    used = [0] * sectors
    cur = 0
    for _ in range(saves):
        if used[cur] == per_sector:
            cur = (cur + 1) % sectors
            if used[cur]:
                erases[cur] += 1
                used[cur] = 0
        used[cur] += 1
    return erases
```

```python tests
assert log_wear(1000, 4, 100) == [2, 2, 1, 1], "Ten sectors' worth over four: the first two have been erased twice."
assert log_wear(400, 4, 100) == [0, 0, 0, 0], "Exactly full: nothing erased yet."
assert log_wear(4000, 8, 64) == [7, 7, 7, 7, 7, 7, 7, 6], "Wear stays within one erase across sectors."
```

::: right
Right. The counts never differ by more than one: the log spreads wear evenly without any extra bookkeeping.
:::
:::

::: check
kind: python

## Write `wdt_reset(kicks, timeout)`: a watchdog starts at time 0 and resets the device if `timeout` seconds pass without a kick. `kicks` are the times of kicks. Return the time of the first reset before the last kick, or `None` if every gap is short enough.

```python starter
def wdt_reset(kicks, timeout):
    return None
```

```python solution
def wdt_reset(kicks, timeout):
    last = 0.0
    for k in sorted(kicks):
        if k - last > timeout:
            return last + timeout
        last = k
    return None
```

```python tests
assert wdt_reset([0.05, 0.1, 0.15], 0.1) is None, "Every gap is 50 ms: no reset."
assert abs(wdt_reset([0.05, 0.1, 0.25], 0.1) - 0.2) < 1e-12, "A 150 ms gap: reset at 0.2 s."
assert abs(wdt_reset([0.2], 0.1) - 0.1) < 1e-12, "The first kick came too late: reset at 0.1 s."
```

::: right
Right. Run it on kick times logged from a real loop to see how much margin the timeout really has.
:::
:::

::: check
kind: c
run: 0.01
expect: print = 630, 110, 0

## Run the integer PI controller on the board: `kp_q8` = 192, `ki_q16` = 131, output limits 0 and 1000, with the accumulator updated by `ki_q16 * e` only when that doesn't push a limited output further into its limit. Feed it 20 errors of 800, then 20 of 100, then 20 of −50, and print the outputs for the 20th, 40th and 60th.

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

int main(void) {
    print(0);
    print(0);
    print(0);
    return 0;
}
```

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

int32_t acc = 0;

int pi_step(int e) {
    int raw = ((192 * e) >> 8) + (acc >> 16);
    int u = raw;
    if (u > 1000) u = 1000;
    if (u < 0) u = 0;
    if (!((raw >= 1000 && e > 0) || (raw <= 0 && e < 0)))
        acc += 131 * e;
    return u;
}

int main(void) {
    for (int i = 0; i < 60; i++) {
        int e = i < 20 ? 800 : i < 40 ? 100 : -50;
        int u = pi_step(e);
        if (i == 19 || i == 39 || i == 59)
            print(u);
    }
    return 0;
}
```

::: right
Right. 630, 110 and 0, the same as the Python model: the shifts of negative numbers round down in both.
:::
:::

::: explain
## Why does a PI loop with an output limit and conditional integration overshoot less than the same loop with no limit at all?

::: model
Without a limit, the controller's large initial output drives the plant hard, and the integrator keeps accumulating the error during the rise, so by the time the output reaches the set point the integrator holds far more than it needs and pushes the output past it. With a limit, the output is held at the maximum during the rise, and conditional integration stops the integrator from growing while the output is limited and the error still pushes the same way. The integrator only starts to act once the output comes off the limit, close to the set point, so it holds much less excess and the overshoot is smaller, at the cost of a slightly slower rise.
:::
:::
