Course 2 · Chapter 12 · Testing, Safety and Where to Go Next
Eleven chapters have built a robot that senses, filters, controls, plans, estimates and reaches. This last chapter is about the question that sits under all of it: how do you know it works, and what does it do when it does not? A robot is code that moves things in the world, so a bug is not a wrong number on a screen but a wall that is hit or a motor that burns. The honest answer to the first question is a test suite that you have seen fail on purpose. The honest answer to the second is a set of rules that make stopped the state every failure falls into, built from pieces that do not depend on the code they are guarding.
The chapter has five parts: unit tests for the host-built logic of the whole course, mutation testing to find out whether those tests would notice a bug, fault injection on the simulator to find out whether the safety pieces really stop the robot, the same pieces on the Uno with their cost, and a short look at what lies beyond an 8-bit board. It ends with a review of what this course measured and what it only compiled.
What was run, and what was not
Run on a PC (g++ 16.2, C++11, -Wall -Wextra -pedantic): the unit tests, the mutation runs, the fault-injection runs and the three challenge solutions, against the simulated robot of Programming for Robotics with Arduino C++ 3. The faults, the late controller, the sensor noise and the arena are assumptions I chose.
Compiled for the Uno, not run (arduino-cli, core arduino:avr 1.8.8, --warnings all): the seven-variant cost-test sketch and robot_ch12.ino; instruction counts come from avr-objdump. The watchdog, the emergency-stop input and the ring-buffer dump were never run on a board.
Read from the core’s own files: the Uno’s fuse bytes (boards.txt). From memory and not checked: what those bytes mean (the brown-out level) and everything said about faster boards, an RTOS and micro-ROS.
Nothing was attached to a board and no time was measured. A test that passes on the PC shows the logic is right on the PC; it does not show the board behaves.
1. A test suite in twenty lines of harness
Because the course wrote its logic as plain C++ with no Arduino calls, it can be tested on the PC without a board, a framework or a download. The whole test harness is a macro that counts passes and failures and says which line failed:
// minitest.h -- a test harness in twenty lines (host only). No framework: a macro that counts passes and failures and says which line failed.
#pragma once
#include <cstdio>
#include <cmath>
static int mt_pass = 0, mt_fail = 0;
#define CHECK(cond) do { if (cond) ++mt_pass; else { ++mt_fail; std::printf(" FAIL line %d: %s\n", __LINE__, #cond); } } while (0)
#define CHECK_NEAR(a, b, tol) do { double _a = (a), _b = (b); if (std::fabs(_a - _b) <= (tol)) ++mt_pass; else { ++mt_fail; std::printf(" FAIL line %d: %s = %.6g, expected %.6g (+-%g)\n", __LINE__, #a, _a, _b, (double)(tol)); } } while (0)
#define TEST(name) static void name()
#define RUN(name) do { int f0 = mt_fail; name(); std::printf(" %-34s %s\n", #name, mt_fail == f0 ? "ok" : "FAILED"); } while (0)
static int mt_summary() { std::printf("%d checks passed, %d failed\n", mt_pass, mt_fail); return mt_fail ? 1 : 0; }
The test file covers the pieces of the whole course: time and the scheduler (including the 32-bit counter wrap), the PID anti-windup, the planner, inverse kinematics and its lookup table, the trapezoid profile, the three estimators, and the new safety pieces of this chapter. Each test states one thing with a number that comes from the maths or from a definition, not copied from what the code printed: a trapezoid covers its distance; a BFS round a wall with a gap at the top is 4 + 7 + 3 + 7 = 21 steps; a scalar Kalman filter’s gain settles at P / (P + R) with the steady-state P of the formula; a complementary filter fed a constant angle converges to it.
// tests.cpp -- unit tests of the host-built logic of the whole course (Programming for Robotics with Arduino C++ 12). Host build: no board is involved.
// Each test states one thing the code must do, with a number that comes from the maths or from a definition, not copied from the code's own output.
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <initializer_list>
#include "minitest.h"
#include "timing.h"
#include "scheduler.h"
#include "pid.h"
#include "grid.h"
#include "tables.h"
#include "arm.h"
#include "est.h"
#include "safety.h"
#include "ringlog.h"
// ---- timing and the scheduler ----
static int g_calls = 0;
static void count_task(void*, uint32_t) { ++g_calls; }
TEST(elapsed_survives_the_wrap) {
CHECK(elapsed(5u, 0xFFFFFFFBu) == 10u); // the counter wrapped 10 ms ago
CHECK(elapsed(100u, 40u) == 60u);
}
TEST(periodic_runs_once_per_period) {
Periodic p(10); int runs = 0;
for (uint32_t t = 0; t < 1000; ++t) if (p.due(t)) ++runs;
CHECK(runs == 100); // at 0, 10, ..., 990
}
TEST(periodic_survives_the_wrap) {
Periodic p(10); int runs = 0;
uint32_t t0 = 0xFFFFFF00u;
for (uint32_t i = 0; i < 1000; ++i) if (p.due(t0 + i)) ++runs; // 1000 ms starting 256 ms before the counter wraps
CHECK(runs == 100);
}
TEST(scheduler_runs_tasks_at_their_periods) {
Scheduler<2> s; g_calls = 0;
s.add(count_task, 0, 20);
for (uint32_t t = 0; t < 1000; ++t) s.run(t);
CHECK(g_calls == 50);
}
// ---- control ----
TEST(pid_anti_windup_bounds_the_integral) {
PidConfig c = {1.0f, 2.0f, 0.0f, -1.0f, 1.0f, 0.0f, true, AW_CLAMP, 0.0f};
PidConfig n = c; n.aw = AW_NONE;
Pid a(c), b(n);
for (int i = 0; i < 500; ++i) { a.update(10.0f, 0.0f, 0.01f); b.update(10.0f, 0.0f, 0.01f); } // an error of 10 for 5 s, the output stuck at its limit
CHECK(a.integral() <= 1.0f + 1e-3f); // clamped: the integral cannot go beyond what the output can use
CHECK(b.integral() > 50.0f); // unclamped: 2 x 10 x 5 = 100 (it winds up)
}
// ---- planning ----
TEST(bfs_goes_left_too) {
BitGrid<8, 8> g; Bfs<8, 8, 64> bfs; uint16_t path[64];
CHECK(bfs.plan(g, 7, 3, 0, 3, path, 64) == 7); // an open grid, the goal to the left of the start: 7 steps
CHECK(bfs.plan(g, 3, 7, 3, 0, path, 64) == 7); // and upward
}
TEST(bfs_finds_the_shortest_path_round_a_wall) {
BitGrid<8, 8> g;
for (uint8_t y = 0; y < 7; ++y) g.set(4, y, true); // a wall at x = 4 with a gap at y = 7
Bfs<8, 8, 64> bfs; uint16_t path[64];
int16_t n = bfs.plan(g, 0, 0, 7, 0, path, 64);
CHECK(n == 21); // 4 + 7 to the gap, 3 + 7 back: 21 steps
CHECK(bfs.plan(g, 0, 0, 4, 3, path, 64) == -1); // the goal is inside the wall
for (uint8_t y = 0; y < 8; ++y) g.set(4, y, true);
CHECK(bfs.plan(g, 0, 0, 7, 0, path, 64) == -1); // no gap at all: unreachable, and the planner says so
}
// ---- kinematics and profiles ----
TEST(atan2_table_matches_atan2_in_all_quadrants) {
const float pts[9][2] = {{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}, {0, 0}};
for (int i = 0; i < 9; ++i) CHECK_NEAR(atan2_lut(pts[i][1], pts[i][0], ATAN_T, LUT_N), std::atan2(pts[i][1], pts[i][0]), 2e-3); // including the origin, where atan2 is 0
}
TEST(ik_round_trip_and_reach) {
Arm a = {100.0f, 80.0f}; float t1 = 0, t2 = 0, x, y;
for (int px = -170; px <= 170; px += 17)
for (int py = -170; py <= 170; py += 17) {
bool ok = ik(a, (float)px, (float)py, true, t1, t2);
double r = std::hypot((double)px, (double)py);
if (r > 21.0 && r < 179.0) { CHECK(ok); if (ok) { fk(a, t1, t2, x, y); CHECK_NEAR(x, px, 1e-3); CHECK_NEAR(y, py, 1e-3); } }
if (r > 181.0 || r < 19.0) CHECK(!ok);
}
}
TEST(ik_elbow_sign) {
Arm a = {100.0f, 80.0f}; float u1 = 0, u2 = 0, d1 = 0, d2 = 0;
CHECK(ik(a, 120.0f, 40.0f, true, u1, u2));
CHECK(ik(a, 120.0f, 40.0f, false, d1, d2));
CHECK(u2 < 0.0f && d2 > 0.0f); // up: the elbow bends clockwise; down: counter-clockwise
}
TEST(lut_ik_is_close_to_the_math_ik) {
Arm a = {100.0f, 80.0f}; float s1 = 0, s2 = 0, l1 = 0, l2 = 0;
for (int px = 60; px <= 140; px += 20)
for (int py = -30; py <= 60; py += 15) {
CHECK(ik(a, (float)px, (float)py, true, s1, s2));
CHECK(ik_lut(a, (float)px, (float)py, true, l1, l2, ACOS_T, ATAN_T, LUT_N));
float x, y; fk(a, l1, l2, x, y);
CHECK(std::hypot(x - px, y - py) < 0.5); // half a millimetre in the middle of the workspace
}
}
TEST(integer_fk_matches_float_fk) {
Arm a = {100.0f, 80.0f};
for (int t1 = 0; t1 <= 90; t1 += 15)
for (int t2 = -150; t2 <= 30; t2 += 30) {
float x, y; fk(a, t1 * 0.0174532925f, t2 * 0.0174532925f, x, y);
int16_t xi, yi; fk_int(100, 80, (int16_t)t1, (int16_t)t2, xi, yi);
CHECK(std::fabs(xi - x * 10.0f) < 3.0f && std::fabs(yi - y * 10.0f) < 3.0f); // within 0.3 mm
}
}
TEST(trapezoid_covers_the_distance_in_the_planned_time) {
for (float d : {5.0f, 20.0f, 30.0f, 36.0f, 90.0f, -60.0f}) {
Trap t; t.plan(d, 120.0f, 400.0f);
CHECK_NEAR(t.pos(t.T), d, 1e-4);
CHECK_NEAR(t.pos(t.T * 0.5f), d * 0.5f, std::fabs(d) * 1e-3); // symmetric: half the distance at half the time
CHECK(t.vel(0.0f) == 0.0f && t.vel(t.T) == 0.0f);
double integ = 0; for (int i = 1; i <= (int)(t.T * 1000); ++i) integ += t.vel(i * 0.001f) * 0.001;
CHECK_NEAR(integ, d, std::fabs(d) * 0.01);
}
Trap tri; tri.plan(10.0f, 120.0f, 400.0f);
CHECK_NEAR(tri.v, std::sqrt(400.0 * 10.0), 1e-3); // a short move is a triangle: the peak speed is sqrt(a d)
Trap a, b; plan_sync(a, b, 60.0f, 15.0f, 120.0f, 400.0f);
CHECK_NEAR(a.T, b.T, 1e-4); // two joints finish together
}
// ---- estimation ----
TEST(complementary_filter_believes_the_gyro_in_the_short_term) {
Complementary f(0.5f, 0.01f, 0.0f);
for (int i = 0; i < 10; ++i) f.update(1.0f, 0.0f, 0.01f); // a gyro saying 1 rad/s for 0.1 s, an absolute sensor saying 0
CHECK(f.angle() > 0.08f && f.angle() < 0.1f); // the gyro wins over 0.1 s: about 0.09 (the weight is alpha = tau / (tau + dt))
}
TEST(complementary_filter_converges_to_a_constant_angle) {
Complementary f(0.5f, 0.01f, 0.0f);
for (int i = 0; i < 2000; ++i) f.update(0.0f, 0.3f, 0.01f); // 20 s at 40 time constants
CHECK_NEAR(f.angle(), 0.3, 1e-3);
}
TEST(scalar_kalman_gain_reaches_the_formula) {
const float q = 1e-6f, r = 2.5e-5f;
Kalman1 k(0.0f, 1.0f, q, r);
for (int i = 0; i < 500; ++i) k.update(1.0f);
double p = (q + std::sqrt((double)q * q + 4.0 * q * r)) / 2.0; // steady-state predicted variance
CHECK_NEAR(k.gain(), p / (p + r), 1e-3);
CHECK_NEAR(k.x(), 1.0, 1e-3);
}
TEST(fixed_point_heading_filter_learns_the_gyro_offset) {
HeadingFixed f(1223, -114);
for (int i = 1; i <= 6000; ++i) { // a still robot, a gyro that reads 0.02 rad/s too much, a compass that says 0
f.predict(20000);
if (i % 10 == 0) f.update(0);
}
CHECK(std::abs(f.heading()) < 20000); // within 0.02 rad
CHECK(std::abs(f.bias() - 20000) < 4000); // the offset is found to 20 %
}
// ---- the safety pieces ----
TEST(output_expires) {
ExpiringCmd e(100); Cmd c = {0.3f, 0.3f};
CHECK(e.expired(0)); // nothing given yet: expired
e.set(c, 1000);
CHECK(e.get(1050).vl == 0.3f);
CHECK(e.get(1100).vl == 0.3f); // exactly at the timeout it is still good: it expires AFTER it
CHECK(e.get(1101).vl == 0.0f && e.get(1101).vr == 0.0f);
e.set(c, 0xFFFFFFF0u);
CHECK(e.get(20).vl == 0.3f); // 36 ms later, across the wrap
}
TEST(estop_is_debounced_and_latched) {
Estop s(3);
s.sample(true); s.sample(false); s.sample(true); s.sample(true);
CHECK(!s.tripped()); // bounce: never three in a row
s.sample(true);
CHECK(s.tripped());
s.sample(false);
CHECK(s.tripped()); // releasing the button does not restart the robot
s.sample(true);
CHECK(!s.reset()); // reset is refused while the button is held
s.sample(false);
CHECK(s.reset() && !s.tripped());
}
TEST(stuck_detector_needs_motion_and_no_change) {
StuckDetector d(0.02f, 500);
for (uint32_t t = 0; t <= 1000; t += 60) d.update(1.0f, true, false, t); // still: a constant reading is normal
CHECK(!d.stuck(1000));
StuckDetector m(0.02f, 500);
for (uint32_t t = 0; t <= 400; t += 60) m.update(1.0f, true, true, t);
CHECK(!m.stuck(400)); // not yet: the window is 500 ms
for (uint32_t t = 420; t <= 800; t += 60) m.update(1.0f, true, true, t);
CHECK(m.stuck(800));
StuckDetector ok(0.02f, 500); float r = 2.0f;
for (uint32_t t = 0; t <= 2000; t += 60) { ok.update(r, true, true, t); r -= 0.015f; }
CHECK(!ok.stuck(2000)); // a reading that changes while moving is alive
StuckDetector slow(0.02f, 500); float q = 2.0f;
for (uint32_t t = 0; t <= 2000; t += 60) { slow.update(q, true, true, t); q -= 0.0036f; } // 36 mm per 600 ms: slow, but more than the 20 mm threshold in 500 ms
CHECK(!slow.stuck(2000));
}
TEST(stall_detector_sees_a_blocked_wheel) {
StallDetector s(0.05f, 400);
for (uint32_t t = 0; t <= 300; t += 20) s.update(0.3f, 0, t);
CHECK(!s.stalled(300));
for (uint32_t t = 320; t <= 500; t += 20) s.update(0.3f, 0, t);
CHECK(s.stalled(500));
StallDetector w(0.05f, 400); int32_t tk = 0;
for (uint32_t t = 0; t <= 2000; t += 20) { tk += 3; w.update(0.3f, tk, t); }
CHECK(!w.stalled(2000)); // turning: no stall
}
TEST(supervisor_stops_what_it_must_and_passes_the_rest) {
SafetyConfig c = {250, 300, 0.02f, 500, 400, 0.15f, 0.4f};
Supervisor s(c); Cmd go = {0.3f, 0.3f};
s.command(go, 0);
int32_t tk = 0; Cmd out = go;
for (uint32_t t = 20; t <= 200; t += 20) { tk += 6; s.range_sample(t, 2.0f - 0.001f * t); out = s.step(t, tk, tk); }
CHECK(out.vl == 0.3f && s.faults() == 0); // healthy: passed through
out = s.step(200 + 400, tk, tk);
CHECK(out.vl == 0.0f && out.vr == 0.0f); // the command is older than 250 ms: zero, and no latched fault
s.command(go, 700);
s.range_sample(710, 0.10f);
out = s.step(720, tk + 6, tk + 6);
CHECK(out.vl == 0.0f && (s.faults() & F_TOO_CLOSE)); // forward with a wall at 0.10 m: stop, latched
s.command(go, 740);
s.range_sample(750, 1.5f);
out = s.step(760, tk + 12, tk + 12);
CHECK(out.vl == 0.0f); // still latched although the wall is no longer seen
CHECK(s.reset() && s.faults() == 0);
Cmd fast = {2.0f, -2.0f}; s.command(fast, 800);
s.range_sample(810, 3.0f);
out = s.step(820, tk + 20, tk + 20);
CHECK(out.vl == 0.4f && out.vr == -0.4f); // the speed limit is symmetric
Supervisor st(c); st.command(go, 1000);
for (uint32_t t = 1020; t <= 1400; t += 20) { st.command(go, t); st.range_sample(t, -1.0f); st.step(t, 0, 0); } // the controller keeps commanding, the sensor never answers
CHECK(st.faults() & F_STALE_RANGE); // no valid reading for more than 300 ms while driving forward
}
// ---- the log ----
TEST(ring_log_keeps_the_last_events) {
RingLog<4> log;
for (int i = 1; i <= 10; ++i) log.add((uint32_t)i * 10, (uint8_t)i, (int16_t)(i * 100));
CHECK(log.size() == 4 && log.total() == 10);
CHECK(log.at(0).code == 7 && log.at(3).code == 10); // the oldest kept is event 7, the newest is 10
CHECK(log.at(0).value == 700 && log.at(3).t_ms == 100);
RingLog<4> few; few.add(1, 1, 1); few.add(2, 2, 2);
CHECK(few.size() == 2 && few.at(0).code == 1 && few.at(1).code == 2); // not yet full: in order from the start
}
int main() {
std::printf("unit tests of the host-built logic\n");
RUN(elapsed_survives_the_wrap);
RUN(periodic_runs_once_per_period);
RUN(periodic_survives_the_wrap);
RUN(scheduler_runs_tasks_at_their_periods);
RUN(pid_anti_windup_bounds_the_integral);
RUN(bfs_goes_left_too);
RUN(bfs_finds_the_shortest_path_round_a_wall);
RUN(atan2_table_matches_atan2_in_all_quadrants);
RUN(ik_round_trip_and_reach);
RUN(ik_elbow_sign);
RUN(lut_ik_is_close_to_the_math_ik);
RUN(integer_fk_matches_float_fk);
RUN(trapezoid_covers_the_distance_in_the_planned_time);
RUN(complementary_filter_believes_the_gyro_in_the_short_term);
RUN(complementary_filter_converges_to_a_constant_angle);
RUN(scalar_kalman_gain_reaches_the_formula);
RUN(fixed_point_heading_filter_learns_the_gyro_offset);
RUN(output_expires);
RUN(estop_is_debounced_and_latched);
RUN(stuck_detector_needs_motion_and_no_change);
RUN(stall_detector_sees_a_blocked_wheel);
RUN(supervisor_stops_what_it_must_and_passes_the_rest);
RUN(ring_log_keeps_the_last_events);
return mt_summary();
}
unit tests of the host-built logic
elapsed_survives_the_wrap ok
periodic_runs_once_per_period ok
periodic_survives_the_wrap ok
scheduler_runs_tasks_at_their_periods ok
pid_anti_windup_bounds_the_integral ok
bfs_goes_left_too ok
bfs_finds_the_shortest_path_round_a_wall ok
atan2_table_matches_atan2_in_all_quadrants ok
ik_round_trip_and_reach ok
ik_elbow_sign ok
lut_ik_is_close_to_the_math_ik ok
integer_fk_matches_float_fk ok
trapezoid_covers_the_distance_in_the_planned_time ok
complementary_filter_believes_the_gyro_in_the_short_term ok
complementary_filter_converges_to_a_constant_angle ok
scalar_kalman_gain_reaches_the_formula ok
fixed_point_heading_filter_learns_the_gyro_offset ok
output_expires ok
estop_is_debounced_and_latched ok
stuck_detector_needs_motion_and_no_change ok
stall_detector_sees_a_blocked_wheel ok
supervisor_stops_what_it_must_and_passes_the_rest ok
ring_log_keeps_the_last_events ok
1360 checks passed, 0 failed
2. Would the tests notice a bug?
The first version of this suite had 1,337 checks, and it passed the first time it was run. That is the dangerous moment: a green suite proves nothing if it cannot go red. Mutation testing answers the question mechanically. Take the code, change one thing that a careless edit could change (a sign, a > for >=, a forgotten term), build the tests against the changed code and run them. If a check fails, the mutant is killed: the suite would have caught that bug. If everything still passes, the mutant survived: the suite is blind to it. The script below does that for 21 mutants:
# mutate.py -- does the test suite notice a bug? Each mutant is a copy of the code with ONE small change; tests.cpp is built against it and run.
# "killed" = at least one check failed (or the program crashed or hung); "survived" = every check still passed: the suite would not have caught that bug.
import os, re, shutil, subprocess, sys
HERE = os.path.dirname(os.path.abspath(__file__))
GPP = r"C:/Users/emuba/AppData/Local/Microsoft/WinGet/Packages/BrechtSanders.WinLibs.POSIX.UCRT_Microsoft.Winget.Source_8wekyb3d8bbwe/mingw64/bin/g++.exe"
HEADERS = [f for f in os.listdir(HERE) if f.endswith(".h")] + ["tests.cpp"]
# (file, text that must occur, replacement, what the mutant is)
M = [
("arm.h", "if (elbow_up) s2 = -s2;", "if (!elbow_up) s2 = -s2;", "ik: the elbow-up and elbow-down branches swapped"),
("arm.h", "if (c2 > 1.0f || c2 < -1.0f) return false;", "if (c2 > 1.0f) return false;", "ik: the too-close side of the reach test removed"),
("arm.h", "T = 2.0f * ta + tc;", "T = ta + tc;", "Trap: the braking phase left out of the total time"),
("arm.h", "if (d < vmax * vmax / amax)", "if (d < 0.5f * vmax * vmax / amax)", "Trap: the triangle/trapezoid threshold halved"),
("arm.h", "if (ax == 0.0f && ay == 0.0f) return 0.0f;", "if (ax == 0.0f && ay == 0.0f) return 1.0f;", "atan2_lut: wrong answer for the point at the origin"),
("est.h", "alpha_(tau_s / (tau_s + dt_s))", "alpha_(dt_s / (tau_s + dt_s))", "Complementary: gyro and measurement weights swapped"),
("est.h", "p_ *= (1.0f - k_);", "p_ *= k_;", "Kalman1: the uncertainty update uses K instead of 1 - K"),
("est.h", "th_ += (rate_urad_s - b_) / 100;", "th_ += (rate_urad_s + b_) / 100;", "HeadingFixed: the offset is added instead of subtracted"),
("timing.h", "inline uint32_t elapsed(uint32_t now, uint32_t then) { return now - then; }", "inline uint32_t elapsed(uint32_t now, uint32_t then) { return now > then ? now - then : 0; }", "elapsed: the counter wrap is no longer handled"),
("pid.h", "u > c_.out_max && e > 0.0f", "u > c_.out_max && e < 0.0f", "Pid: the anti-windup test looks at the wrong sign"),
("grid.h", "if (m.blocked(sx, sy) || m.blocked(gx, gy)) return -1;", "if (m.blocked(sx, sy)) return -1;", "Bfs: a blocked goal is no longer rejected up front"),
("grid.h", "inline int8_t dx4(uint8_t d) { return d == 0 ? 1 : (d == 2 ? -1 : 0); }", "inline int8_t dx4(uint8_t d) { return d == 0 ? 1 : (d == 2 ? 1 : 0); }", "Bfs: the 'left' neighbour is replaced by 'right'"),
("safety.h", "if (count_ >= n_) latched_ = true;", "if (count_ > n_) latched_ = true;", "Estop: debounce needs one sample more than asked"),
("safety.h", "if (released_) { latched_ = false; return true; } return false;", "latched_ = false; return true;", "Estop: reset accepted while the button is still held"),
("safety.h", "elapsed(now, stamp_) > timeout_", "elapsed(now, stamp_) >= timeout_", "ExpiringCmd: expires at the timeout instead of after it"),
("safety.h", "if (c < min_cmd_ || !have_ || ticks != last_ticks_)", "if (c < min_cmd_ || !have_)", "StallDetector: wheel movement no longer resets the timer"),
("safety.h", "else if (out.vr < -c_.v_max) out.vr = -c_.v_max;", "else if (out.vr < -c_.v_max) out.vr = c_.v_max;", "Supervisor: the reverse speed limit has the wrong sign"),
("safety.h", "if (faults_ != 0) { out.vl = 0.0f; out.vr = 0.0f; }", "if (faults_ != 0 && false) { out.vl = 0.0f; out.vr = 0.0f; }", "Supervisor: a fault no longer stops the motors"),
("safety.h", "if (d > delta_) { anchor_ = reading_m; since_ = now; }", "if (d > 2.0f * delta_) { anchor_ = reading_m; since_ = now; }", "StuckDetector: the change threshold doubled"),
("ringlog.h", "head_ = (uint8_t)((head_ + 1) % N);", "head_ = (uint8_t)((head_ + 1) % (N - 1));", "RingLog: the write position wraps one slot early"),
("ringlog.h", "if (count_ < N) ++count_;", "if (count_ < N - 1) ++count_;", "RingLog: one slot of the buffer is never counted"),
]
def run(cmd, **kw):
return subprocess.run(cmd, capture_output=True, text=True, **kw)
killed = survived = invalid = 0
print("%-3s %-62s %s" % ("#", "mutant (one change)", "result"))
for i, (fname, old, new, what) in enumerate(M, 1):
d = os.path.join(HERE, "mut", "m%02d" % i)
shutil.rmtree(d, ignore_errors=True); os.makedirs(d)
for h in HEADERS:
shutil.copy(os.path.join(HERE, h), d)
p = os.path.join(d, fname)
s = open(p, encoding="utf-8").read()
if old not in s:
print("%-3d %-62s NOT APPLIED (text not found)" % (i, what)); invalid += 1; continue
open(p, "w", encoding="utf-8", newline="\n").write(s.replace(old, new, 1))
exe = os.path.join(d, "t.exe")
c = run([GPP, "-std=c++11", "-O1", os.path.join(d, "tests.cpp"), "-o", exe], cwd=d)
if c.returncode != 0:
print("%-3d %-62s DID NOT COMPILE" % (i, what)); invalid += 1; continue
try:
r = run([exe], cwd=d, timeout=20)
out = r.stdout
m = re.search(r"(\d+) checks passed, (\d+) failed", out)
if r.returncode != 0 and m:
failed_tests = [l.split()[0] for l in out.splitlines() if l.rstrip().endswith("FAILED")]
print("%-3d %-62s killed: %s checks failed (%s)" % (i, what, m.group(2), ", ".join(failed_tests[:3]) + (" ..." if len(failed_tests) > 3 else ""))); killed += 1
elif r.returncode != 0:
print("%-3d %-62s killed: the program crashed" % (i, what)); killed += 1
else:
print("%-3d %-62s SURVIVED" % (i, what)); survived += 1
except subprocess.TimeoutExpired:
print("%-3d %-62s killed: the program hung (20 s)" % (i, what)); killed += 1
print("%d mutants: %d killed, %d survived, %d invalid" % (len(M), killed, survived, invalid))
First run, against that first suite:
# mutant (one change) result
1 ik: the elbow-up and elbow-down branches swapped killed: 1 checks failed (ik_elbow_sign)
2 ik: the too-close side of the reach test removed killed: 5 checks failed (ik_round_trip_and_reach)
3 Trap: the braking phase left out of the total time killed: 8 checks failed (trapezoid_covers_the_distance_in_the_planned_time)
4 Trap: the triangle/trapezoid threshold halved SURVIVED
5 atan2_lut: wrong answer for the point at the origin SURVIVED
6 Complementary: gyro and measurement weights swapped SURVIVED
7 Kalman1: the uncertainty update uses K instead of 1 - K killed: 1 checks failed (scalar_kalman_gain_reaches_the_formula)
8 HeadingFixed: the offset is added instead of subtracted killed: 2 checks failed (fixed_point_heading_filter_learns_the_gyro_offset)
9 elapsed: the counter wrap is no longer handled killed: 2 checks failed (elapsed_survives_the_wrap, periodic_survives_the_wrap)
10 Pid: the anti-windup test looks at the wrong sign killed: 1 checks failed (pid_anti_windup_bounds_the_integral)
11 Bfs: a blocked goal is no longer rejected up front SURVIVED
12 Bfs: the 'left' neighbour is replaced by 'right' SURVIVED
13 Estop: debounce needs one sample more than asked killed: 2 checks failed (estop_is_debounced_and_latched)
14 Estop: reset accepted while the button is still held killed: 1 checks failed (estop_is_debounced_and_latched)
15 ExpiringCmd: expires at the timeout instead of after it SURVIVED
16 StallDetector: wheel movement no longer resets the timer killed: 1 checks failed (stall_detector_sees_a_blocked_wheel)
17 Supervisor: the reverse speed limit has the wrong sign killed: 1 checks failed (supervisor_stops_what_it_must_and_passes_the_rest)
18 Supervisor: a fault no longer stops the motors killed: 2 checks failed (supervisor_stops_what_it_must_and_passes_the_rest)
19 StuckDetector: the change threshold doubled SURVIVED
20 RingLog: the write position wraps one slot early killed: 2 checks failed (ring_log_keeps_the_last_events)
21 RingLog: one slot of the buffer is never counted killed: 3 checks failed (ring_log_keeps_the_last_events)
21 mutants: 14 killed, 7 survived, 0 invalid
Seven of 21 survived, and each survivor was a hole in the tests, not in the code. The trapezoid’s triangle threshold was halved and nothing noticed, because no test used a move between 18° and 36°. The complementary filter’s two weights were swapped and nothing noticed, because the only test fed it a constant angle, which the swapped filter reaches even faster; it never tested that the gyro is believed in the short term. The breadth-first search lost its “left” neighbour and nothing noticed, because every test path went up and to the right. The command timeout fired at the timeout instead of after it, because no test sat exactly on the boundary. The stuck detector’s threshold was doubled, because no test had a reading that drifted slowly. The point at the origin of the table-based arctangent was wrong, because no test asked for it.
I added tests to close those holes (a trapezoid of 20° and 30°; the gyro in the short term; a path to the left and downward; a command at exactly its timeout; a slow drift; the arctangent table in all quadrants) and ran it again:
# mutant (one change) result
1 ik: the elbow-up and elbow-down branches swapped killed: 1 checks failed (ik_elbow_sign)
2 ik: the too-close side of the reach test removed killed: 5 checks failed (ik_round_trip_and_reach)
3 Trap: the braking phase left out of the total time killed: 12 checks failed (trapezoid_covers_the_distance_in_the_planned_time)
4 Trap: the triangle/trapezoid threshold halved killed: 4 checks failed (trapezoid_covers_the_distance_in_the_planned_time)
5 atan2_lut: wrong answer for the point at the origin killed: 1 checks failed (atan2_table_matches_atan2_in_all_quadrants)
6 Complementary: gyro and measurement weights swapped killed: 1 checks failed (complementary_filter_believes_the_gyro_in_the_short_term)
7 Kalman1: the uncertainty update uses K instead of 1 - K killed: 1 checks failed (scalar_kalman_gain_reaches_the_formula)
8 HeadingFixed: the offset is added instead of subtracted killed: 2 checks failed (fixed_point_heading_filter_learns_the_gyro_offset)
9 elapsed: the counter wrap is no longer handled killed: 2 checks failed (elapsed_survives_the_wrap, periodic_survives_the_wrap)
10 Pid: the anti-windup test looks at the wrong sign killed: 1 checks failed (pid_anti_windup_bounds_the_integral)
11 Bfs: a blocked goal is no longer rejected up front SURVIVED
12 Bfs: the 'left' neighbour is replaced by 'right' killed: 1 checks failed (bfs_goes_left_too)
13 Estop: debounce needs one sample more than asked killed: 2 checks failed (estop_is_debounced_and_latched)
14 Estop: reset accepted while the button is still held killed: 1 checks failed (estop_is_debounced_and_latched)
15 ExpiringCmd: expires at the timeout instead of after it killed: 1 checks failed (output_expires)
16 StallDetector: wheel movement no longer resets the timer killed: 1 checks failed (stall_detector_sees_a_blocked_wheel)
17 Supervisor: the reverse speed limit has the wrong sign killed: 1 checks failed (supervisor_stops_what_it_must_and_passes_the_rest)
18 Supervisor: a fault no longer stops the motors killed: 2 checks failed (supervisor_stops_what_it_must_and_passes_the_rest)
19 StuckDetector: the change threshold doubled killed: 1 checks failed (stuck_detector_needs_motion_and_no_change)
20 RingLog: the write position wraps one slot early killed: 2 checks failed (ring_log_keeps_the_last_events)
21 RingLog: one slot of the buffer is never counted killed: 3 checks failed (ring_log_keeps_the_last_events)
21 mutants: 20 killed, 1 survived, 0 invalid
Twenty of 21 are killed (the suite now has 1,360 checks). The survivor, a blocked goal no longer rejected up front in Bfs, is an equivalent mutant: the search never enqueues a blocked cell, so a blocked goal returns “unreachable” either way and no test can tell the two versions apart. Equivalent mutants are the one kind of survivor you stop worrying about, once you have checked that it really is one. Mutation testing has limits: 21 hand-picked mutants are a sample, not a proof, and the tests only check what the host build can reach (nothing here tests the interrupts or the pins).
3. Safety is a design, not a feature
Three principles run through the code of this chapter. The safe state is stopped, and every part fails toward it. The guard must not depend on the thing it guards: a supervisor that stops working when the controller hangs is no supervisor. A fault is latched: when something has gone wrong the robot stays stopped until a person has looked and reset it, not until the condition happens to go away. safety.h turns them into five small pieces, plain C++ with no heap and no Arduino calls so the PC can fault-inject them:
// safety.h -- the rules that keep a moving robot from doing damage, as small testable pieces (Programming for Robotics with Arduino C++ 12).
// Plain C++11: no heap, no Arduino calls, so a PC can test and fault-inject it. Times are uint32_t milliseconds that may wrap (use elapsed()).
// The principle: the safe state is "stopped". Every piece fails toward it, and nothing in here depends on the code it is guarding.
#pragma once
#include <stdint.h>
#include "timing.h"
#include "fsm.h" // Cmd { vl, vr }
enum Fault : uint8_t {
F_NONE = 0, F_ESTOP = 1, F_STALE_CMD = 2, F_STALE_RANGE = 4, F_STUCK_RANGE = 8, F_STALL = 16, F_TOO_CLOSE = 32
};
// ---- 1. an output that expires: a command is only good for `timeout_ms` after it was given ----
// If the controller hangs, crashes or is late, the motors do not keep the last command: they get zero.
class ExpiringCmd {
public:
explicit ExpiringCmd(uint32_t timeout_ms) : timeout_(timeout_ms), stamp_(0), have_(false) { cmd_.vl = 0.0f; cmd_.vr = 0.0f; }
void set(const Cmd& c, uint32_t now) { cmd_ = c; stamp_ = now; have_ = true; }
bool expired(uint32_t now) const { return !have_ || elapsed(now, stamp_) > timeout_; }
Cmd get(uint32_t now) const { Cmd z = {0.0f, 0.0f}; return expired(now) ? z : cmd_; }
private:
uint32_t timeout_, stamp_;
bool have_;
Cmd cmd_;
};
// ---- 2. an emergency-stop input: debounced and LATCHED ----
// The switch must read "pressed" for `n` consecutive samples to trip; once tripped the stop stays on until reset() is called AND the switch has been released:
// a bounce or a released button must not restart the robot.
class Estop {
public:
explicit Estop(uint8_t n) : n_(n), count_(0), latched_(false), released_(true) {}
void sample(bool pressed) {
if (pressed) { if (count_ < 255) ++count_; released_ = false; if (count_ >= n_) latched_ = true; }
else { count_ = 0; released_ = true; }
}
bool reset() { if (released_) { latched_ = false; return true; } return false; }
bool tripped() const { return latched_; }
private:
uint8_t n_, count_;
bool latched_, released_;
};
// ---- 3. a stuck-sensor detector: while the robot is moving, a distance reading that does not change by more than `delta` for `window_ms` is not a measurement ----
class StuckDetector {
public:
StuckDetector(float delta, uint32_t window_ms) : delta_(delta), window_(window_ms), anchor_(0.0f), since_(0), have_(false) {}
void update(float reading_m, bool valid, bool moving, uint32_t now) {
if (!moving || !valid) { have_ = false; return; } // restart the window when stopped or when there is no reading
if (!have_) { anchor_ = reading_m; since_ = now; have_ = true; return; }
float d = reading_m - anchor_; if (d < 0.0f) d = -d;
if (d > delta_) { anchor_ = reading_m; since_ = now; }
}
bool stuck(uint32_t now) const { return have_ && elapsed(now, since_) > window_; }
private:
float delta_; uint32_t window_; float anchor_; uint32_t since_; bool have_;
};
// ---- 4. a stall detector: the motors are driven but the wheels do not turn ----
class StallDetector {
public:
StallDetector(float min_cmd, uint32_t window_ms) : min_cmd_(min_cmd), window_(window_ms), last_ticks_(0), since_(0), have_(false) {}
void update(float cmd_speed, int32_t ticks, uint32_t now) {
float c = cmd_speed < 0.0f ? -cmd_speed : cmd_speed;
if (c < min_cmd_ || !have_ || ticks != last_ticks_) { last_ticks_ = ticks; since_ = now; have_ = true; }
}
bool stalled(uint32_t now) const { return have_ && elapsed(now, since_) > window_; }
private:
float min_cmd_; uint32_t window_; int32_t last_ticks_; uint32_t since_; bool have_;
};
// ---- 5. the supervisor: between the controller and the motors ----
struct SafetyConfig {
uint32_t cmd_timeout_ms; // a command older than this is dropped
uint32_t range_stale_ms; // no valid range reading for this long while moving forward
float stuck_delta_m; // a moving robot's reading must change by more than this ...
uint32_t stuck_window_ms; // ... within this window
uint32_t stall_ms; // driven but not turning for this long
float stop_m; // never drive forward when the last valid range is below this
float v_max; // hard speed limit, m/s
};
class Supervisor {
public:
explicit Supervisor(const SafetyConfig& c)
: c_(c), cmd_(c.cmd_timeout_ms), estop_(3), stuck_(c.stuck_delta_m, c.stuck_window_ms), stall_(0.05f, c.stall_ms),
faults_(0), last_valid_(0), have_valid_(false), last_range_(-1.0f), moving_(false), cmd_seen_(false), first_cmd_(0) {}
void command(const Cmd& c, uint32_t now) { cmd_.set(c, now); if (!cmd_seen_) { cmd_seen_ = true; first_cmd_ = now; } }
void estop_input(bool pressed) { estop_.sample(pressed); }
bool reset() { if (!estop_.tripped() || estop_.reset()) { faults_ = 0; return true; } return false; }
// a new range measurement arrived (-1 = no echo): call this once per measurement, whatever its value
void range_sample(uint32_t now, float range_m) {
bool valid = range_m >= 0.0f;
if (valid) { last_valid_ = now; have_valid_ = true; last_range_ = range_m; }
stuck_.update(range_m, valid, moving_, now);
}
// one supervision step (call it on a fixed period, faster than the controller): returns the command that may reach the motors
Cmd step(uint32_t now, int32_t ticks_l, int32_t ticks_r) {
Cmd req = cmd_.get(now); // an expired command is zero: expiry is not a latched fault
float fwd = (req.vl + req.vr) * 0.5f;
moving_ = fwd > 0.05f || fwd < -0.05f;
if (estop_.tripped()) faults_ |= F_ESTOP;
if (fwd > 0.05f && elapsed(now, have_valid_ ? last_valid_ : first_cmd_) > c_.range_stale_ms) faults_ |= F_STALE_RANGE; // before the first good reading the clock runs from the first command
if (stuck_.stuck(now)) faults_ |= F_STUCK_RANGE;
stall_.update(fwd, ticks_l + ticks_r, now);
if (stall_.stalled(now)) faults_ |= F_STALL;
if (fwd > 0.05f && have_valid_ && last_range_ < c_.stop_m) faults_ |= F_TOO_CLOSE;
Cmd out = req;
if (faults_ != 0) { out.vl = 0.0f; out.vr = 0.0f; }
if (out.vl > c_.v_max) out.vl = c_.v_max; else if (out.vl < -c_.v_max) out.vl = -c_.v_max;
if (out.vr > c_.v_max) out.vr = c_.v_max; else if (out.vr < -c_.v_max) out.vr = -c_.v_max;
return out;
}
uint8_t faults() const { return faults_; }
bool cmd_expired(uint32_t now) const { return cmd_.expired(now); }
private:
SafetyConfig c_;
ExpiringCmd cmd_;
Estop estop_;
StuckDetector stuck_;
StallDetector stall_;
uint8_t faults_;
uint32_t last_valid_;
bool have_valid_;
float last_range_;
bool moving_;
bool cmd_seen_;
uint32_t first_cmd_;
};
ExpiringCmd. A command is only good for timeout_ms after it was given. If the controller hangs, crashes, or is simply late, the motors get zero, not the last command. (Expiry is not a latched fault: a fresh command restarts the robot.)
Estop. A debounced, latched input. The switch must read “pressed” for n samples in a row to trip; releasing the switch does not restart the robot; reset() is refused while the switch is held.
StuckDetector. While the robot is moving, a distance reading that does not change by more than delta within window_ms is not a measurement. It is not enough for it to be constant: a still robot sees a constant range.
StallDetector. The motors are driven but the wheel ticks do not change.
Supervisor. Sits between the controller and the motors. The controller only asks (command); the supervisor decides what reaches the motors (step): zero if any fault is latched, a stale range while driving forward, a wall closer than a stop distance, and a hard speed limit that applies whatever the controller says.
4. Fault injection on the simulator
A safety rule that has never been triggered is a hope. Fault injection breaks one thing at a chosen moment on the simulator and watches. Here a controller drives at a wall and stops 0.30 m from it, using the front range sensor; when it gets “no echo” it keeps its last command (a naive policy, on purpose, because that is what first versions do). At 2 s one thing breaks; each case is run without and with the supervisor, 20 runs each:
// e_faults.cpp -- fault injection on the simulator: a robot drives at a wall and one thing breaks at t = 2 s (host build; the faults and the simulated robot are assumptions).
// The controller approaches the wall at up to 0.30 m/s and stops 0.30 m from it, using the front range sensor every 60 ms; when it gets "no echo" it keeps its last command (a naive policy, on purpose).
// Each scenario is run without and with the supervisor of safety.h (command timeout 250 ms, stale range 300 ms, stuck window 500 ms, stall 400 ms, stop distance 0.15 m), 20 seeded runs each.
// Scored: runs that hit the wall (the front sensor reached the wall), mean time from the fault to the motors being stopped (tick of 20 ms), and the speed when the robot stops or hits.
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "sim.h"
#include "safety.h"
enum Scenario { NONE, HANG, STUCK_FAR, NO_ECHO, ENCODER_DEAD, WHEELS_BLOCKED, SENSOR_NOISY_BURST };
static const char* NAMES[] = {"no fault (control)", "controller hangs (stops sending commands)", "range sensor stuck at 2.5 m", "range sensor sees no echo",
"encoders dead (ticks frozen)", "wheels blocked (motors turn, robot does not move)", "range sensor stuck at 0.01 m (reads 'touching')"};
struct R { bool hit; double stop_delay; double speed_at_end; bool stopped_by_sup; };
static R run(Scenario sc, bool supervised, uint32_t seed) {
RobotParams rp; SensorParams sp; Arena arena;
SimHW sim(rp, sp, arena, seed * 2654435761u + 12345u); // a well-mixed seed: xorshift started from a small number gives small first values
SafetyConfig cfg = {250, 300, 0.02f, 500, 400, 0.15f, 0.4f};
Supervisor sup(cfg);
const double T_FAULT = 2.0, DT = 0.005;
Cmd cmd = {0.0f, 0.0f}, applied = {0.0f, 0.0f};
float last_range = 3.0f;
double stop_time = -1; bool hit = false; bool sup_stopped = false;
int32_t frozen_l = 0, frozen_r = 0; bool frozen = false;
uint32_t last_ctrl = 0;
for (long k = 0; k < 2000; ++k) { // 10 s
double t = k * DT; uint32_t now = (uint32_t)std::lround(t * 1000.0);
bool fault = t >= T_FAULT;
if (k % 12 == 0) { // the controller, every 60 ms
bool hung = fault && sc == HANG;
if (!hung) {
float r = sim.range_m();
if (fault && sc == STUCK_FAR) r = 2.5f;
if (fault && sc == NO_ECHO) r = -1.0f;
if (fault && sc == SENSOR_NOISY_BURST) r = 0.01f;
if (supervised) sup.range_sample(now, r);
if (r >= 0.0f) last_range = r;
float v = last_range - 0.30f; if (v < 0.0f) v = 0.0f; if (v > 0.30f) v = 0.30f; // r < 0: keeps going on the last reading
cmd.vl = cmd.vr = v;
if (supervised) sup.command(cmd, now);
last_ctrl = now;
} else if (supervised) {
sup.range_sample(now, last_range); // the sensor still works; the controller does not ask for it, so the sample is the stale one
}
}
int32_t tl, tr; sim.read_ticks(tl, tr);
if (fault && sc == ENCODER_DEAD) { if (!frozen) { frozen = true; frozen_l = tl; frozen_r = tr; } tl = frozen_l; tr = frozen_r; }
if (k % 4 == 0) { // the supervisor, every 20 ms
if (supervised) { applied = sup.step(now, tl, tr); if (sup.faults() && !sup_stopped) sup_stopped = true; }
else applied = cmd; // without it the motors keep the last command
}
if (fault && sc == WHEELS_BLOCKED) { sim.drive(0.0f, 0.0f); }
else sim.drive(applied.vl, applied.vr);
sim.step(DT);
if (sim.ray_distance() <= 0.0) hit = true;
double speed = 0.5 * (sim.wheel_l() + sim.wheel_r());
if (fault && stop_time < 0 && std::fabs(applied.vl) < 1e-6 && std::fabs(applied.vr) < 1e-6) stop_time = t;
(void)last_ctrl;
if (hit) { R r = {true, stop_time < 0 ? -1.0 : stop_time - T_FAULT, speed, sup_stopped}; return r; }
}
R r = {false, stop_time < 0 ? -1.0 : stop_time - T_FAULT, 0.5 * (sim.wheel_l() + sim.wheel_r()), sup_stopped};
return r;
}
int main() {
std::printf("fault injection: a robot drives at a wall, one thing breaks at t = 2 s; 20 runs per line\n");
std::printf(" %-52s %-12s %10s %24s %s\n", "scenario", "supervisor", "hit wall", "motors stopped after (s)", "supervisor acted");
for (int s = 0; s < 7; ++s) {
for (int sup = 0; sup < 2; ++sup) {
int hits = 0, acted = 0, nstop = 0; double sum_delay = 0;
for (uint32_t seed = 1; seed <= 20; ++seed) {
R r = run((Scenario)s, sup != 0, seed);
if (r.hit) ++hits;
if (r.stopped_by_sup) ++acted;
if (r.stop_delay >= 0) { sum_delay += r.stop_delay; ++nstop; }
}
char buf[40];
if (s == NONE) std::snprintf(buf, sizeof buf, "-");
else if (nstop) std::snprintf(buf, sizeof buf, "%.3f (%d of 20 stopped)", sum_delay / nstop, nstop); else std::snprintf(buf, sizeof buf, "never");
std::printf(" %-52s %-12s %7d/20 %24s %d/20\n", NAMES[s], sup ? "yes" : "no", hits, buf, acted);
}
}
return 0;
}
fault injection: a robot drives at a wall, one thing breaks at t = 2 s; 20 runs per line
scenario supervisor hit wall motors stopped after (s) supervisor acted
no fault (control) no 0/20 - 0/20
no fault (control) yes 0/20 - 2/20
controller hangs (stops sending commands) no 20/20 never 0/20
controller hangs (stops sending commands) yes 0/20 0.240 (20 of 20 stopped) 0/20
range sensor stuck at 2.5 m no 20/20 never 0/20
range sensor stuck at 2.5 m yes 0/20 0.560 (20 of 20 stopped) 20/20
range sensor sees no echo no 20/20 never 0/20
range sensor sees no echo yes 0/20 0.297 (20 of 20 stopped) 20/20
encoders dead (ticks frozen) no 0/20 7.780 (3 of 20 stopped) 0/20
encoders dead (ticks frozen) yes 0/20 0.420 (20 of 20 stopped) 20/20
wheels blocked (motors turn, robot does not move) no 0/20 never 0/20
wheels blocked (motors turn, robot does not move) yes 0/20 0.699 (20 of 20 stopped) 20/20
range sensor stuck at 0.01 m (reads 'touching') no 0/20 0.040 (20 of 20 stopped) 0/20
range sensor stuck at 0.01 m (reads 'touching') yes 0/20 0.040 (20 of 20 stopped) 0/20
Without the supervisor, three faults drive the robot into the wall in every run: a hung controller (the last command stays on the motors), a range sensor stuck at a far value, and a range sensor that sees no echo (the naive policy keeps going). With it, none does: the motors are stopped 0.24 s after the hang (the 250 ms command timeout), 0.56 s after the sensor sticks (the 500 ms stuck window of this configuration plus the sampling), and 0.30 s after the echo is lost (the 300 ms stale limit). The stuck-at-0.01 m sensor is the instructive harmless one: the controller itself stops on a reading of “touching”, so the fault is safe with or without the supervisor. The blocked wheels and the dead encoders hurt nothing with the walls here, and the supervisor stops them anyway (0.70 s and 0.42 s): a driven motor that does not turn is heating, and a robot that has lost its odometry is blind.
It also has a cost, and the table shows it. In the healthy control runs the supervisor stopped the robot in 2 of 20: the stuck detector fired during the slow creep up to the stopping distance, where the commanded speed is small and the range hardly changes. That is a false alarm, and a latched one: the robot stops short of its goal until someone resets it. Challenge 2 measures the trade between false alarms and detection delay.
Two mistakes the testing found in my own code
A start-up false latch. The first version of the stale-range rule latched a fault at time zero in 4 of 20 healthy runs, with the reading 3.000 m and the robot not yet moving: the rule asked for a valid reading, and the first measurement of those runs was a dropout. A rule that fires before the system has started is wrong; the fix is that, before the first valid reading, the clock for “stale” runs from the first command. A bad seed. Why 4 of 20, when dropouts are 2 %? The seeds were small multiples (77, 154, …) given to a xorshift generator, whose first outputs for small seeds are small numbers, which the simulator reads as a dropout. The runs above use well-mixed seeds. Both were found only because a healthy run was injected with no fault and the supervisor’s reaction was counted.
5. The watchdog, brown-out and the stop button
The software supervisor cannot help when the software itself stops. That is the job of the hardware watchdog (Programming for Robotics with Arduino C++ 8): a timer that resets the chip unless the program feeds it, fed here only when every task has checked in since the last feed, so a wedged control task or echo task cannot be hidden by a loop that still runs. robot_ch12.ino turns the motors off first in setup(), before anything else can go wrong, and enables the watchdog at 250 ms.
On a board a supply that sags can corrupt the chip before the watchdog can do anything; the chip has a brown-out detector that holds it in reset below a voltage set by a fuse. The Uno’s core says what the board is programmed with: in boards.txt, uno.bootloader.extended_fuses=0xFD and uno.bootloader.high_fuses=0xDE. That I verified. What those bytes mean, a brown-out level of about 2.7 V and the watchdog not being forced on by a fuse, is what I remember of the ATmega328P data sheet and I did not check it; read the data sheet before you rely on it, and note that a motor that stalls and sags the supply is exactly the case it is for.
An emergency stop that is code is a contradiction: code can only stop what the code can still control. A real stop must cut the motor power in hardware, with a switch in the supply, so that no software state can keep the motors running. In robot_ch12.ino the bumper switch on pin 11 feeds the latched Estop of safety.h as a stand-in, and the comment in the sketch says so.
6. A log that survives the fault
After a fault there is no room to print the whole history, and by then it is too late to ask what the robot was doing. A ring buffer keeps the last N events in a fixed array, overwriting the oldest, and is dumped when a fault latches. RingLog in ringlog.h stores a time, a code and a value (7 bytes on the AVR) and has no heap:
// ringlog.h -- an event log in a fixed ring buffer (Programming for Robotics with Arduino C++ 12). Plain C++11, no heap.
// A robot that has just misbehaved cannot print everything it did: there is no room and no time. It keeps the LAST N events in RAM and dumps them after a fault.
#pragma once
#include <stdint.h>
struct LogEvent { uint32_t t_ms; uint8_t code; int16_t value; }; // 7 bytes of data; 8 with padding on a PC, 7 on the AVR
template <uint8_t N>
class RingLog {
public:
RingLog() : head_(0), count_(0), total_(0) {}
void add(uint32_t t_ms, uint8_t code, int16_t value) {
buf_[head_].t_ms = t_ms; buf_[head_].code = code; buf_[head_].value = value;
head_ = (uint8_t)((head_ + 1) % N);
if (count_ < N) ++count_;
++total_;
}
uint8_t size() const { return count_; }
uint32_t total() const { return total_; } // events ever added: total() - size() have been overwritten
const LogEvent& at(uint8_t i) const { return buf_[(uint8_t)((head_ + N - count_ + i) % N)]; } // 0 = oldest kept
private:
LogEvent buf_[N];
uint8_t head_, count_;
uint32_t total_;
};
How large N must be is a question with an answer you can compute, and challenge 3 does. First what all of it costs on the Uno. The cost-test sketch has seven variants (baseline, then one safety piece each, fed from analogRead and printed as an integer so the compiler cannot remove it):
Most of the flash is the floating-point library, not the safety logic: Estop has no floating-point arithmetic, is 64 bytes and 23 instructions and costs +40 bytes of flash; the others pull in compare, multiply and subtract routines that the first of them pays for (+810 for ExpiringCmd, +1124 for StuckDetector, which are mostly the same routines counted again because each variant is built alone). In a sketch that already uses floats (every sketch of this course after the first chapters does) the marginal cost is the function itself: 180, 294, 270 and 1,198 bytes. The log costs RAM, not flash: 7 bytes an event, 168 for 24, plus 6 for its bookkeeping.
7. The robot
robot_ch12.ino is the robot of Programming for Robotics with Arduino C++ 8 (the Timer1 1 kHz tick, the non-blocking echo driver, the encoders on interrupts, the table-driven avoider) with the safety layer between the avoider and the motors. The avoider only asks for a command; the supervisor, stepped every 20 ms with the encoder ticks, decides what reaches the motors; every range measurement, every change of the applied command and every change of the fault mask goes into a 24-event ring; when a fault latches the ring is dumped over the serial line once; sending r over the serial line asks for a reset, which is refused while the stop button is held.
// robot_ch12.ino -- Programming for Robotics with Arduino C++, chapter 12: chapter 8's robot with a safety supervisor between the controller and the motors,
// a hardware watchdog, an emergency-stop input and a ring-buffer event log that is dumped when a fault latches.
// Compile-checked for the Uno (arduino:avr:uno). NOT run on a board: nothing was attached, the watchdog was never tripped on real hardware, and the thresholds are the SIMULATOR's.
// The bumper switch on pin 11 stands in for an emergency stop. A real emergency stop must cut the motor power in HARDWARE: code can only stop what the code can still control.
#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"
#include "safety.h"
#include "ringlog.h"
const float V_MAX_MPS = 0.5f;
const uint8_t DEAD_DUTY = 40; // ASSUMED: measure yours
const float PER_TICK = 6.2831853f * 0.033f / 360.0f;
volatile uint32_t g_ms = 0;
volatile uint8_t g_control_due = 0, g_echo_due = 0, g_report_due = 0;
volatile int32_t g_ticks_l = 0, g_ticks_r = 0;
ISR(TIMER1_COMPA_vect) { // every 1 ms: only counts and sets flags
static uint8_t c20 = 0, c60 = 0;
static uint16_t c500 = 0;
++g_ms;
if (++c20 >= 20) { c20 = 0; 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() { 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));
}
// the controller: as in chapter 8
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;
static bool trig_level = false;
static float g_range = -1.0f;
// the safety layer
static const SafetyConfig SAFE = {250, 300, 0.02f, 1000, 400, 0.15f, 0.4f}; // from the simulator runs of this chapter; tune on the real robot
static Supervisor sup(SAFE);
static RingLog<24> logbuf; // 24 events x 7 bytes = 168 bytes of RAM
static uint8_t last_mask = 0;
static bool dumped = false;
enum : uint8_t { EV_RANGE = 1, EV_CMD = 2, EV_FAULT = 3, EV_ESTOP = 4 };
static float last_v = -9.0f;
static void dump_log() {
Serial.print(F("-- log: ")); Serial.print(logbuf.size()); Serial.print(F(" of ")); Serial.print(logbuf.total()); Serial.println(F(" events"));
for (uint8_t i = 0; i < logbuf.size(); ++i) {
const LogEvent& e = logbuf.at(i);
Serial.print(e.t_ms); Serial.print(' '); Serial.print(e.code); Serial.print(' '); Serial.println(e.value);
}
}
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);
drive(0.0f, 0.0f); // the motors are off BEFORE anything else can go wrong
EICRA = _BV(ISC00) | _BV(ISC10); EIFR = _BV(INTF0) | _BV(INTF1); EIMSK = _BV(INT0) | _BV(INT1);
timer1_begin_1khz();
wdt_enable(WDTO_250MS);
}
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);
bool new_range = false;
if (st == Echo::READY) { g_range = (float)median.update((int16_t)(echo_us_to_m(echo.width_us()) * 1000.0f + 0.5f)) * 0.001f; new_range = true; }
else if (st == Echo::TIMEOUT) { g_range = -1.0f; new_range = true; }
if (new_range) { sup.range_sample(now_ms(), g_range); logbuf.add(now_ms(), EV_RANGE, (int16_t)(g_range * 1000.0f)); }
if (g_echo_due) { g_echo_due = 0; echo.start(); beats.checkin(1); }
if (g_control_due) {
g_control_due = 0;
uint32_t now = now_ms();
bool bump = digitalRead(PIN_BUMP) == LOW;
sup.estop_input(bump);
Sense s; s.front_m = g_range; s.right_m = -1.0f; s.bump = bump;
sup.command(machine.update(s, now), now); // the controller only ASKS; the supervisor decides what reaches the motors
int32_t l, r; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { l = g_ticks_l; r = g_ticks_r; }
Cmd out = sup.step(now, l, r);
drive(out.vl, out.vr);
if (out.vl != last_v) { logbuf.add(now, EV_CMD, (int16_t)(out.vl * 1000.0f)); last_v = out.vl; }
if (sup.faults() != last_mask) { logbuf.add(now, EV_FAULT, (int16_t)sup.faults()); last_mask = sup.faults(); dumped = false; }
beats.checkin(0);
}
if (sup.faults() != 0 && !dumped) { dump_log(); dumped = true; } // after a latched fault: say what happened, once
if (Serial.available() && Serial.read() == 'r') { if (sup.reset()) { last_mask = 0; dumped = false; Serial.println(F("reset")); } else Serial.println(F("release the stop button first")); }
if (g_report_due) {
g_report_due = 0;
Serial.print(now_ms()); Serial.print(F(" ms range ")); Serial.print(g_range, 2); Serial.print(F(" faults 0x")); Serial.println(sup.faults(), HEX);
}
if (beats.all_alive()) { wdt_reset(); beats.clear(); }
}
It compiles for the Uno under --warnings all with no warning from the sketch to:
Sketch uses 9692 bytes (30%) of program storage space. Maximum is 32256 bytes.
Global variables use 644 bytes (31%) of dynamic memory, leaving 1404 bytes for local variables. Maximum is 2048 bytes.
That is 9,692 bytes of flash and 644 bytes of RAM: 2,774 bytes of flash and 317 bytes of RAM more than the robot of Programming for Robotics with Arduino C++ 8 (6,918 and 327), of which 168 bytes of RAM are the log. It was not run: nothing was attached, the watchdog was never tripped, the supervisor’s thresholds are those of the simulator and the hardware may need others, and the false alarm of section 4 would show up on a real robot too.
8. Where to go next
This is from memory and nothing in it was run for this course; treat it as a list of questions to check against the data sheets, not as results. The Uno R3 was chosen because its limits make the lessons visible: 2 KB of RAM, 32 KB of flash, 16 MHz, no floating-point unit. Many later boards remove one limit at a time: more RAM and flash, a floating-point unit in the 32-bit ARM parts (which would change the float-against-fixed question of Programming for Robotics with Arduino C++ 10), several cores or radios in the ESP32 and the Pico. What does not go away is the method of the course: write the logic as plain C++ behind a small hardware interface, test it on the PC, and count what it costs.
Two steps up from the cooperative scheduler of Programming for Robotics with Arduino C++ 8: a real-time operating system (FreeRTOS is the common one) gives preemptive tasks with priorities, so a slow task can no longer delay a fast one, at the price of a stack for each task and the need for locks around shared data; and micro-ROS puts a small ROS 2 node on a microcontroller, so the board can talk to the rest of a robot as one more sensor or actuator. The supervisor of this chapter does not become unnecessary on any of them: the safe state is still stopped and the guard still must not depend on the thing it guards.
9. The course in one table
The running theme of the course was the budget. Here is what each chapter’s whole-robot sketch compiled to for the Uno (Programming for Robotics with Arduino C++ 1 has only size tests, and no whole-robot sketch). All are compile-time figures from the compiler; none was run on a board.
chapter sketch flash (bytes) RAM (bytes) what it added
2 robot_ch2.ino 9,606 936 talking to the hardware
3 robot_ch3.ino 7,726 413 a simulator to test in
4 robot_ch4.ino 8,626 433 sensor code and filtering
5 robot_ch5.ino 8,868 409 driving and odometry
6 robot_ch6.ino 7,638 541 control loops
7 robot_ch7.ino 7,114 381 state machines
8 robot_ch8.ino 6,918 327 interrupts, timing, the watchdog
9 robot_ch9.ino 11,388 943 planning in kilobytes
10 robot_ch10.ino 9,726 574 state estimation
11 robot_ch11.ino 10,040 437 robot arms
12 robot_ch12.ino 9,692 644 the safety supervisor and the event log
(Uno R3: 32,256 bytes of flash after the bootloader, 2,048 bytes of RAM.)
The robot never needed more than 11,388 bytes of flash (35 %) or 943 bytes of RAM (46 %), so the Uno was enough; where it was tight was RAM (the chapter 9 planner left 61 bytes of stack) and, for anything with floats, the library. And an honest summary of the status of the course: the logic was run on a PC, against simulated sensors whose numbers were my assumptions; the sketches were compiled for the Uno and their sizes are the compiler’s; no sketch was ever run on a board, no time was ever measured, no sensor, motor, gyro or servo was ever connected. The first thing to do with a real robot is to take each assumption of this course and replace it with a measurement.
10. What the numbers can and cannot be trusted for
What they show. The tests pass, and a suite that passes can be shown to fail: 20 of 21 mutants killed after the first run showed 14. Three faults that crash a naive robot into a wall in every run do not once the supervisor is between the controller and the motors. Expiring outputs, a latched stop, stuck and stall detectors and a log are small: 64 to 1,198 bytes of code each. The costs on the Uno are bytes, instructions and library calls.
What they do not show. The faults are the ones I thought of; a robot fails in ways nobody thought of. The thresholds were tuned on a simulator and may be wrong on a robot. The supervisor itself can have bugs, and it is checked only by these tests. The tests exercise the host build; the interrupts, the pins, the watchdog and the brown-out detector were never tested. No time was measured: “the motors are stopped 0.24 s after the hang” is simulated time with an assumed motor lag, not a stopping time on a robot. robot_ch12.ino was compiled, not run.
Challenge 1: How long may a command live?
Sweep the command timeout of the supervisor from 50 ms to 4 s. For each value find how far the robot travels after the controller hangs while driving at cruise speed toward a wall 3 m from the start (the hang happens at 6.5 s into the run), and, in a run with no fault but a controller that is sometimes late (5 % of its runs 150 ms late, 1 % 400 ms late), how often the timeout expires a command that was only late. Choose a timeout and say what limits it from above and from below.
For a change threshold of 10, 20 and 40 mm and a window of 250 ms to 4 s, run the supervisor on 100 healthy approaches to the wall (they end with a slow creep) and on 100 runs where the range sensor sticks at 2.5 m. Report the false alarms and the detection delay for every pair. Which pair would you use, and what does the delay cost in distance travelled at 0.3 m/s?
Log every range measurement, every change of the applied command and every change of the fault mask while the range sensor sticks at 2 s and the fault latches. For ring buffers of 8 to 255 events report how much history the dump holds, whether it reaches back past the moment the sensor stuck, and what it costs in RAM at 7 bytes an event. Choose a size.
Unit tests. A 20-line harness (CHECK, CHECK_NEAR); 23 tests, 1,360 checks on the logic of the course; expected numbers come from maths and definitions, not from the code’s own output.
Mutation testing. One small change per mutant; killed = a check fails. First run: 14 of 21 killed (7 holes in the tests); after the new tests 20 of 21; the survivor is an equivalent mutant. A green suite means nothing until it has failed on purpose.
Principles. The safe state is stopped; the guard must not depend on what it guards; faults latch until a person resets.
Pieces. ExpiringCmd (zero after the timeout), Estop (debounced, latched, reset only when released), StuckDetector (moving and no change), StallDetector (driven and no ticks), Supervisor (between controller and motors, speed limit), RingLog (last N events).
Fault injection (simulated, 20 runs). Hung controller, stuck range, no echo: 20/20 hit the wall without the supervisor, 0/20 with it; motors stopped after 0.24, 0.56 and 0.30 s. It also stopped 2 of 20 healthy runs (a false alarm in the final creep).
Timeout (challenge 1). 4 s: 50 of 50 hit the wall; 2 s: 0.62 m after a hang; 500 ms: 0.17 m and no spurious expiries with a controller up to 400 ms late; 250 ms: 1.3 spurious expiries per 10 s.
Stuck detector (challenge 2). 20 mm and 500 ms: 10 false alarms in 100 healthy runs; 20 mm and 1 s: none, detected after 1.06 s (0.32 m at 0.3 m/s); 250 ms: 34 to 100 false alarms.
Log (challenge 3). About 19 events a second near the fault; a log of 32 events (224 bytes) reaches back 0.68 s past the moment the sensor stuck, 64 (448 bytes) holds the whole 3 s run.
Hardware. Watchdog fed only when every task has checked in; motors off first in setup(); a real emergency stop cuts power in hardware; Uno fuses 0xFD and 0xDE (read from boards.txt; their meaning from memory, unchecked).
Cost on the Uno (compiled, not run). Supervisor +2,450 bytes flash alone (mostly the float library), +127 RAM; Estop +40 flash; RingLog<24> 174 RAM. robot_ch12.ino: 9,692 bytes flash (30 %), 644 bytes RAM (31 %).
Not run: anything on a board; the watchdog, the brown-out detector or the stop button; any real fault; any time.
Course complete
That is the last chapter of Programming for Robotics with Arduino C++: twelve chapters, from the first setup() and loop() to a robot with a safety supervisor. The companion course, Programming for Robotics, covers the same topics in Python, in the same order. What comes next is the part this course could not do: put a robot on the table, measure what it really does, and replace every number that this course marked as an assumption.