---
title: Watchdogs and robust firmware
heading: Recovering from the bugs you didn't find
eyebrow: C12 · Lesson 41 · Watchdogs and robust firmware
xp: 40
---

::: hook
Firmware runs for years without anyone watching, through electrical noise, brownouts and the one input sequence nobody tested. Sooner or later something makes it hang: a loop waiting for a device that never answers, a corrupted pointer, a deadlock. A **watchdog timer** is the last line of defense: a hardware countdown the program must restart ("kick") regularly. If the program stops kicking, because it's stuck, the watchdog resets the whole chip and the device starts again. Good firmware also avoids needing it, by never waiting forever for anything.
:::

::: play
- The program kicks a 50 ms watchdog every 10 ms while it works. A planted bug makes it hang after 200 ms. It prints the watchdog's reset count each time it starts.
- Run it: it prints 0 at the start, then the hang stops the kicks, and 50 ms later the watchdog resets the board. It restarts, prints 1, and so on: four resets in a second, visible as gaps in P0's toggling.
- Delete the `if (loops == 20)` hang and run again: one start, no resets.
:::
:::

```sim board
lang: c
attach: led P0 | green
scope: P0
run: 1 s
code:
#include "board.h"

int main(void) {
    GPIO_DIR = 1;
    print(SYS_RESETS);                    // watchdog resets so far
    WDT_LOAD = 500000;                    // 50 ms
    WDT_CTRL = 1;
    uint32_t loops = 0;
    while (1) {
        GPIO_TOGGLE = 1;
        uint32_t t = SYS_CYCLES;
        while (SYS_CYCLES - t < 100000) ; // 10 ms of work
        loops++;
        if (loops == 20)                  // a bug: after 200 ms it hangs
            while (1) ;
        WDT_KICK = 0x5A;                  // still alive: restart the countdown
    }
}
```

::: predict
## A watchdog times out after 50 ms, and the program kicks it at the end of each pass of its main loop. A pass normally takes 10 ms, but occasionally 70 ms. What happens?

- [ ] Nothing: 70 ms is still short
- [x] The watchdog resets the board during the long passes
- [ ] The watchdog only counts passes, not time
- [ ] The board resets every 50 ms regardless

::: reveal
The board resets during each 70 ms pass: from the last kick, 70 ms is longer than the 50 ms timeout. The timeout must be longer than the longest legitimate gap between kicks, with margin, or the watchdog becomes the bug.
:::
:::

::: nameit
## The watchdog

A hardware counter, independent of the program, counting down from a reload value. The program writes a special value to restart it (here `WDT_KICK = 0x5A`, a value unlikely to be written by accident); if the count reaches zero, the chip resets. On this board: `WDT_LOAD` sets the timeout in cycles, `WDT_CTRL = 1` starts it, and `SYS_RESETS` counts watchdog resets, so the restarted program can tell it recovered from a hang and log it.

## Using it well

- **Timeout:** longer than the longest normal gap between kicks, with margin; shorter than the outage the device can tolerate.
- **Where to kick:** in the main loop, once every task has shown it's alive, never from a timer interrupt, which keeps running even when the main loop is stuck.
- **After a reset:** put outputs in a safe state first (heater off, motor stopped), then read the reset cause.
- **Windowed** watchdogs also reset if kicked too early, catching code that's running wild and kicking in a tight loop.

## Not needing it

- Every wait gets a timeout: `while (busy && SYS_CYCLES - start < limit)`, then handle the failure.
- Check every input's range and every function's result.
- Keep the stack well clear of other data; some systems fill it with a pattern at start-up and check how much is ever overwritten.
- A **brown-out detector** resets the chip cleanly when the supply sags, instead of letting it run on corrupt logic levels.
:::

::: example
## A main loop normally takes up to 12 ms, and the device may be out of action for at most 100 ms. Choose a watchdog timeout.

::: solution
1. **Bracket the timeout.** Anywhere comfortably above 12 ms and below 100 ms.
2. **Pick 50 ms.** That leaves a 4× margin over the longest pass and recovers within half the allowed outage.
3. **Convert to cycles.** At 10 MHz:
   $$50\ \text{ms} \times 10\ \text{MHz} = 500\,000$$
   so WDT_LOAD = 500,000.

**Answer:** 50 ms, WDT_LOAD = 500,000.
:::
:::

::: example
## Rewrite `while (!(UART_STATUS & UART_RX_READY)) ;` so it can't hang.

::: solution
1. **Give up after a time limit.** Note the cycle count when the wait starts, and return an error once 100,000 cycles (10 ms) have passed.

```c
uint32_t start = SYS_CYCLES;
while (!(UART_STATUS & UART_RX_READY))
    if (SYS_CYCLES - start > 100000) return -1;   // 10 ms: give up
```

2. **Let the caller decide.** The caller then decides what a missing byte means, instead of the whole device freezing.

**Answer:** check `SYS_CYCLES - start` inside the loop and return −1 after 10 ms.
:::
:::

::: example
## A windowed watchdog must be kicked between 5 ms and 20 ms after the last kick. What does the window catch that a plain timeout doesn't?

::: solution
1. **What a plain watchdog catches.** Only a program that stops kicking.
2. **What a window adds.** It also catches one that kicks too often, for example a runaway loop that calls the kick function repeatedly while doing nothing useful.
3. **How it acts.** Kicks closer than 5 ms reset the device as surely as a missing kick.

**Answer:** a program that kicks too often, such as a runaway loop that calls the kick function repeatedly while doing nothing useful.
:::
:::

::: check
given: t = 10 | 50 | 250 | 1000
answer: t*10000
tolerance: 0

## What WDT_LOAD gives a {t} ms timeout on the 10 MHz board?

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

::: misses
- [t*10] That's microseconds' worth: 10,000 cycles per millisecond.
- [any] Not yet. Cycles per ms times {t}.
:::
:::

::: check
given: w = 100 | 200 | 400; T = 20 | 50; s = 1 | 3
answer: floor(s*1000/(w + T))
tolerance: 0

## A program hangs {w} ms after every start, and its watchdog resets it {T} ms after the last kick (at the hang). How many resets happen in {s} s?

::: right
Right. A cycle every {w} + {T} ms: {answer} resets.
:::

::: misses
- [any] Not yet. Count whole cycles of start-to-reset.
:::
:::

::: check
given: g = 8 | 15 | 30; m = 2 | 4
answer: g*m
unit: ms
tolerance: 0.5%

## The longest normal gap between kicks is {g} ms. With a {m}× margin, what timeout?

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

::: misses
- [any] Not yet. Gap times margin.
:::
:::

::: check
given: b = 9600 | 115200; n = 1 | 4 | 20; m = 2
answer: m*n*10/b*1e6
unit: µs
tolerance: 0.5%

## A program waits for {n} bytes at {b} baud, with a timeout of {m} times the time they should take. What timeout is that?

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

::: misses
- [any] Not yet. {m} × {n} bytes × 10 bits ÷ baud.
:::
:::

::: check
given: k = 2 | 20 | 100; r = 50 | 300 | 2000
answer: 100*k*r/1000/86400
unit: %
tolerance: 1%

## A fault makes a device reset {k} times a day, and each reset leaves it out of action for {r} ms while it restarts. What percentage of the time is it out of action?

::: right
Right. {answer}%: small, but each outage still has to be safe.
:::

::: misses
- [any] Not yet. Total outage per day over the 86,400 s in a day.
:::
:::

::: check
kind: choice

## Where should a program kick its watchdog?

- [ ] In a 1 ms timer interrupt, so it's never late
- [x] In the main loop, after confirming each task has made progress
- [ ] At the start of main only
- [ ] Inside every function

::: misses
- [1] The timer keeps interrupting even if the main loop is stuck, so the watchdog never fires.
- [3] Then it resets after one timeout.
- [4] A hang inside one function's loop would still be kicking if that loop calls the others.
:::
:::

::: check
kind: c
attach: terminal
run: 0.05
expect: print = -1; ends

## This program waits for a byte from the terminal, which never sends one, so it hangs. Give the wait a 10 ms timeout: print the byte if it comes, or -1 if it doesn't, and return.

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

int main(void) {
    UART_BAUDDIV = 87;
    while (!(UART_STATUS & UART_RX_READY)) ;
    print(UART_DATA);
    return 0;
}
```

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

int get_byte(uint32_t timeout) {
    uint32_t start = SYS_CYCLES;
    while (!(UART_STATUS & UART_RX_READY))
        if (SYS_CYCLES - start > timeout) return -1;
    return UART_DATA;
}

int main(void) {
    UART_BAUDDIV = 87;
    print(get_byte(100000));
    return 0;
}
```

::: right
Right. The caller learns the byte never came, and the program carries on.
:::
:::

::: check
kind: micropython
run: 1
expect: print = "boot"; resets = 0

## Start a watchdog with a 100 ms timeout, then run the loop below for the whole second without being reset.

```micropython starter
from machine import WDT, Pin
import time

print('boot')
w = WDT(timeout=100)
led = Pin(0, Pin.OUT)
while True:
    led.toggle()
    time.sleep_ms(20)
```

```micropython solution
from machine import WDT, Pin
import time

print('boot')
w = WDT(timeout=100)
led = Pin(0, Pin.OUT)
while True:
    led.toggle()
    w.feed()
    time.sleep_ms(20)
```

::: right
Right: fed every 20 ms, the 100 ms watchdog never expires, and `boot` prints once.
:::
:::

::: check
kind: parts
given: L = 5 | 12 | 40; O = 100 | 500

## A main loop takes up to {L} ms, and the device may be out of action for at most {O} ms.

::: part
answer: L
unit: ms
tolerance: 0.5%

### What is the shortest safe watchdog timeout?

::: misses
- [any] At least the loop's longest pass.
:::
:::

::: part
answer: O
unit: ms
tolerance: 0.5%

### What is the longest allowed?

::: misses
- [any] The allowed outage.
:::
:::
:::

::: check
kind: parts
given: a = 5 | 10; b = 20 | 50; k = 2 | 8 | 30

## A windowed watchdog must be kicked between {a} ms and {b} ms after the last kick. A loop kicks every {k} ms.

::: part
answer: step(k - a)*step(b - k)
tolerance: 0

### Is that inside the window (1 for yes)?

::: misses
- [any] It must be no sooner than {a} ms and no later than {b} ms.
:::
:::

::: part
answer: b - a
unit: ms
tolerance: 0.5%

### How wide is the window?

::: misses
- [any] Late limit less early limit.
:::
:::
:::

::: explain
## Why kick the watchdog from the main loop rather than from a timer interrupt?

::: model
The watchdog's job is to detect that the program has stopped doing its work. A timer interrupt keeps firing on schedule even when the main loop is stuck in an endless wait or a corrupted loop, because interrupts preempt the stuck code, so kicking from there would keep the watchdog satisfied forever while the device does nothing useful. Kicking from the main loop, ideally only after checking that each task has run since the last kick, ties the kicks to real progress: if any part of the program stalls, the kicks stop and the reset happens.
:::
:::

::: practice

::: check
given: t = 10 | 30 | 100 | 250 | 500 | 1000 | 2000
answer: t*10000
tolerance: 0

## WDT_LOAD for {t} ms?

::: misses
- [any] 10,000 cycles per ms.
:::
:::

::: check
given: w = 150 | 600; T = 25 | 100; s = 2 | 5
answer: floor(s*1000/(w + T))
tolerance: 0

## Resets in {s} s: hang after {w} ms, timeout {T} ms?

::: misses
- [any] Whole cycles of w + T.
:::
:::

::: check
given: g = 5 | 40; m = 3 | 5
answer: g*m
unit: ms
tolerance: 0.5%

## Timeout for a {g} ms gap with {m}× margin?

::: misses
- [any] g × m.
:::
:::
:::
