Programming for Robotics with Arduino C++ 2 ended with a sketch that nobody has run: it compiles for the Uno, and that is all anyone knows. A robot cannot be debugged by wiring it and hoping. Every hardware mistake costs a minute of re-uploading, a noisy sensor never gives the same reading twice, and a real wall is not a place to find out that a controller overshoots. This chapter builds the thing that stands in for the world: a small simulator that runs on the PC, behind the same hardware interface as the real pins, so that the robot code is tested before it is flashed.
The chapter is about two things at once: how the simulator works, and, more important, how far to trust it. A simulator that is never tested against anything is a way of producing confident numbers. So the simulator is tested first against answers worked out by hand, then used to find three things about the robot that a first look at the code does not show, and then its limits are stated plainly.
What was run, and what was not
Run on a PC (g++ 16.2, C++11, -Wall -Wextra -pedantic, no warnings): the simulator, its tests, every experiment with an output under it, and the challenge solutions. The simulator is a model with assumed parameters (motor lag, noise, dropouts, wheel size); none of them was measured on a real robot, so results show how the code behaves in a stated world, not how a real robot would behave. Compiled for the Uno, not run (arduino-cli 1.6.0, core arduino:avr 1.8.8): robot_ch3.ino. The flash and RAM figures are the compiler’s; the sketch’s encoders are not wired (they need interrupts, chapter 4), so on the board the odometry would stand still. No board, motor, encoder or sensor was attached. Nothing in this chapter was measured on hardware.
1. What a simulator is for, and what it cannot say
A simulator earns its place in four ways. It is fast: compiling and running the 2,400 twelve-second runs of section 6 took 1.4 seconds in total on this PC. It is repeatable: the same seed gives the same noise, so a failure can be reproduced exactly. It knows the truth: the robot’s belief can be compared with where it really is, which no real robot can do. And it is safe: it can drive a robot into a wall a thousand times.
It cannot tell you what you did not put into it. A simulator contains the physics its author thought of, and a robot fails mostly for reasons the author did not think of. The right use is therefore modest: to find the bugs and the misunderstandings in your code cheaply, to make comparisons (this gain against that one), and to build a test that keeps a fixed problem fixed. It is not a replacement for putting the robot on the floor; it is what makes the first floor test a short one.
2. The seam: four functions
The robot code of this course does not call analogWrite or digitalRead. It calls four functions on an object the code is a template of, the HW parameter, exactly as WallRobot<HW> did in Programming for Robotics with Arduino C++ 1:
Function
Meaning
float range_m()
distance ahead in metres; negative means no echo
void read_ticks(int32_t& l, int32_t& r)
cumulative encoder ticks of each wheel, signed
void drive(float vl, float vr)
wheel surface speeds in m/s; negative means backwards
bool bumped()
the bumper switch
Anything with those four functions is a HW, and this chapter has five of them: PinHW (the real pins, section 8), SimHW (the simulator), RecordingHW (wraps another and writes down what the controller saw and did), ReplayHW (plays a recording back) and AveragedRange (wraps another and averages its range, in challenge 1). The controller does not know which one it has. Here it is in full: it is the part that will run on the board, and it is plain C++ with no Arduino call in it.
// drive.h -- the robot logic for a two-wheel robot that drives to a wall and stops short of it. Plain C++11: no Arduino calls, no heap; it needs only sinf and cosf from <math.h>.
// It compiles unchanged for the Uno and for the PC. The hardware is a template parameter HW with exactly four functions:
// float range_m(); // distance ahead in metres; negative means "no echo"
// void read_ticks(int32_t& left, int32_t& right); // cumulative encoder ticks (signed)
// void drive(float v_left, float v_right); // wheel surface speeds, m/s (negative = backwards)
// bool bumped(); // true if the bumper is pressed
#pragma once
#include <stdint.h>
#include <math.h> // sinf, cosf: on the Uno from avr-libc
inline float clamp_f(float v, float lo, float hi) { return v < lo ? lo : (v > hi ? hi : v); }
enum DriveFault : uint8_t { FAULT_NONE = 0, FAULT_NO_RANGE = 1, FAULT_BUMPED = 2 };
struct DriveConfig {
float stop_m; // stop this far from the wall
float k_range; // speed per metre of distance still to go (1/s)
float vmax; // cruise speed (m/s)
float k_heading; // turn rate per radian of heading error (1/s); 0 switches heading hold off
float wheel_r, track; // metres
int ticks_per_rev;
uint8_t max_dropouts; // this many consecutive "no echo" readings in a row is a fault
};
template <class HW>
class DriveRobot {
public:
DriveRobot(HW& hw, const DriveConfig& c)
: hw_(hw), c_(c), range_(0.0f), have_range_(false), dropouts_(0), total_dropouts_(0), fault_(FAULT_NONE),
x_(0.0f), y_(0.0f), th_(0.0f), tl_(0), tr_(0), first_ticks_(true), vl_(0.0f), vr_(0.0f) {}
void sense(uint32_t) {
float m = hw_.range_m();
if (m < 0.0f) { // no echo: keep the last good range, but count, and give up after too many
++dropouts_; ++total_dropouts_;
if (dropouts_ > c_.max_dropouts) fault_ = FAULT_NO_RANGE;
} else {
dropouts_ = 0; range_ = m; have_range_ = true;
}
if (hw_.bumped()) fault_ = FAULT_BUMPED;
int32_t l, r;
hw_.read_ticks(l, r);
if (first_ticks_) { tl_ = l; tr_ = r; first_ticks_ = false; }
const float per_tick = 6.2831853f * c_.wheel_r / (float)c_.ticks_per_rev;
float dl = (float)(l - tl_) * per_tick, dr = (float)(r - tr_) * per_tick; // how far each wheel has gone since the last look
tl_ = l; tr_ = r;
float d = 0.5f * (dl + dr), dth = (dr - dl) / c_.track;
// dead reckoning: advance along the middle of the turn
float mid = th_ + 0.5f * dth;
#ifdef DRIVE_FAST_TRIG
float m2 = mid * mid; // first terms of the series: cheap, and ONLY good for small angles (section 7 measures where it fails)
float c = 1.0f - 0.5f * m2, s = mid * (1.0f - m2 / 6.0f);
#else
float c = cosf(mid), s = sinf(mid); // correct at any heading; costs flash on the Uno (section 7)
#endif
x_ += d * c; y_ += d * s; th_ += dth;
}
void think(uint32_t) {
if (fault_ != FAULT_NONE || !have_range_) { vl_ = vr_ = 0.0f; return; } // no range yet, or a fault: stand still
float v = clamp_f(c_.k_range * (range_ - c_.stop_m), 0.0f, c_.vmax);
float w = -c_.k_heading * th_ * (v / c_.vmax); // hold the heading at 0, fading out as the robot slows to a stop
vl_ = v - 0.5f * w * c_.track;
vr_ = v + 0.5f * w * c_.track;
}
void act(uint32_t) { hw_.drive(vl_, vr_); }
float range() const { return range_; }
float x() const { return x_; }
float y() const { return y_; }
float theta() const { return th_; }
DriveFault fault() const { return fault_; }
uint32_t dropouts() const { return total_dropouts_; }
float command_left() const { return vl_; }
float command_right() const { return vr_; }
static void sense_task(void* c, uint32_t now) { static_cast<DriveRobot*>(c)->sense(now); }
static void think_task(void* c, uint32_t now) { static_cast<DriveRobot*>(c)->think(now); }
static void act_task(void* c, uint32_t now) { static_cast<DriveRobot*>(c)->act(now); }
private:
HW& hw_;
DriveConfig c_;
float range_;
bool have_range_;
uint8_t dropouts_;
uint32_t total_dropouts_;
DriveFault fault_;
float x_, y_, th_;
int32_t tl_, tr_;
bool first_ticks_;
float vl_, vr_;
};
Four design choices in it are worth noticing, each a lesson of an earlier chapter put to use. A reading of no echo keeps the last good range and is counted, and too many in a row is a fault that stops the robot, because an unreadable sensor must not be treated as a clear road. The speed is a clamped proportional of the distance still to go (it cannot go negative: the robot never reverses). The heading hold fades out as the robot slows, so that it does not spin the robot on the spot at the wall. And the dead reckoning uses sinf and cosf, with a switch, DRIVE_FAST_TRIG, for a cheaper version that section 8 tests and shows to be unsafe at large angles.
3. The simulator
The simulator is a class with the same four functions plus a step(dt) that moves the world on. It is host only: it uses <cmath> and doubles and is never compiled for the Uno. What it models, and what it leaves out, is the list that decides how far to trust it:
Modelled (all values are assumptions)
Not modelled
two wheels, 0.033 m radius, 0.15 m apart, a pose integrated every millisecond
motor speed that follows its command with a 0.1 s lag, an 8-bit duty (through chapter 2’s speed_to_pwm), a weaker or stronger motor
encoders that count whole ticks (360 per wheel turn) from the true wheel travel
an ultrasonic range found by a ray to the nearest wall of a 3.0 × 2.0 m rectangle; Gaussian noise; readings with no echo; the echo width known only to the polling interval (chapter 2)
a seeded random generator, the same on every machine
wheel slip and stiction (a motor that will not turn below some duty)
battery voltage falling
a sensor beam with width, or a wall at an angle that bounces the sound away
the I2C bus, the IMU, backlash
variable loop timing: the control task runs exactly every 20 ms
anything else in the room
// sim.h -- a small differential-drive simulator for the PC (HOST ONLY: it uses <cmath>, doubles and a lot of RAM; it never runs on the Uno).
// It stands behind the same hardware interface as the real pins: range_m(), read_ticks(), drive(), bumped().
#pragma once
#include <stdint.h>
#include <cmath>
#include "conv.h"
#ifndef SIMREAL
#define SIMREAL double // the simulator's own arithmetic; the robot code is float either way, as on the board
#endif
typedef SIMREAL real;
const double SIM_PI = 3.14159265358979323846;
// A tiny reproducible random generator: the same seed gives the same numbers on every machine and compiler (std::mt19937's distributions do not).
struct Rng {
uint32_t s;
explicit Rng(uint32_t seed) : s(seed ? seed : 1u) {}
uint32_t next() { s ^= s << 13; s ^= s >> 17; s ^= s << 5; return s; } // xorshift32
double uniform() { return (next() >> 8) * (1.0 / 16777216.0); } // [0, 1)
double normal() { // Box-Muller
double u1 = uniform();
if (u1 < 1e-12) u1 = 1e-12;
double u2 = uniform();
return std::sqrt(-2.0 * std::log(u1)) * std::cos(2.0 * SIM_PI * u2);
}
};
struct RobotParams {
real wheel_r = 0.033; // m
real track = 0.15; // m between the wheels
int ticks_per_rev = 360; // encoder ticks per wheel revolution
real vmax = 0.5; // wheel surface speed at a PWM duty of 255 (m/s), before the side gain
real tau = 0.10; // motor lag, seconds: a wheel closes 63 % of a speed change in this time
real gain_l = 1.0, gain_r = 1.0; // how strong each motor is: 0.95 means 5 % weaker for the same duty
bool pwm_quantise = true; // true: commands go through speed_to_pwm (8-bit duty), as on the board
real half_length = 0.06; // from the centre to the sensor at the front
};
struct SensorParams {
real sigma_m = 0.005; // Gaussian noise on the distance (m): an ASSUMPTION, not a measured sensor
real dropout = 0.02; // probability that a reading returns no echo
real poll_us = 100.0; // the echo is measured by polling, so its width is a multiple of this (chapter 2)
real max_m = 4.0, min_m = 0.02;
};
struct Arena { real w = 3.0, h = 2.0; }; // a rectangle with a corner at the origin
class SimHW {
public:
SimHW(const RobotParams& rp, const SensorParams& sp, const Arena& arena, uint32_t seed)
: x(0.3), y(1.0), th(0.0), rp_(rp), sp_(sp), arena_(arena), rng_(seed), wl_(0), wr_(0), tl_(0), tr_(0), sl_(0), sr_(0), t(0) {}
// ---- the hardware interface the robot code sees ----
float range_m() { // one new measurement per call; -1 means no echo
real d = ray_distance();
if (d > sp_.max_m || d < sp_.min_m) return -1.0f;
if (rng_.uniform() < sp_.dropout) return -1.0f;
real noisy = d + sp_.sigma_m * rng_.normal();
if (noisy < 0) noisy = 0;
double us = (double)m_to_echo_us((float)noisy);
us = std::floor(us / sp_.poll_us) * sp_.poll_us; // the echo width is only known to one poll interval
return echo_us_to_m((uint32_t)us);
}
void read_ticks(int32_t& l, int32_t& r) const { l = tl_; r = tr_; }
void drive(float vl, float vr) { cmd_l_ = vl; cmd_r_ = vr; }
bool bumped() const { return ray_distance() <= 0.0; }
// ---- physics: advance by dt seconds ----
void step(real dt) {
real target_l = target_speed(cmd_l_, rp_.gain_l), target_r = target_speed(cmd_r_, rp_.gain_r);
if (rp_.tau > 0) { wl_ += (target_l - wl_) * dt / rp_.tau; wr_ += (target_r - wr_) * dt / rp_.tau; }
else { wl_ = target_l; wr_ = target_r; }
sl_ += wl_ * dt;
sr_ += wr_ * dt;
real v = (wl_ + wr_) / 2, w = (wr_ - wl_) / rp_.track;
real mid = th + w * dt / 2; // midpoint integration of the heading
x += v * std::cos(mid) * dt;
y += v * std::sin(mid) * dt;
th += w * dt;
real per_tick = 2.0 * SIM_PI * rp_.wheel_r / rp_.ticks_per_rev;
tl_ = (int32_t)std::floor(sl_ / per_tick);
tr_ = (int32_t)std::floor(sr_ / per_tick);
t += dt;
}
real ray_distance() const { // from the sensor at the front of the robot to the nearest wall, along the heading
real px = x + rp_.half_length * std::cos(th), py = y + rp_.half_length * std::sin(th);
if (px <= 0 || px >= arena_.w || py <= 0 || py >= arena_.h) return 0.0;
real dx = std::cos(th), dy = std::sin(th), best = 1e9;
if (dx > 1e-12) best = std::fmin(best, (arena_.w - px) / dx); else if (dx < -1e-12) best = std::fmin(best, (0 - px) / dx);
if (dy > 1e-12) best = std::fmin(best, (arena_.h - py) / dy); else if (dy < -1e-12) best = std::fmin(best, (0 - py) / dy);
return best;
}
const RobotParams& params() const { return rp_; }
real x, y, th; // the TRUTH: only the simulator knows it
real wheel_l() const { return wl_; }
real wheel_r() const { return wr_; }
real time() const { return t; }
private:
real target_speed(float cmd, real gain) const {
real mag = cmd < 0 ? -cmd : cmd;
real sign = cmd < 0 ? -1.0 : 1.0;
if (rp_.pwm_quantise) return sign * speed_to_pwm((float)mag, (float)rp_.vmax) / 255.0 * rp_.vmax * gain;
return cmd * gain;
}
RobotParams rp_;
SensorParams sp_;
Arena arena_;
Rng rng_;
real wl_, wr_;
int32_t tl_, tr_;
real sl_, sr_, t;
float cmd_l_ = 0.0f, cmd_r_ = 0.0f;
};
One detail is easy to miss and mattered: the random generator is the simulator’s own, a few lines of xorshift with a Box-Muller step for the Gaussian, not the C++ library’s. The library’s random distributions are allowed to give different numbers on different compilers, so a seed would not name one run everywhere. With the simulator’s own generator a seed does, and challenge 3 uses that.
4. Test the simulator first
Before the simulator is allowed to say anything about the robot, it is checked against numbers worked out by hand: a straight run with motor lag, a quarter-circle arc, the encoder count for one metre of travel, the duty quantisation, the range to the walls in four directions, and the noise model.
physics:
PASS straight 0.2 m/s for 2 s with 0.1 s motor lag: x got 0.68020 want 0.68000 (tolerance 0.0005)
PASS ... and y stays got 1.00000 want 1.00000 (tolerance 1e-09)
PASS quarter arc: heading (rad) got 1.57067 want 1.57067 (tolerance 1e-06)
PASS quarter arc: x = 0.3 + R sin(theta) got 0.52500 want 0.52500 (tolerance 0.0005)
PASS quarter arc: y = 1.0 + R (1 - cos(theta)) got 1.22497 want 1.22497 (tolerance 0.0005)
PASS encoder ticks after 1 m of wheel travel (left) got 1736.00000 want 1736.00000 (tolerance 0.5)
PASS encoder ticks after 1 m of wheel travel (right) got 1736.00000 want 1736.00000 (tolerance 0.5)
PASS 0.25 m/s through the 8-bit duty: wheel speed got 0.25098 want 0.25098 (tolerance 1e-09)
range sensor (geometry worked out by hand; the sensor sits 0.06 m in front of the centre):
PASS facing +x from (0.3, 1.0) got 2.64007 want 2.64000 (tolerance 0.001)
PASS facing +y from (0.3, 1.0) got 0.93999 want 0.94000 (tolerance 0.001)
PASS 45 degrees from (1.0, 0.5) got 2.06126 want 2.06117 (tolerance 0.001)
PASS facing -x from (1.0, 0.5) got 0.93999 want 0.94000 (tolerance 0.001)
noise model:
PASS mean of 200000 readings of 2.64 m got 2.63999 want 2.64000 (tolerance 0.001)
PASS spread of the readings (sigma 0.010 m) got 0.00998 want 0.01000 (tolerance 0.0007)
PASS fraction of readings with no echo (10 %) got 0.09823 want 0.10000 (tolerance 0.003)
PASS poll 100 us: 2.64 m reads (a multiple of 17.15 mm) got 2.62395 want 2.62395 (tolerance 0.0005)
PASS ... and is below the truth by 0 to 17.15 mm (one step) got 0.01605 want 0.00858 (tolerance 0.00858)
PASS same seed: readings that agree out of 1000 got 1000.00000 want 1000.00000 (tolerance 0)
PASS different seed: readings that agree out of 1000 got 211.00000 want 200.00000 (tolerance 200)
0 failure(s)
All 19 checks pass, and each was set up so that a wrong simulator would fail. The straight run reaches x = 0.68020 where the lag formula (x = x0 + v(t - τ(1 - e-t/τ))) gives 0.68000: the 0.2 mm is the millisecond steps. The arc ends at (0.52500, 1.22497) for a radius of 0.225 m, which is what the geometry says, and one metre of wheel travel is 1736 ticks, which is 1 / (2π × 0.033) × 360 = 1736.3 by hand. The ranges are hand-geometry (the 45° case, 2.06117 m, I worked out on paper as (2 - 0.54243) / sin 45°). A tolerance of a millimetre or two is allowed where the hand arithmetic itself was rounded.
Two of the checks taught something. The dropout fraction came out at 9.5 % where 10 % was set, 2.3 standard errors low, and I did not simply widen the tolerance: I tested the random generator alone (12 seeds, 200,000 draws each, average 0.0999) and the sensor path alone (12 seeds, average 9.95 %), and the low result was seed 7 being an ordinary outlier. The test now uses ten times as many readings (9.82 %, inside a tolerance of 0.3 %). The second: with seeds 42 and 43 the readings agree on 211 of 1000, which looks like a bug until you remember that the range is quantised to 17 mm steps and a noise of 20 mm is only about one step wide, so different noise often gives the same reading. A test that expects different seeds to give different results must allow for what the quantiser throws away.
5. The robot in the simulator
The first experiment: from (0.30, 1.00), heading toward the wall at x = 3.0 m, with the stop line at 0.25 m. Five runs: ideal motors; then the right motor made 5 % weak, with the heading hold off and then at gains of 2, 6 and 20.
// e_drive.cpp -- the robot in the simulator: ideal motors, then a weak right motor with the heading hold off and at four strengths (host build)
#include <cstdio>
#include <initializer_list>
#include "harness.h"
static void show(const char* label, const Outcome& o, double start_y) {
const char* f = o.fault == FAULT_NONE ? "none" : o.fault == FAULT_NO_RANGE ? "NO_RANGE" : "BUMPED";
std::printf(" %-30s x %5.3f y %6.3f drift %+7.1f mm heading %+7.2f deg odometry %+7.2f deg true range %5.3f m settled %4.1f s fault %s\n",
label, o.x, o.y, (o.y - start_y) * 1000.0, o.th * 180.0 / SIM_PI, o.odo_th * 180.0 / SIM_PI, o.true_range, o.settle_s, f);
}
int main() {
RobotParams rp;
SensorParams sp; // 5 mm noise, 2 % dropouts, polled every 100 us (assumed values)
Arena arena;
DriveConfig cfg = default_config();
std::printf("from (0.30, 1.00) heading +x toward the wall at x = 3.0 m, stop line 0.25 m, 10 s, seed 1:\n");
{
SimHW w(rp, sp, arena, 1);
show("ideal motors, hold 2.0", run_robot(w, cfg, 10000), 1.0);
}
RobotParams weak = rp;
weak.gain_r = 0.95; // the right motor is 5 % weaker for the same duty
for (float k : {0.0f, 2.0f, 6.0f, 20.0f}) {
DriveConfig c = cfg; c.k_heading = k;
SimHW w(weak, sp, arena, 1);
char label[64];
std::snprintf(label, sizeof label, "weak right motor, hold %.1f", k);
show(label, run_robot(w, c, 10000), 1.0);
}
return 0;
}
from (0.30, 1.00) heading +x toward the wall at x = 3.0 m, stop line 0.25 m, 10 s, seed 1:
ideal motors, hold 2.0 x 2.690 y 1.000 drift +0.0 mm heading +0.00 deg odometry +0.00 deg true range 0.250 m settled 8.5 s fault none
weak right motor, hold 0.0 x 2.298 y 0.212 drift -788.5 mm heading -43.08 deg odometry -43.12 deg true range 0.250 m settled 7.8 s fault none
weak right motor, hold 2.0 x 2.691 y 0.681 drift -318.8 mm heading -5.56 deg odometry -5.50 deg true range 0.250 m settled 8.4 s fault none
weak right motor, hold 6.0 x 2.690 y 0.878 drift -122.0 mm heading -0.69 deg odometry -0.66 deg true range 0.250 m settled 8.4 s fault none
weak right motor, hold 20.0 x 2.690 y 0.964 drift -36.5 mm heading -0.06 deg odometry +0.00 deg true range 0.250 m settled 8.5 s fault none
Three things in the output are not obvious from the code.
The robot can stop in the right place at the wrong wall. With a weak motor and no heading hold the robot veered to -43°, drifted 788.5 mm sideways and stopped exactly 0.250 m from a wall, true range 0.250, no fault. It was 0.25 m from the bottom wall, because the range sensor only measures along the heading and cannot tell which wall it faces. Both the range controller and the sensor were working perfectly. The thing that failed is that nothing was holding the heading.
The odometry knew. Its heading, -43.12°, matches the truth, -43.08°: the encoders saw the drift that the range sensor could not. That is the reason to have encoders.
A proportional hold reduces the drift but cannot remove it. A correction proportional to the heading error needs an error to exist before it produces any correction, so a steady disturbance (a weak motor) leaves a steady error. The drift fell from 788.5 mm (no hold) to 318.8, 122.0 and 36.5 mm at gains of 2, 6 and 20, roughly in inverse proportion to the gain (drift times gain is 638, 732 and 730). A bigger gain helps, with a limit set by the loop’s period and the motor’s lag that none of these runs reached: nothing misbehaved even at 20, which is a fact about this model, not a promise. The cure for a steady error, an integral term, comes with PID in a later chapter.
6. Noise: 200 seeded runs per setting
A single run says little about a noisy system. Each row below is 200 runs with seeds 1 to 200, with the error measured as the true distance to the wall at the end minus the 250 mm stop line (positive means stopped short, negative means went past). Runs that ended in a no-range fault are counted but not averaged, because a robot standing still far from the wall has not “stopped at the line”.
200 runs each (seeds 1..200), ideal motors, heading hold on; error = true distance to the wall at the end minus the 250 mm stop line
setting runs fault bump mean mm sd mm min mm max mm
noise and dropouts, echo polled every 100 us:
sigma 0 mm, dropouts 0 % 200 0 0 +5.8 0.0 +5.8 +5.8
sigma 0 mm, dropouts 5 % 200 0 0 +5.8 0.1 +5.6 +6.0
sigma 0 mm, dropouts 30 % 200 44 0 +5.7 0.2 +5.1 +6.0
sigma 5 mm, dropouts 0 % 200 0 0 -1.4 0.5 -2.7 +0.7
sigma 5 mm, dropouts 5 % 200 0 0 -1.4 0.6 -3.1 +0.4
sigma 5 mm, dropouts 30 % 200 44 0 -1.5 0.7 -3.6 +0.7
sigma 20 mm, dropouts 0 % 200 0 0 -17.5 1.6 -22.2 -13.7
sigma 20 mm, dropouts 5 % 200 0 0 -17.4 1.8 -22.8 -13.0
sigma 20 mm, dropouts 30 % 200 44 0 -17.6 1.9 -22.9 -12.3
echo poll interval, sigma 5 mm, dropouts 2 %:
polled every 1 us (step 0.2 mm) 200 0 0 -5.6 0.5 -6.8 -4.1
polled every 10 us (step 1.7 mm) 200 0 0 -4.9 0.5 -6.2 -3.3
polled every 100 us (step 17.2 mm) 200 0 0 -1.4 0.5 -2.8 +0.4
polled every 1000 us (step 171.5 mm) 200 0 0 +75.9 2.0 +70.5 +80.0
Read the table in three parts.
Dropouts do not move the answer, they stop the job. At 30 % no-echo readings 44 of 200 runs (22 %) hit the fault: five consecutive readings with nothing is likely over 500 samples when each has a 30 % chance. The fault works, since the robot stands still and nothing hits the wall (no bumps in any row), but a standing robot is also a failed task. The count is the same in the three rows of 30 % because the seed fixes the dropout pattern whatever the noise level; that is exactly what a seed is for, and it makes the rows comparable.
Noise pushes the robot past the line, systematically. The mean error goes from +5.8 mm with no noise to -1.4 mm at 5 mm of noise and -17.5 mm at 20 mm. The reason is the controller’s one-way speed: once a noisy reading is large the robot moves forward, and it can never move back, so it ratchets toward the most extreme reading. That is a hypothesis until it is tested, so it was: the same experiment with the lower speed clamp changed from 0 to the negative of the top speed (the robot may reverse) gave +7.3, +8.1 and +8.3 mm at the same three noise levels, and +0.0 mm at the finest polling. The bias disappeared when reversing was allowed. It was the controller, not the sensor.
The polling interval sets a floor under the accuracy. With echo polling every 1000 microseconds, one step is 171.5 mm: the sensor reports 0.1715 m or 0.343 m, never between, and the robot stops 75.9 mm short, each time, with a spread of only 2 mm. This is the polling error of Programming for Robotics with Arduino C++ 2 seen from the robot’s side. The +5.8 mm of the no-noise row is the same effect at 17 mm steps: a reading is rounded down, which means measured distances are always a little short, so the robot thinks it is nearer than it is and stops early.
The first and third of these effects were predicted by the arithmetic of chapter 2; the second was not, and it is the sort of finding a simulator is for.
setting runs fault bump mean mm sd mm min mm max mm
noise and dropouts, echo polled every 100 us:
sigma 0 mm, dropouts 0 % 200 0 0 +7.3 0.0 +7.3 +7.3
sigma 5 mm, dropouts 0 % 200 0 0 +8.1 0.9 +5.2 +11.5
sigma 20 mm, dropouts 0 % 200 0 0 +8.3 2.5 +0.6 +17.3
echo poll interval, sigma 5 mm, dropouts 2 %:
polled every 1 us (step 0.2 mm) 200 0 0 +0.0 0.6 -1.3 +1.9
polled every 10 us (step 1.7 mm) 200 0 0 +0.8 0.6 -0.6 +2.7
polled every 100 us (step 17.2 mm) 200 0 0 +8.2 1.0 +5.3 +11.6
polled every 1000 us (step 171.5 mm) 200 0 0 +92.5 3.0 +83.7 +99.9
(That table is the same program as the previous one, rebuilt with the lower speed clamp of drive.h changed from 0 to the negative of the top speed; only the rows that are comparable are shown.)
7. Replay: running a recorded run again
Some bugs only show up in a particular run. A recording keeps what the controller saw at every control tick (the range, the encoder counts, the bumper) and what it did (the two wheel commands and its odometry). The values are stored as hexadecimal floats, so nothing is rounded: reading the file back gives the same numbers bit for bit. Replay then feeds the recorded inputs to the controller again.
// replay.h -- record the sensor inputs and the outputs of a run to a text file, and feed the inputs back through the controller later (HOST ONLY).
// A line per 20 ms control tick: range ticks_left ticks_right bumped | v_left v_right odometry_x odometry_y (floats in hex, so nothing is rounded)
#pragma once
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include "drive.h"
struct Tick {
float range; int32_t tl, tr; int bump; // inputs the controller saw
float vl, vr, ox, oy; // outputs it produced
};
// Wraps any HW: forwards every call and notes what the controller saw and did.
template <class HW>
class RecordingHW {
public:
explicit RecordingHW(HW& hw) : hw_(hw) { cur_.range = 0; cur_.tl = cur_.tr = 0; cur_.bump = 0; cur_.vl = cur_.vr = cur_.ox = cur_.oy = 0; }
float range_m() { cur_.range = hw_.range_m(); return cur_.range; }
bool bumped() { cur_.bump = hw_.bumped(); return cur_.bump != 0; }
void read_ticks(int32_t& l, int32_t& r) { hw_.read_ticks(l, r); cur_.tl = l; cur_.tr = r; } // the last input read in sense()
void drive(float vl, float vr) { cur_.vl = vl; cur_.vr = vr; hw_.drive(vl, vr); }
Tick cur_; // the caller copies this after each tick, once the odometry is known
private:
HW& hw_;
};
// Plays recorded inputs back, one tick at a time. drive() just notes the command.
class ReplayHW {
public:
explicit ReplayHW(const std::vector<Tick>& ticks) : vl_(0), vr_(0), t_(ticks), i_(0) {}
void set_index(size_t i) { i_ = i; }
float range_m() { return t_[i_].range; }
bool bumped() { return t_[i_].bump != 0; }
void read_ticks(int32_t& l, int32_t& r) { l = t_[i_].tl; r = t_[i_].tr; }
void drive(float vl, float vr) { vl_ = vl; vr_ = vr; }
float vl_, vr_;
private:
const std::vector<Tick>& t_;
size_t i_;
};
inline bool save_ticks(const char* path, const std::vector<Tick>& v) {
FILE* f = std::fopen(path, "w");
if (!f) return false;
for (const Tick& t : v)
std::fprintf(f, "%a %d %d %d | %a %a %a %a\n", (double)t.range, (int)t.tl, (int)t.tr, t.bump, (double)t.vl, (double)t.vr, (double)t.ox, (double)t.oy);
std::fclose(f);
return true;
}
inline bool load_ticks(const char* path, std::vector<Tick>& v) {
FILE* f = std::fopen(path, "r");
if (!f) return false;
double r, vl, vr, ox, oy; int tl, tr, bump;
while (std::fscanf(f, "%la %d %d %d | %la %la %la %la", &r, &tl, &tr, &bump, &vl, &vr, &ox, &oy) == 8) {
Tick t; t.range = (float)r; t.tl = tl; t.tr = tr; t.bump = bump; t.vl = (float)vl; t.vr = (float)vr; t.ox = (float)ox; t.oy = (float)oy;
v.push_back(t);
}
std::fclose(f);
return true;
}
inline uint32_t fnv1a(const void* data, size_t n, uint32_t h = 2166136261u) { // a 32-bit fingerprint of a block of bytes
const unsigned char* p = (const unsigned char*)data;
for (size_t i = 0; i < n; ++i) { h ^= p[i]; h *= 16777619u; }
return h;
}
Two runs were recorded, with the right motor weak: one with the heading hold at 2.0, the other with it off. Then they were replayed with the same code, with a changed range gain, and with a different build of the same controller, the cheap trigonometry:
--- record two runs (a weak right motor; heading gain 2.0 and 0.0)
recorded 500 ticks to run_hold.txt; fingerprint of the commands ce1530d6; true range at the end 0.251 m, drift -318.8 mm
recorded 500 ticks to run_free.txt; fingerprint of the commands 05fe9965; true range at the end 0.250 m, drift -788.2 mm
--- replay the same code on the same inputs
replayed 500 ticks of run_hold.txt (heading gain 2.0, k_range 1.50): fingerprint ce1530d6; 0 commands differ from the recording; odometry position differs by at most 0.0 mm
replayed 500 ticks of run_free.txt (heading gain 0.0, k_range 1.50): fingerprint 05fe9965; 0 commands differ from the recording; odometry position differs by at most 0.0 mm
--- replay with a changed gain (k_range 1.5 -> 1.2)
replayed 500 ticks of run_hold.txt (heading gain 2.0, k_range 1.20): fingerprint 865c632a; 178 commands differ from the recording (first at tick 216 = 4.32 s, largest difference 0.1048 m/s); odometry position differs by at most 0.0 mm
--- replay with the cheap sin/cos (a different build of the same controller)
replayed 500 ticks of run_hold.txt (heading gain 2.0, k_range 1.50): fingerprint ce1530d6; 0 commands differ from the recording; odometry position differs by at most 0.0 mm
replayed 500 ticks of run_free.txt (heading gain 0.0, k_range 1.50): fingerprint 05fe9965; 0 commands differ from the recording; odometry position differs by at most 5.8 mm
--- the same changed gain run for real, in the closed loop (the world answers back)
closed loop, 500 ticks to -; fingerprint of the commands ce1530d6; true range at the end 0.251 m, drift -318.8 mm
closed loop, 500 ticks to -; fingerprint of the commands 04fbafcb; true range at the end 0.253 m, drift -313.9 mm
Four results, each one a use of replay or a limit on it.
Same code, same inputs, identical outputs. The fingerprint of the 500 recorded commands (a 32-bit hash of their bytes) is ce1530d6 when recorded and ce1530d6 on replay, with 0 commands differing. This is the basis of a regression test: if a refactoring changes the fingerprint, it changed behaviour.
A different build can change the answer in a way the commands hide. With the cheap sin and cos, replaying the free-running run gave 0 different commands, because the commands depend on the heading, which is not calculated with trigonometry, yet the odometry position differs by up to 5.8 mm. A test that compares only the commands would have passed a change that made the position estimate worse.
A changed gain is visible at once. With the range gain at 1.2 instead of 1.5, 178 of 500 commands differed, from tick 216 (4.32 s, about when the robot starts to slow for the wall and the gain starts to matter), by up to 0.1048 m/s.
But replay cannot say what the changed controller would have done. The recorded world did not answer the changed commands: the robot in the recording did not slow down earlier, so the next recorded range is the one the old controller produced. Running the changed gain for real, in the closed loop, gave a different fingerprint (04fbafcb) from the replay of the same change (865c632a), and a different ending (0.253 m from the wall, drift -313.9 mm, against 0.251 m and -318.8 mm for the original). Replay tests the controller’s decisions on fixed inputs; it does not test the loop, which needs the simulator.
8. One robot, two targets
The point of the seam is that the file that ran in the simulator is the file that goes on the board. That was checked as a fact, not assumed: the copy of drive.h in the sketch folder and the one used by the simulator have the same MD5 hash, as have timing.h and scheduler.h:
The sketch is a thin shell: PinHW implements the four functions on pins (the range from chapter 2’s echo state machine, the bumper from a pin, drive as direction lines and PWM), and setup() and loop() hand control to the scheduler. The encoders are not wired in this chapter, so read_ticks returns zero and says so.
// robot_ch3.ino -- Programming for Robotics with Arduino C++, chapter 3: the SAME drive.h that ran in the simulator, behind the real pins.
// Compile-checked for the Arduino Uno R3 (arduino:avr:uno). NOT run on a board: no board was attached.
// The wheel encoders are not wired yet (they need interrupts: chapter 4), so read_ticks() reports zero and the robot's odometry stands still.
#include "scheduler.h"
#include "conv.h"
#include "echo.h"
#include "pins.h"
#include "drive.h"
const float V_MAX_MPS = 0.5f; // wheel speed at a duty of 255: an assumption, as in chapter 2
class PinHW { // the four functions drive.h needs, on real pins
public:
PinHW() : range_m_(-1.0f) {}
float range_m() { return range_m_; } // negative until the first echo, and after a timeout
void set_range(float m) { range_m_ = m; }
void read_ticks(int32_t& l, int32_t& r) { l = 0; r = 0; }
bool bumped() { return digitalRead(PIN_BUMP) == LOW; }
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(vl >= 0.0f ? vl : -vl, V_MAX_MPS));
analogWrite(PIN_MR_PWM, speed_to_pwm(vr >= 0.0f ? vr : -vr, V_MAX_MPS));
}
private:
float range_m_;
};
static PinHW hw;
static DriveConfig make_config() {
DriveConfig c;
c.stop_m = 0.25f; c.k_range = 1.5f; c.vmax = V_MAX_MPS; c.k_heading = 2.0f;
c.wheel_r = 0.033f; c.track = 0.15f; c.ticks_per_rev = 360; c.max_dropouts = 5;
return c;
}
static DriveRobot<PinHW> robot(hw, make_config());
static Echo echo;
static Scheduler<5> sch;
static bool trig_level = false;
static void echo_start_task(void*, uint32_t) { echo.start(); }
static void report_task(void*, uint32_t now) {
Serial.print(now); Serial.print(F(" ms range ")); Serial.print(robot.range(), 3);
Serial.print(F(" m cmd ")); Serial.print(robot.command_left(), 3);
Serial.print(F(" m/s fault ")); Serial.println((int)robot.fault());
}
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);
sch.add(DriveRobot<PinHW>::sense_task, &robot, 20);
sch.add(DriveRobot<PinHW>::think_task, &robot, 20);
sch.add(DriveRobot<PinHW>::act_task, &robot, 20);
sch.add(echo_start_task, 0, 60);
sch.add(report_task, 0, 500);
}
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) hw.set_range(echo_us_to_m(echo.width_us()));
else if (st == Echo::TIMEOUT) hw.set_range(-1.0f);
sch.run(millis());
}
Compiled for the Uno, without warnings from the project’s own files:
Build
Flash (of 32,256)
RAM by globals (of 2,048)
robot_ch3.ino, sinf and cosf
7726 bytes (23 %)
413 bytes (20 %)
robot_ch3.ino, -DDRIVE_FAST_TRIG
7454 bytes (23 %), 272 less
413 bytes (20 %)
The two figures are not comparable to chapter 2’s sketch (9606 bytes, 936 bytes of RAM), because this sketch has no Wire, IMU or log. The cheap trigonometry saves 272 bytes of flash, and the next experiment is the price, the error of its two series against the library functions:
// e_trig.cpp -- the cheap sin/cos of the odometry (first terms of the series) against sinf/cosf, by heading (host build)
#include <cstdio>
#include <math.h>
#include <initializer_list>
int main() {
std::printf(" heading rad deg sin approx sin exact error cos approx cos exact error\n");
for (float a : {0.05f, 0.1f, 0.3f, 0.5f, 0.75f, 1.0f, 1.5f, 2.0f, 3.1416f}) {
float m2 = a * a, c = 1.0f - 0.5f * m2, s = a * (1.0f - m2 / 6.0f);
std::printf(" %11.4f %5.1f %+9.5f %+9.5f %+8.5f %+9.5f %+9.5f %+8.5f\n", a, a * 57.29578f, s, sinf(a), s - sinf(a), c, cosf(a), c - cosf(a));
}
return 0;
}
At the headings of the weak-motor runs it is harmless: the cosine is wrong by 0.00034 at 17°, 0.0129 at 43°. By 86° the cosine has the wrong sign (-0.125 against +0.071), and at 180° it returns -3.93 for a function that cannot leave -1 to +1. A robot that turns round, which any robot with a planner will, would have its position estimate wrecked, silently. The default of this course is therefore the library; the cheap one is for a robot that can prove its heading stays small, and 272 bytes is 0.8 % of the flash. That is the budget lesson: a saving is only a saving where its error is acceptable, and the way to find out is to measure the error, not the flash.
9. Is the simulation reproducible?
If a seed is to be a bug report, the same seed must give the same run every time. Four things could break that: the compiler’s optimisation, floating-point shortcuts, the number type used for the world, and the random generator. The experiment builds the same program at four optimisation levels, with the unsafe-looking -ffast-math, and with a float world, and compares the output byte for byte:
#!/bin/bash
# is the simulation reproducible? build e_drive at several optimisation levels and with a float world, and compare the output byte for byte
GPP="C:/Users/emuba/AppData/Local/Microsoft/WinGet/Packages/BrechtSanders.WinLibs.POSIX.UCRT_Microsoft.Winget.Source_8wekyb3d8bbwe/mingw64/bin/g++.exe"
export PATH="$(cygpath -u "$(dirname "$GPP")"):$PATH"
cd "$(dirname "$0")"
echo "build fingerprint of the output (md5, first 8 hex)"
for opt in -O0 -O1 -O2 -O3; do
g++ -std=c++11 $opt e_drive.cpp -o det.exe && printf "%-38s %s\n" "double world, $opt" "$(./det.exe | md5sum | cut -c1-8)"
done
g++ -std=c++11 -O2 -ffast-math e_drive.cpp -o det.exe && printf "%-38s %s\n" "double world, -O2 -ffast-math" "$(./det.exe | md5sum | cut -c1-8)"
g++ -std=c++11 -O2 -DSIMREAL=float e_drive.cpp -o detf.exe && printf "%-38s %s\n" "FLOAT world, -O2" "$(./detf.exe | md5sum | cut -c1-8)"
echo "--- the two outputs, line by line, where they differ (double world first, float world second)"
g++ -std=c++11 -O2 e_drive.cpp -o det.exe && diff <(./det.exe) <(./detf.exe) | cut -c1-200
build fingerprint of the output (md5, first 8 hex)
double world, -O0 0cfd4dfe
double world, -O1 0cfd4dfe
double world, -O2 0cfd4dfe
double world, -O3 0cfd4dfe
double world, -O2 -ffast-math 0cfd4dfe
FLOAT world, -O2 357e0779
--- the two outputs, line by line, where they differ (double world first, float world second)
3,6c3,6
< weak right motor, hold 0.0 x 2.298 y 0.212 drift -788.5 mm heading -43.08 deg odometry -43.12 deg true range 0.250 m settled 7.8 s fault none
< weak right motor, hold 2.0 x 2.691 y 0.681 drift -318.8 mm heading -5.56 deg odometry -5.50 deg true range 0.250 m settled 8.4 s fault none
< weak right motor, hold 6.0 x 2.690 y 0.878 drift -122.0 mm heading -0.69 deg odometry -0.66 deg true range 0.250 m settled 8.4 s fault none
< weak right motor, hold 20.0 x 2.690 y 0.964 drift -36.5 mm heading -0.06 deg odometry +0.00 deg true range 0.250 m settled 8.5 s fault none
---
> weak right motor, hold 0.0 x 2.298 y 0.212 drift -788.5 mm heading -43.08 deg odometry -42.90 deg true range 0.250 m settled 7.8 s fault none
> weak right motor, hold 2.0 x 2.691 y 0.681 drift -319.1 mm heading -5.59 deg odometry -5.50 deg true range 0.250 m settled 8.4 s fault none
> weak right motor, hold 6.0 x 2.690 y 0.878 drift -122.3 mm heading -0.74 deg odometry -0.66 deg true range 0.250 m settled 8.4 s fault none
> weak right motor, hold 20.0 x 2.690 y 0.963 drift -36.9 mm heading -0.09 deg odometry +0.00 deg true range 0.250 m settled 8.5 s fault none
On this machine and this compiler the output is bit-identical from -O0 to -O3 and even with -ffast-math (fingerprint 0cfd4dfe each time). That is a fact about this machine, not a guarantee: a processor with fused multiply-add instructions, or a different compiler, is allowed to give different last digits, and I did not test one. The float world is different. Its drift differs by 0.3 mm and its heading by 0.03° to 0.05°, and the odometry heading in the free-running case is -42.90° against -43.12°, a difference of 0.22°. The float simulator accumulates each wheel’s travel in 32 bits, 1 mm at a time, and loses the small increments, so its encoders count slightly wrong. A simulator is not neutral about its number type. The simulator’s world is therefore kept in double, as the truth, while the robot code stays float, because that is what the board runs.
10. What the chapter’s numbers can and cannot be trusted for
What can: the code (that the controller stops, that the fault triggers, that the replay is exact), the comparisons (more noise means more bias; more polling resolution means less; reversing removes the ratchet), and the reasoning they support. What cannot: any absolute figure for a real robot. The 5 mm of noise, the 2 % dropouts, the 0.1 s motor lag, the 5 % weak motor and the 0.5 m/s at a duty of 255 are assumptions from this chapter, and the simulator does not have stiction, slip, a sagging battery or timing jitter. The first test on the floor will disagree with the simulator, and the disagreement is the interesting part: each difference is a missing line in the table of section 3.
Challenges
Challenge 1: Filter at the seam
The ratchet bias of section 6 (-17.4 mm at 20 mm of noise) is a property of the one-way controller. Without letting the robot reverse and without editing drive.h, remove it by wrapping the hardware in a class with the same four functions that averages the last N valid ranges. Report the mean error, the spread and the worst case for N of 1, 3, 5 and 9 over 200 seeds at 20 mm of noise and 5 % dropouts.
With the weak right motor and no heading hold the robot turns to -43°. Run it with encoders of 20, 90, 360 and 1440 ticks per wheel turn (the simulator and the controller must agree) and report the heading and position error of the odometry against the simulator’s truth. Say what the millimetres per tick tell you.
On the roughest setting of section 6 (20 mm of noise, 30 % dropouts) run 1000 seeds. Count the faults, find the seed whose run ended closest to the wall without a fault, and show that running that seed again reproduces the run exactly (a fingerprint of the final position), while the next seed does not. Do the same for the first faulting seed.
The seam. Four functions: range_m() (negative = no echo), read_ticks(), drive(vl, vr), bumped(). Five implementations here: pins, simulator, recorder, replayer, averaging wrapper. drive.h is byte-identical in the simulator and the sketch (MD5 51f2295b…).
Simulator tests. 19 checks against hand-worked answers, all pass (straight run x = 0.68020 against 0.68000; arc (0.52500, 1.22497); 1 m = 1736 ticks). Dropout fraction checked across 12 seeds: 9.95 %.
The wrong wall. Weak right motor, no heading hold: -43°, 788.5 mm of drift, and stopped exactly 0.250 m from the bottom wall. Odometry heading -43.12° against truth -43.08°.
P-only heading hold. Drift 788.5, 318.8, 122.0, 36.5 mm at gains 0, 2, 6, 20: roughly 1/gain; a steady disturbance leaves a steady error.
Noise. Mean stop error +5.8 mm (no noise), -1.4 (5 mm), -17.5 (20 mm); with reversing allowed +7.3, +8.1, +8.3: the bias was the one-way controller. Polling every 1000 us stops 75.9 mm short.
Dropouts. 30 % no-echo: 44 of 200 runs hit the fault (243 of 1000 in challenge 3); the robot stands still, never hits the wall.
Replay. Same code: fingerprint ce1530d6 both times, 0 differing commands. Gain 1.5 to 1.2: 178 of 500 commands differ from 4.32 s. Replay cannot give the closed-loop outcome (fingerprints 865c632a against 04fbafcb).
Budget.robot_ch3.ino: 7726 bytes flash (23 %), 413 bytes RAM (20 %). Cheap trig: 7454 (-272), but the cosine is wrong by 0.0129 at 43° and has the wrong sign by 86°.
Reproducibility. Identical output from -O0 to -O3 and -ffast-math on this machine (fingerprint 0cfd4dfe); a float world differs (odometry heading -42.90° against -43.12°). Own random generator, so a seed names one run everywhere.
Challenges. Averaging at the seam: bias -17.4, -5.9, -2.5, -0.1 mm for N = 1, 3, 5, 9; odometry position error 7.1, 0.8, 0.3, 0.1 mm for 20, 90, 360, 1440 ticks per turn; seed 302 is the worst fault-free run (-24.1 mm) and reproduces exactly.
Not run: anything on a board; every simulator parameter is an assumption.
Next: Programming for Robotics with Arduino C++ 4, Sensor Code and Filtering
Programming for Robotics with Arduino C++ 4 (planned; not yet written) takes the filter that challenge 1 bolted on at the seam and builds the real ones: median, moving-average and exponential filters in integer and float versions, in fixed-size buffers with no lists, and the encoder decoding with interrupts that this chapter’s sketch left as a stub, with the interrupt-safe reads that volatile data needs.