Course 2 · Chapter 8 · Concurrency and Real-Time Basics
Programming for Robotics with Arduino C++ 7 gave the robot decisions, and every one of them assumed that update() would be called on time and that nothing else would get in the way. This chapter looks at what else is happening on the chip. The processor does one thing at a time, but it can be interrupted: a pin changes or a timer reaches a number, the hardware stops loop() in the middle of an instruction, runs a short function, and carries on. That is the nearest thing to concurrency an Uno has, and it brings the oldest bugs in embedded software: a variable the compiler thinks cannot change, a 32-bit number read half-way through an update, a long task that makes a short one late, a robot that hangs.
The chapter has the course’s usual habit: where it can, the claim is shown by the compiler or by a run. The disassembly of the avr-gcc compiler shows what volatile does; a simulation shows what a long Serial dump does to a 20 ms control loop, and that my own first prediction of it was wrong; a model of the watchdog shows that most of the places you could feed it do not catch the faults you wanted it for.
What was run, and what was not
Compiled for the Uno, and the machine code read (arduino-cli, core arduino:avr 1.8.8, avr-gcc 7.3, avr-objdump): the volatile and atomic-read examples, and robot_ch8.ino with its Timer1 interrupt. The instruction listings are the compiler’s own.
Run on a PC (g++ 16.2, C++11): the timer-setting calculator, the polling model, the scheduler on a virtual clock, and a model of the watchdog. The task times in the scheduler experiment are assumptions I chose; the watchdog is a software model of one, not the chip’s.
Not done: nothing was attached to a board. No interrupt latency, no execution time and no watchdog reset was measured on hardware, so the chapter counts instructions and says what they are, never microseconds of real machine time.
1. What an interrupt is, in C++ for a Python programmer
An interrupt service routine (ISR) is a function the hardware calls when an event happens, with no call in your code: ISR(INT0_vect) { ... } runs when pin 2 changes (the encoder, Programming for Robotics with Arduino C++ 4), ISR(TIMER1_COMPA_vect) when Timer1 reaches its compare value. While it runs, further interrupts are held off. It then returns to exactly where loop() was.
In Python
On the Uno in C++
threading.Thread, asyncio: the runtime switches between tasks
there is one thread; the only preemption is an ISR, and only for as long as the ISR runs
a lock (threading.Lock) protects shared data
shared data is protected by volatile and by switching interrupts off for a few instructions (section 2)
time.sleep(0.02) lets other threads run
delay() would stop the robot; time is checked against a counter (Programming for Robotics with Arduino C++ 1)
an exception, a traceback and a process that ends
a hang: the program just stops, unless a watchdog resets it (section 6)
the language runtime decides when a task runs
you decide: the ISR is hardware-timed, loop() is as late as its slowest task (section 5)
Four rules keep an ISR from doing harm; they are conventions rather than things the compiler checks. Keep it short: nothing else interrupts it, and the time it takes is added to every other task’s lateness. Do not call delay() or Serial.print() in it: millis() does not advance inside an ISR, and Serial uses interrupts itself. Do not do real work in it: count, copy, set a flag, and let loop() do the rest. Everything it shares with loop() is volatile, which is the next section.
2. volatile and atomic access, as the compiler sees them
Two bugs are the reason for the second and third rules, and the chapter does not ask you to take them on trust. The program below has a flag set by an ISR and a 32-bit counter it increments, and four functions: one that waits for the flag, one that reads the counter plainly, one that reads it inside ATOMIC_BLOCK. It was compiled twice for the Uno, once with volatile on the two variables and once without, and the machine code of the three functions was read with avr-objdump.
// s_vol.ino -- what `volatile` and an atomic block change in the machine code (Programming for Robotics with Arduino C++ 8). Compile-checked for the Uno; NOT run.
// VOL is `volatile` or nothing (-DVOL=). ATOMIC selects the guarded copy of a 32-bit counter.
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/atomic.h>
#ifndef VOL
#define VOL volatile
#endif
VOL bool g_flag = false;
VOL uint32_t g_ticks = 0;
ISR(INT0_vect) { g_flag = true; g_ticks++; }
__attribute__((noinline)) void wait_flag() { while (!g_flag) { } }
__attribute__((noinline)) uint32_t read_plain() { return g_ticks; }
__attribute__((noinline)) uint32_t read_atomic() {
uint32_t t;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { t = g_ticks; }
return t;
}
void setup() { pinMode(13, OUTPUT); EICRA = _BV(ISC00); EIMSK = _BV(INT0); }
void loop() {
wait_flag();
g_flag = false;
uint32_t a = read_plain(), b = read_atomic();
digitalWrite(13, (a ^ b) & 1);
}
The flag. Look at wait_flag(). With volatile (first listing) it loads the flag from memory, tests it, and branches back to the load: lds, and, breq .-8. Without it (second listing) the compiler reasons that nothing in this loop changes g_flag, so it needs to load it only once: lds, cpse (skip the next instruction if it is zero), and then either return or rjmp .-2, a jump to itself, for ever. The interrupt that sets the flag can run all it likes; the loop does not look. The compiler did nothing wrong: the language says a variable that nothing in the program changes does not change. volatile is how you say “something outside the program does”, and it makes no difference to the size here (894 bytes for the whole sketch with it, 896 without).
The counter. Look at read_plain() and read_atomic(). A 32-bit value on an 8-bit chip is four separate loads (lds r22, r23, r24, r25). An interrupt that fires between two of them and increments the counter leaves the copy with some bytes from before and some from after: when a byte carries (0x00FF to 0x0100) the result can be off by 256. That is the torn read of Programming for Robotics with Arduino C++ 4, now seen in the machine code. read_atomic() saves the status register, executes cli (interrupts off), loads the four bytes, and restores the status register with out 0x3f: eight instructions where the plain read has five, and no interrupt can arrive in the middle. ATOMIC_RESTORESTATE restores whatever the interrupt-enable bit was, so it is safe to call from code that already had interrupts off. Both listings are identical for the two builds, as they should be: volatile does not make a 32-bit read atomic, and an atomic block does not make a variable volatile. A single byte read (the flag) is one instruction and needs no guard; a 16-bit value is two instructions and does.
3. Hardware timers
The Uno’s ATmega328P has three timers: Timer0 (8 bit) and Timer2 (8 bit), and Timer1 (16 bit). The Arduino core already uses Timer0 for millis(), micros() and PWM on pins 5 and 6, which are the build robot’s motor speed pins (Programming for Robotics with Arduino C++ 2), so changing it would break both the clock and the motors. Timer2 drives PWM on pins 3 and 11, and Timer1 on pins 9 and 10, which the pin plan does not use, so Timer1 is the one this chapter takes. (The Servo library also takes Timer1 on the Uno; that is a documented conflict I did not test here.)
In CTC mode (clear timer on compare) a timer counts from 0 to a value OCR and starts again, firing an interrupt at each match, so the frequency is F_CPU / (prescaler × (OCR + 1)). The prescaler divides the 16 MHz clock by 1, 8, 64, 256 or 1024 (Timer2 also offers 32 and 128), and OCR is 8 or 16 bits wide. The two limits together decide which frequencies are possible and how accurate they are. The calculator is plain C++, so a PC runs it:
// timer_calc.h -- choosing a prescaler and a compare value for an AVR timer in CTC mode (Programming for Robotics with Arduino C++ 8). Plain C++11: runs on the PC.
// In CTC mode the timer counts 0..OCR and starts again, so the compare-match frequency is f = F_CPU / (prescaler * (OCR + 1)).
#pragma once
#include <stdint.h>
#include <cmath>
struct TimerPlan { bool ok; uint16_t prescaler; uint32_t ocr; double actual_hz; double error_ppm; };
// bits: 8 for Timer0/Timer2 (OCR 0..255), 16 for Timer1 (OCR 0..65535). `prescalers` lists what that timer offers.
inline TimerPlan plan_timer(double target_hz, const uint16_t* prescalers, int n, int bits, double f_cpu = 16000000.0) {
TimerPlan best = {false, 0, 0, 0.0, 1e18};
uint32_t max_ocr = bits == 8 ? 255u : 65535u;
for (int i = 0; i < n; ++i) {
double ticks = f_cpu / (prescalers[i] * target_hz); // timer counts per period
double ocr_real = ticks - 1.0;
if (ocr_real < 0.0 || ocr_real > (double)max_ocr + 0.5) continue;
uint32_t ocr = (uint32_t)std::floor(ocr_real + 0.5);
if (ocr > max_ocr) ocr = max_ocr;
double actual = f_cpu / (prescalers[i] * (double)(ocr + 1));
double err = std::fabs(actual - target_hz) / target_hz * 1e6;
if (err < best.error_ppm) { best.ok = true; best.prescaler = prescalers[i]; best.ocr = ocr; best.actual_hz = actual; best.error_ppm = err; }
}
return best;
}
// e_timer.cpp -- choosing timer settings on the host. For several wanted frequencies it finds, for Timer1 (16 bit) and Timer2 (8 bit), the prescaler and compare value
// with the smallest frequency error, and prints the frequency really produced. Then the numbers behind millis() and micros(), which run on Timer0.
#include <cstdio>
#include "timer_calc.h"
int main() {
const uint16_t P1[] = {1, 8, 64, 256, 1024}; // Timer1 and Timer0
const uint16_t P2[] = {1, 8, 32, 64, 128, 256, 1024}; // Timer2
const double targets[] = {1.0, 50.0, 440.0, 1000.0, 20000.0, 38000.0, 100000.0};
std::printf("CTC settings at 16 MHz: best prescaler and OCR per timer, and the frequency really produced\n");
std::printf(" wanted (Hz) Timer1 (16 bit): presc OCR actual (Hz) error (ppm) Timer2 (8 bit): presc OCR actual (Hz) error (ppm)\n");
for (double t : targets) {
TimerPlan a = plan_timer(t, P1, 5, 16), b = plan_timer(t, P2, 7, 8);
std::printf(" %11.0f ", t);
if (a.ok) std::printf("%21u %6lu %12.3f %12.1f ", a.prescaler, (unsigned long)a.ocr, a.actual_hz, a.error_ppm); else std::printf("%58s ", "out of range");
if (b.ok) std::printf("%20u %4lu %12.3f %12.1f\n", b.prescaler, (unsigned long)b.ocr, b.actual_hz, b.error_ppm); else std::printf("%s\n", "out of range");
}
std::printf("\nTimer0 as the Arduino core sets it up (prescaler 64, 8-bit overflow):\n");
double tick_us = 64.0 / 16.0, overflow_us = 256.0 * tick_us;
std::printf(" one timer count = %.1f us (so micros() moves in steps of 4 us)\n", tick_us);
std::printf(" one overflow = %.1f us (the millis() interrupt fires at %.3f Hz)\n", overflow_us, 1e6 / overflow_us);
// the core's own bookkeeping (wiring.c, arduino:avr 1.8.8): 1 ms per overflow, and the 24 us left over kept as a fraction in units of 8 us
const int MILLIS_INC = 1024 / 1000, FRACT_INC = (1024 % 1000) >> 3, FRACT_MAX = 1000 >> 3;
unsigned long ms = 0; int f = 0; unsigned long n = 0;
while (ms < 1000000UL) { ms += MILLIS_INC; f += FRACT_INC; if (f >= FRACT_MAX) { f -= FRACT_MAX; ms += 1; } ++n; }
std::printf(" the core adds %d ms and %d (x 8 us) of fraction per overflow, and a spare ms when the fraction reaches %d\n", MILLIS_INC, FRACT_INC, FRACT_MAX);
std::printf(" simulated: %lu overflows (%.3f s of real time) are counted as %lu ms; error %.0f ppm\n", n, n * 1.024e-3, ms, ((double)ms - n * 1.024) / (n * 1.024) * 1e6);
return 0;
}
CTC settings at 16 MHz: best prescaler and OCR per timer, and the frequency really produced
wanted (Hz) Timer1 (16 bit): presc OCR actual (Hz) error (ppm) Timer2 (8 bit): presc OCR actual (Hz) error (ppm)
1 256 62499 1.000 0.0 out of range
50 8 39999 50.000 0.0 out of range
440 1 36363 439.996 10.0 256 141 440.141 320.1
1000 1 15999 1000.000 0.0 64 249 1000.000 0.0
20000 1 799 20000.000 0.0 8 99 20000.000 0.0
38000 1 420 38004.751 125.0 8 52 37735.849 6951.3
100000 1 159 100000.000 0.0 1 159 100000.000 0.0
Timer0 as the Arduino core sets it up (prescaler 64, 8-bit overflow):
one timer count = 4.0 us (so micros() moves in steps of 4 us)
one overflow = 1024.0 us (the millis() interrupt fires at 976.562 Hz)
the core adds 1 ms and 3 (x 8 us) of fraction per overflow, and a spare ms when the fraction reaches 125
simulated: 976563 overflows (1000.001 s of real time) are counted as 1000000 ms; error -1 ppm
Read the table for what the limits mean. A 1 kHz tick is exact on both timers (Timer1: prescaler 1, OCR1A = 15999; Timer2: prescaler 64, OCR2A = 249). 50 Hz and 1 Hz need Timer1: an 8-bit timer cannot count slowly enough, since the lowest it can reach is about 61 Hz. 440 Hz (a musical A) is 10 ppm off on Timer1 and 320 ppm off on Timer2, which is 0.02 of a cent against 0.55, and the 38 kHz of an infrared remote carrier is 125 ppm off on Timer1 and nearly 7000 ppm (0.7 %) off on Timer2, where the 8-bit compare value is too coarse. The last lines are the Arduino core’s own bookkeeping for Timer0, which I read from its source and ran: one timer count is 4 µs, which is why micros() moves in steps of 4 µs; an overflow takes 1.024 ms, not 1 ms, and the core keeps the extra 24 µs as a fraction and adds a spare millisecond when it reaches 125 (units of 8 µs), so millis() stays within about 1 ppm of the timer (the simulated run printed above counts 1000.001 s of timer time as 1000000 ms). The timer, of course, is only as accurate as the board’s clock, whose error I did not measure.
Challenge 1 asks how many whole frequencies each timer can reach. The setup of Timer1 for a 1 kHz tick is five register writes (in timer1_begin_1khz() in section 8).
4. Polling against events
The alternative to an interrupt is to poll: read the pin every time round loop(). It is simpler and has no shared variables, and it works when the signal is slow compared with the loop. When it is not, polling misses events. The experiment models a digital input that gets pulses of width w at random moments (about 20 per second, never overlapping), a polling loop that reads the pin every T and counts a pulse when it sees the pin high after seeing it low, and an interrupt that counts every rising edge (the reference: the model assumes its latency is much shorter than the pulse, which I did not measure):
// e_poll.cpp -- polling against an interrupt, as a model (host only; nothing here ran on a board).
// A digital input gets pulses of width w at random moments (about 20 per second, never overlapping). A polling loop reads the pin every T and counts a pulse when it sees
// the pin high after seeing it low. An interrupt counts every rising edge, so it is the reference: the model assumes its latency is much shorter than w.
// For each (w, T): the share of pulses the polling loop sees, over 20 seeds of 100 s, and the simple formula min(1, w / T).
#include <cstdio>
#include <cmath>
#include <vector>
#include <initializer_list>
#include "sim.h"
struct Result { double seen, formula; long pulses; };
static Result run(double w, double T, int seeds) {
long pulses = 0, seen = 0;
for (int seed = 1; seed <= seeds; ++seed) {
Rng rng((uint32_t)seed * 7919u);
std::vector<double> start;
double t = 0.05;
while (t < 100.0) { start.push_back(t); t += w + (-std::log(1.0 - rng.uniform() * 0.999999)) / 20.0; } // gap = w + exponential with mean 1/20 s
double phase = rng.uniform() * T;
bool prev = false; size_t k = 0;
long s = 0;
for (double ts = phase; ts < 100.0; ts += T) {
while (k < start.size() && start[k] + w < ts) ++k; // pulses that ended before this sample are gone
bool high = k < start.size() && start[k] <= ts && ts <= start[k] + w;
if (high && !prev) ++s;
prev = high;
}
pulses += (long)start.size(); seen += s;
}
Result r = {(double)seen / (double)pulses, w / T < 1.0 ? w / T : 1.0, pulses};
return r;
}
int main() {
std::printf("share of pulses a polling loop sees (an interrupt sees 100 %%, in this model), 20 pulses/s, 20 runs of 100 s\n");
std::printf(" loop period T: 0.1 ms 1 ms 5 ms 20 ms\n");
for (double w : {0.0002, 0.001, 0.005, 0.02, 0.1}) {
std::printf(" pulse %6.1f ms:", w * 1000);
for (double T : {0.0001, 0.001, 0.005, 0.02}) { Result r = run(w, T, 20); std::printf(" %5.1f%% (%3.0f%%)", 100.0 * r.seen, 100.0 * r.formula); }
std::printf("\n");
}
std::printf("(in brackets: the formula min(1, w / T))\n");
return 0;
}
share of pulses a polling loop sees (an interrupt sees 100 %, in this model), 20 pulses/s, 20 runs of 100 s
loop period T: 0.1 ms 1 ms 5 ms 20 ms
pulse 0.2 ms: 99.9% (100%) 20.0% ( 20%) 3.9% ( 4%) 1.0% ( 1%)
pulse 1.0 ms: 99.9% (100%) 99.0% (100%) 19.8% ( 20%) 4.9% ( 5%)
pulse 5.0 ms: 99.9% (100%) 99.0% (100%) 95.3% (100%) 22.8% ( 25%)
pulse 20.0 ms: 99.9% (100%) 99.0% (100%) 95.3% (100%) 82.6% (100%)
pulse 100.0 ms: 99.9% (100%) 99.0% (100%) 95.2% (100%) 82.5% (100%)
(in brackets: the formula min(1, w / T))
The share a polling loop sees is close to the formula min(1, w/T) when the pulse is shorter than the loop period: a 0.2 ms pulse polled every 1 ms is seen 20 % of the time, every 5 ms 3.9 %, every 20 ms 1.0 %. The odd entries are on the right of the table, where the formula says 100 % and the model says less (95.3 %, 82.6 %): when w is longer than T, polling sees every pulse that is separated from the next by more than one polling period, but two pulses closer together than that look like one, and with an average gap of 50 ms that happens to one pulse in six at a 20 ms period. For the build robot’s encoder (Programming for Robotics with Arduino C++ 4) the pulse is the width of one slot at the speed of the wheel, a fraction of a millisecond at speed, and a control loop that runs every 20 ms would see almost none of them; that is why encoders use interrupts and the bumper switch, whose press lasts tens of milliseconds, can be polled. The rule that follows is one of timing, not of taste: poll when the thing you are waiting for lasts several loop periods, use an interrupt when it can be shorter than one.
5. A cooperative scheduler, and what a long task does to it
The scheduler of Programming for Robotics with Arduino C++ 1 is cooperative: each task runs to its end, and then the next due task starts. It has no preemption, so the control task waits for whatever is running when it falls due, whatever its priority. The experiment puts a control task (20 ms period, assumed 1.2 ms of work) and an echo task (60 ms) on the real Scheduler class with a virtual clock, adds a report task whose time varies (the cost of writing text to Serial when the transmit buffer is full: 10 bit-times per character, 86.8 µs at 115200 baud and 1042 µs at 9600), and records the control task’s worst lateness. My prediction: about the length of the longest other task. The first run, with the report period at 500 ms, said otherwise:
// e_sched.cpp -- what a long task does to a short one in a COOPERATIVE scheduler (the Scheduler of Programming for Robotics with Arduino C++ 1), on a virtual clock in microseconds.
// Task execution times are ASSUMED, not measured: control 1.2 ms every 20 ms, echo start 0.1 ms every 60 ms, and a report task every 500 ms whose time is what the experiment varies.
// A task cannot be interrupted by another task, so the control task, however high its priority, waits for whatever is running. Prediction: its worst lateness is about the longest other task.
// Serial text takes 10 bit-times per character (8 data + start + stop): 86.8 us per character at 115200 baud, 1042 us at 9600 baud, when the transmit buffer is full and print() has to wait.
#include <cstdio>
#include <cstdint>
#include <initializer_list>
#include "scheduler.h"
static uint32_t g_now = 0; // virtual microseconds
struct Ctx { uint32_t cost_us; };
static void run_task(void* c, uint32_t) { g_now += static_cast<Ctx*>(c)->cost_us; }
struct Row { const char* name; uint32_t report_us; };
int main() {
const Row rows[] = {
{"no report task", 0},
{"report 40 chars at 115200 baud (3.5 ms)", 3472},
{"report 40 chars at 9600 baud (41.7 ms)", 41667},
{"dump 200 chars at 115200 baud (17.4 ms)", 17360},
{"dump 200 chars at 9600 baud (208 ms)", 208333},
{"the 200-char dump in 5 pieces of 40 chars at 115200 baud (3.5 ms each)", 3472},
};
std::printf("cooperative scheduler, 60 s of virtual time: control task every 20 ms (1.2 ms of work)\n");
for (int mode = 0; mode < 2; ++mode) {
std::printf("\n%s\n", mode == 0 ? "report period 500 ms (a multiple of the control period: the two are always due together)" : "report period 497 ms (3 ms off the grid each time: over 60 s it lands at every phase against the control task)");
std::printf(" case worst control lateness (ms) control runs skipped control runs\n");
for (int i = 0; i < 6; ++i) {
g_now = 0;
Ctx control = {1200}, echo = {100}, report = {rows[i].report_us};
Scheduler<4> sch;
sch.add(run_task, &control, 20000);
sch.add(run_task, &echo, 60000);
if (rows[i].report_us) sch.add(run_task, &report, i == 5 ? (mode ? 97000u : 100000u) : (mode ? 497000u : 500000u)); // the pieces: one 40-char piece about every 100 ms makes 200 chars per 500 ms
while (g_now < 60000000u) { sch.run(g_now); g_now += 10; } // each pass of loop() costs 10 us when nothing is due
const Task& c = sch.task(0);
std::printf(" %-72s %27.2f %20lu %12lu\n", rows[i].name, c.worst_late / 1000.0, (unsigned long)c.timer.skipped(), (unsigned long)c.timer.runs());
}
}
std::printf("(prediction: worst lateness is about the longest OTHER task: 0, 3.5, 41.7, 17.4, 208 and 3.5 ms)\n");
return 0;
}
cooperative scheduler, 60 s of virtual time: control task every 20 ms (1.2 ms of work)
report period 500 ms (a multiple of the control period: the two are always due together)
case worst control lateness (ms) control runs skipped control runs
no report task 0.00 0 3000
report 40 chars at 115200 baud (3.5 ms) 0.01 0 3000
report 40 chars at 9600 baud (41.7 ms) 22.99 120 2880
dump 200 chars at 115200 baud (17.4 ms) 0.00 0 3000
dump 200 chars at 9600 baud (208 ms) 189.65 1080 1920
the 200-char dump in 5 pieces of 40 chars at 115200 baud (3.5 ms each) 0.01 0 3000
report period 497 ms (3 ms off the grid each time: over 60 s it lands at every phase against the control task)
case worst control lateness (ms) control runs skipped control runs
no report task 0.00 0 3000
report 40 chars at 115200 baud (3.5 ms) 2.49 0 3000
report 40 chars at 9600 baud (41.7 ms) 40.69 127 2873
dump 200 chars at 115200 baud (17.4 ms) 16.37 0 3000
dump 200 chars at 9600 baud (208 ms) 207.34 1137 1863
the 200-char dump in 5 pieces of 40 chars at 115200 baud (3.5 ms each) 2.49 0 3000
(prediction: worst lateness is about the longest OTHER task: 0, 3.5, 41.7, 17.4, 208 and 3.5 ms)
In the first table the prediction fails: a 3.5 ms report gives 0.01 ms of lateness, a 17.4 ms dump 0.00. The reason is in the heading I added afterwards: 500 ms is a multiple of 20 ms, so the report and the control task fall due at the same moment and, with the control task first in the table, always run in the order control, report. The report never gets in the way, so the experiment had been measuring a coincidence. Only the 41.7 and 208 ms cases, which are longer than a control period, show damage (23 and 190 ms, with 120 and 1080 control runs skipped). The second table moves the report off the grid (497 ms, so over 60 s it falls at every phase against the control task), and the prediction holds: the worst lateness is 2.49 ms for the 3.5 ms report, 16.37 for the 17.4 ms dump, 40.69 for 41.7 and 207.34 for 208, each about 1 ms below the length of the task because the phases are 1 ms apart. And the cure is as the last row shows: the same 200 characters in five 40-character pieces has the same worst case as one piece (2.49 ms) instead of 16.37 ms.
Two lessons. First, the worst case of a cooperative scheduler is the longest task that can be running when a short one falls due, so the number to design for is the longest task, not the average load. Second, a test that happens to align the tasks measures nothing about the worst case: the check in the second table (a period that is off the grid) is as important as the first. The fixes are to split long work into pieces that fit (challenge 2 finds the size), to let the hardware do the waiting (the Arduino Serial has a 64-byte transmit buffer and print() returns at once while there is room; I did not test the Uno’s buffer limit here), and to give the time-critical work to a timer interrupt, as robot_ch8.ino does for its tick.
6. The watchdog
A watchdog timer is a hardware counter that resets the chip when it reaches its timeout unless the program resets it first (wdt_reset()). It is the answer to “what if the program hangs?”, which on a robot with live motors is not a theoretical question. It is also easy to defeat, because the question is where the program feeds it. wdt.h holds a model of the hardware (for tests) and a Heartbeats class: every task that matters calls checkin(id) when it has done its work, and the watchdog is fed only when all of them have.
// wdt.h -- the logic around a watchdog timer (Programming for Robotics with Arduino C++ 8). Plain C++11: no Arduino calls, so a PC can test it.
// The hardware watchdog resets the chip if it is not "fed" (wdt_reset()) within its timeout. The question is WHERE the feeding happens.
#pragma once
#include <stdint.h>
// A model of the hardware: it counts down and resets when it reaches the timeout.
class WdtModel {
public:
explicit WdtModel(uint32_t timeout_ms) : timeout_(timeout_ms), last_feed_(0), reset_at_(0), reset_(false) {}
void feed(uint32_t now) { if (!reset_) last_feed_ = now; }
bool poll(uint32_t now) { if (!reset_ && now - last_feed_ >= timeout_) { reset_ = true; reset_at_ = now; } return reset_; }
bool has_reset() const { return reset_; }
uint32_t reset_at() const { return reset_at_; }
private:
uint32_t timeout_, last_feed_, reset_at_;
bool reset_;
};
// Heartbeats: every task that matters calls checkin(id) when it has done its work. The watchdog is fed only when ALL of them have checked in since the last feed.
template <uint8_t N>
class Heartbeats {
public:
Heartbeats() : seen_(0) {}
void checkin(uint8_t id) { seen_ |= (uint8_t)(1u << id); }
bool all_alive() const { return seen_ == (uint8_t)((1u << N) - 1u); }
void clear() { seen_ = 0; }
uint8_t mask() const { return seen_; }
private:
uint8_t seen_;
};
The experiment runs three feeding policies against four situations, with a 250 ms timeout and a fault injected at 1 s: feed on every pass of loop(); feed only when both tasks have checked in; feed from a 1 ms timer interrupt.
// e_wdt.cpp -- where should the watchdog be fed? Three feeding policies against four situations, on a 1 ms virtual clock (host only; the watchdog is a MODEL, not the chip's).
// The robot: a control task every 20 ms and an echo task every 60 ms, each checking in with the heartbeat set. Watchdog timeout 250 ms. A fault is injected at t = 1000 ms:
// loop hangs the main loop stops completely (an infinite loop somewhere)
// control dies the control task silently stops running, but loop() keeps spinning
// echo dies the echo task silently stops running, but loop() keeps spinning
// none control run: nothing goes wrong (any reset here is a FALSE reset)
// Policies: "in loop": wdt feed on every pass of loop(). "supervisor": feed only when BOTH tasks have checked in since the last feed. "in timer ISR": feed from a 1 ms timer interrupt.
// Result: the time from the fault to the reset in ms, or "never" (nothing reset the robot within 5 s).
#include <cstdio>
#include "wdt.h"
enum Fault { NONE, LOOP_HANGS, CONTROL_DIES, ECHO_DIES };
enum Policy { IN_LOOP, SUPERVISOR, IN_ISR };
static long run(Policy pol, Fault fault, uint32_t timeout_ms, uint32_t horizon_ms) {
WdtModel wdt(timeout_ms);
Heartbeats<2> hb;
const uint32_t t_fault = 1000;
for (uint32_t t = 1; t <= horizon_ms; ++t) {
bool loop_alive = !(fault == LOOP_HANGS && t >= t_fault);
bool control_alive = !(fault == CONTROL_DIES && t >= t_fault);
bool echo_alive = !(fault == ECHO_DIES && t >= t_fault);
if (loop_alive) {
if (t % 20 == 0 && control_alive) hb.checkin(0);
if (t % 60 == 0 && echo_alive) hb.checkin(1);
if (pol == IN_LOOP) wdt.feed(t);
if (pol == SUPERVISOR && hb.all_alive()) { wdt.feed(t); hb.clear(); }
}
if (pol == IN_ISR) wdt.feed(t); // the interrupt fires whether or not loop() is alive
if (wdt.poll(t)) return fault == NONE ? -2 : (long)(wdt.reset_at() - t_fault);
}
return -1;
}
static void cell(long r) {
if (r == -1) std::printf(" %14s", "never");
else if (r == -2) std::printf(" %14s", "FALSE RESET");
else std::printf(" %11ld ms", r);
}
int main() {
std::printf("watchdog timeout 250 ms: time from the fault to the reset (never = not caught within 5 s)\n");
std::printf(" situation feed in loop supervisor feed in timer ISR\n");
const char* names[] = {"none", "loop hangs", "control dies", "echo dies"};
for (int f = 0; f < 4; ++f) {
std::printf(" %-12s", names[f]);
for (int p = 0; p < 3; ++p) cell(run((Policy)p, (Fault)f, 250, 5000));
std::printf("\n");
}
return 0;
}
watchdog timeout 250 ms: time from the fault to the reset (never = not caught within 5 s)
situation feed in loop supervisor feed in timer ISR
none never never never
loop hangs 249 ms 210 ms never
control dies never 270 ms never
echo dies never 210 ms never
Read the table by columns. Feeding in loop() catches only a total hang (249 ms): if the control task silently stops while loop() spins on, the robot carries on, with its last command, un-watched. Feeding from a timer interrupt catches nothing, not even the total hang, because the interrupt keeps firing while loop() is stuck: it proves that the timer works. It is the most common watchdog mistake, and it looks like safety. The supervisor catches all three, after 210 to 270 ms; the 270 ms is the timeout plus up to one heartbeat period (60 ms), which is the cost of feeding only on a full set of check-ins. The first row, “none”, is the control: with no fault there is no reset in 5 s with any policy. The choice of the timeout is the subject of challenge 3: too short and a healthy robot is reset by a long but harmless task.
On the Uno the calls are wdt_enable(WDTO_250MS) and wdt_reset() from <avr/wdt.h>; robot_ch8.ino compiles them in. Whether a watchdog reset works cleanly on your board depends on its bootloader (the Uno R3’s is expected to cope, but old bootloaders can loop after a watchdog reset), and how to find out afterwards why the chip reset depends on it too. I did not test either on a board.
7. Why there are no threads here, and what an RTOS would add
A real-time operating system (RTOS) gives each task its own stack and switches between them, usually on a timer interrupt, so a high-priority task can preempt a low-priority one in the middle. It would remove the section 5 problem: a control task could preempt a serial dump. It would also cost: each task needs its own stack (a stack of a hundred bytes or so is a realistic minimum for even small code, and it must be big enough for the deepest call and for an ISR on top; several tasks at that size are a large share of the Uno’s 2048 bytes, of which robot_ch8.ino already uses 327), the scheduler itself takes flash and RAM, and every variable shared between tasks now needs a lock, where today only the few that an ISR touches do. I did not build or measure an RTOS for the Uno, so those are descriptions of the cost, not figures. The sensible reading for this robot: the cooperative scheduler plus a few short ISRs gives deadline control that can be analysed (section 5’s rule), in 6918 bytes. An RTOS pays off when there are several tasks that must preempt each other, and on a larger board (the Pico, the ESP32), where the RAM is not the constraint.
8. On the Uno
robot_ch8.ino is chapter 7’s avoider rebuilt around a timer. Timer1 fires every millisecond; its ISR keeps a millisecond count, sets a flag every 20 ms for the control task and every 60 ms for the echo, and counts a control overrun if the control flag is still set when the next one comes (a measure of how often loop() is too slow). The encoders count on their own interrupts. loop() serves the flags, checks both tasks in with the heartbeat, and feeds the watchdog only when both have run.
// robot_ch8.ino -- Programming for Robotics with Arduino C++, chapter 8: chapter 7's avoider, now driven by a hardware timer (Timer1, 1 kHz), with the encoders on interrupts
// and a watchdog fed only when every task has checked in. Compile-checked for the Uno (arduino:avr:uno). NOT run on a board: nothing was attached, and the watchdog was never tripped on real hardware.
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#include <util/atomic.h>
#include "conv.h"
#include "echo.h"
#include "pins.h"
#include "filters.h"
#include "motion.h"
#include "fsm.h"
#include "wdt.h"
const float V_MAX_MPS = 0.5f;
const uint8_t DEAD_DUTY = 40; // ASSUMED: measure yours
// ---- the shared state between interrupts and loop(): every one is volatile; multi-byte ones are copied inside an atomic block ----
volatile uint32_t g_ms = 0; // our own millisecond count, from Timer1
volatile uint8_t g_control_due = 0, g_echo_due = 0, g_report_due = 0;
volatile uint16_t g_control_overruns = 0; // times the control tick came round again before loop() had served the last one
volatile int32_t g_ticks_l = 0, g_ticks_r = 0;
ISR(TIMER1_COMPA_vect) { // every 1 ms: keep this SHORT; it only counts and sets flags
static uint8_t c20 = 0, c60 = 0;
static uint16_t c500 = 0;
++g_ms;
if (++c20 >= 20) { c20 = 0; if (g_control_due) ++g_control_overruns; g_control_due = 1; }
if (++c60 >= 60) { c60 = 0; g_echo_due = 1; }
if (++c500 >= 500) { c500 = 0; g_report_due = 1; }
}
ISR(INT0_vect) { bool a = (PIND & _BV(PD2)) != 0, b = (PINC & _BV(PC1)) != 0; g_ticks_l += (a == b) ? 1 : -1; }
ISR(INT1_vect) { bool a = (PIND & _BV(PD3)) != 0, b = (PINC & _BV(PC2)) != 0; g_ticks_r += (a == b) ? 1 : -1; }
static uint32_t now_ms() { uint32_t t; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { t = g_ms; } return t; }
static void timer1_begin_1khz() { // CTC mode, prescaler 1, OCR1A = 15999: 16 MHz / 16000 = 1000 Hz (e_timer)
TCCR1A = 0;
TCCR1B = _BV(WGM12) | _BV(CS10);
OCR1A = 15999;
TCNT1 = 0;
TIMSK1 = _BV(OCIE1A);
}
static void drive(float vl, float vr) {
digitalWrite(PIN_ML_DIR, vl >= 0.0f ? HIGH : LOW);
digitalWrite(PIN_MR_DIR, vr >= 0.0f ? HIGH : LOW);
analogWrite(PIN_ML_PWM, speed_to_pwm_dz(vl >= 0.0f ? vl : -vl, V_MAX_MPS, DEAD_DUTY));
analogWrite(PIN_MR_PWM, speed_to_pwm_dz(vr >= 0.0f ? vr : -vr, V_MAX_MPS, DEAD_DUTY));
}
static AvoidConfig CFG = {0.3f, 0.25f, 0.2f, 2.0f, 0.15f, 400, 400, 1200, 3, true};
static TableAvoider machine(CFG, 12345);
static Median<int16_t, 5> median;
static Echo echo;
static Heartbeats<2> beats; // 0: control task, 1: echo task
static bool trig_level = false;
static float g_range = -1.0f;
void setup() {
Serial.begin(115200);
pinMode(PIN_ML_DIR, OUTPUT); pinMode(PIN_MR_DIR, OUTPUT); pinMode(PIN_ML_PWM, OUTPUT); pinMode(PIN_MR_PWM, OUTPUT);
pinMode(PIN_TRIG, OUTPUT); pinMode(PIN_ECHO, INPUT); pinMode(PIN_BUMP, INPUT_PULLUP);
pinMode(PIN_ENC_L, INPUT_PULLUP); pinMode(PIN_ENC_R, INPUT_PULLUP); pinMode(PIN_ENC_L_B, INPUT_PULLUP); pinMode(PIN_ENC_R_B, INPUT_PULLUP);
EICRA = _BV(ISC00) | _BV(ISC10); EIFR = _BV(INTF0) | _BV(INTF1); EIMSK = _BV(INT0) | _BV(INT1);
timer1_begin_1khz();
wdt_enable(WDTO_250MS); // from here on, a loop() that stops checking in resets the chip after 250 ms
}
void loop() {
bool before = trig_level;
Echo::Status st = echo.update(micros(), digitalRead(PIN_ECHO), trig_level);
if (trig_level != before) digitalWrite(PIN_TRIG, trig_level);
if (st == Echo::READY) g_range = (float)median.update((int16_t)(echo_us_to_m(echo.width_us()) * 1000.0f + 0.5f)) * 0.001f;
else if (st == Echo::TIMEOUT) g_range = -1.0f;
if (g_echo_due) { g_echo_due = 0; echo.start(); beats.checkin(1); }
if (g_control_due) {
g_control_due = 0;
Sense s; s.front_m = g_range; s.right_m = -1.0f; s.bump = digitalRead(PIN_BUMP) == LOW;
Cmd c = machine.update(s, now_ms());
drive(c.vl, c.vr);
beats.checkin(0);
}
if (g_report_due) {
g_report_due = 0;
int32_t l, r; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { l = g_ticks_l; r = g_ticks_r; }
Serial.print(now_ms()); Serial.print(F(" ms ticks ")); Serial.print(l); Serial.print(' '); Serial.print(r);
Serial.print(F(" overruns ")); Serial.println(g_control_overruns);
}
if (beats.all_alive()) { wdt_reset(); beats.clear(); } // fed only when BOTH tasks have run since the last feed
}
It compiles for the Uno under --warnings all with no warning from the sketch to 6918 bytes of flash (21 %) and 327 bytes of RAM (15 %): smaller than Programming for Robotics with Arduino C++ 7’s sketch (7114 bytes and 381), since it has no Scheduler object, and not comparable with the earlier chapters’ sketches, which did different jobs. The disassembly of the Timer1 interrupt shows the price of an ISR in instructions, with no time claimed:
Timer1 compare-match interrupt (__vector_11) in robot_ch8.ino, from avr-objdump
instructions in the whole routine ........ 71 (198 bytes of flash)
instructions on the usual path ........... 50 (no flag raised: the 20 ms, 60 ms and 500 ms counters have not rolled over)
of which: save 7 registers and the status register, then restore them ... 20
increment of the 32-bit g_ms (4 loads, 3 adds, 4 stores) .................. 11
three counter tests (20, 60, 500) ......................................... 19
time taken: NOT measured (no board)
Twenty of the 50 instructions are overhead the compiler adds to every ISR: seven registers and the status register saved and restored; the useful work is the 32-bit increment of g_ms (11 instructions: four loads, three adds and four stores because the counter is 32 bits wide) and three counter checks. A faster ISR would use a 16-bit counter or count in loop() from micros(). How long those 50 instructions take on a real chip, and how often another interrupt delays this one, I did not measure; at 16 MHz an instruction takes between one and four cycles depending on its kind, so the instruction count is an indication of where to look and not a duration.
9. What the numbers can and cannot be trusted for
What they show. The compiler’s own output for the real chip: that without volatile the wait loop becomes a jump to itself, that a 32-bit read is four loads and an atomic read is eight instructions, the flash and RAM of the sketch, and the number of instructions in the ISR. The calculator’s numbers are arithmetic. The shapes from the models: polling misses short pulses by about w/T; a cooperative scheduler’s worst lateness is the longest other task, if the test covers every phase; a watchdog fed from a timer interrupt catches nothing.
What they do not show. No interrupt latency, execution time or reset was measured; the task times in the scheduler experiment are chosen; the watchdog is a model; the pulse model is Poisson-like with a width I picked; the cost of an RTOS is a description, not a measurement. How the Uno’s own bootloader behaves after a watchdog reset is untested.
Challenge 1: Which frequencies can a timer make?
For every whole frequency from 1 Hz to 20 000 Hz, use the calculator to find the best prescaler and compare value on Timer1 and on Timer2, and report how many frequencies each can reach at all, within 1000 ppm and within 100 ppm, the lowest it can reach and its worst error. Say why the two timers differ.
A 200-character dump at 9600 baud is sent in pieces by a task every 41 ms next to the 20 ms control task. For pieces of 1, 2, 3, 5, 10, 20, 50 and 200 characters, report the control task’s worst lateness, the time the dump takes and the share of processor time it uses. Choose the largest piece that keeps the lateness under 2.5 ms, and say what you give up.
With the supervisor policy, find for each watchdog timeout from 15 ms to 8 s whether a healthy robot is reset by a loop() that is blocked for 0, 4, 17, 42 or 208 ms every 497 ms, and how long a real fault (the control task dying) takes to be caught. Find the rule that predicts the shortest safe timeout for a given blocking time.
ISR rules. Short; no delay() or Serial; count, copy, set a flag; everything shared with loop() is volatile.
volatile. Without it, the compiler (avr-gcc 7.3) turned while (!flag) into rjmp .-2, a jump to itself. With it, a load and a test every time round.
Atomic. A 32-bit read is 4 loads; ATOMIC_BLOCK adds cli and a status-register restore (8 instructions against 5). Single bytes need no guard; 16 bits and up do.
Timers. CTC frequency = 16 MHz / (prescaler × (OCR + 1)). 1 kHz: Timer1 presc 1, OCR 15999; Timer2 presc 64, OCR 249. Timer2 cannot go below 61 Hz. Timer0 runs millis() and the PWM on pins 5 and 6; Servo uses Timer1.
Polling. Sees about min(1, w/T) of pulses shorter than the loop period; use an interrupt when an event can be shorter than one loop.
Cooperative scheduling. Worst lateness of the control task = the longest other task (3.5 ms report: 2.49; 17.4 ms: 16.37; 208 ms: 207.34, at every phase), but a test with the tasks aligned showed none of it. Five 40-character pieces instead of one 200-character dump: 2.49 ms instead of 16.37.
Watchdog. Feeding in loop() catches only a total hang; feeding from a timer ISR catches nothing; the heartbeat supervisor caught all three faults (210–270 ms at a 250 ms timeout). Time to reset is the timeout plus up to one heartbeat period.
RTOS. Preemption and a stack per task; costs RAM and locks; not built or measured here.
Budget.robot_ch8.ino: 6918 bytes flash (21 %), 327 bytes RAM (15 %); Timer1 ISR 71 instructions (198 bytes), 50 on the common path. Compiled, not run; nothing timed.
Not run: anything on a board: interrupt latency, execution time, a real watchdog reset, an RTOS.
Next: Programming for Robotics with Arduino C++ 9, Planning and Navigation
Programming for Robotics with Arduino C++ 9 (planned; not yet written) gives the robot a map and a route: occupancy grids stored as bit arrays, breadth-first search and A* within a few kilobytes of RAM, the grid held in flash with PROGMEM, and pure-pursuit path following, where the memory budget, rather than the algorithm’s elegance, decides how big a map the robot can use.