State Machines

Programming for Robotics with Arduino C++

Course 2 · Chapter 7 · State Machines and Behaviours

Programming for Robotics with Arduino C++ 6 gave the robot controllers: given a goal (a speed, a heading, a distance) they drive the error to zero. This chapter gives it decisions. Something is in the way, so back up and turn; the wall has ended, so search for it; the line has gone, so look for it for a while and then give up. Decisions like these are a state machine: a small set of states, the events that move the robot from one state to another, and what the robot does in each state.

The chapter builds one machine three ways (a switch, a table in RAM, a table in flash), compares what they cost on the Uno, writes the tests a machine needs before it goes near a robot (does the table behave like the switch? is there a state it cannot leave?), and then builds a wall follower and a line follower on the same pattern. As in the whole course, every number is from running the code, and where the numbers embarrass the design the chapter says so: the wall follower’s side error turns out to be an oscillation of the controller itself, and one setting of the avoider’s dropout rule was counting in the wrong unit.

What was run, and what was not
Run on a PC (g++ 16.2, C++11, -Wall -Wextra -pedantic): every experiment with an output under it and the three challenge solutions, on the simulator of Programming for Robotics with Arduino C++ 3, extended for this chapter with a second range sensor looking to the right, a circular line on the floor and a five-sensor line array. The arena, the line, the sensor noise, the dropouts and the sensor array’s gains and offsets are assumptions I chose, not measurements. Compiled for the Uno, not run (arduino-cli, core arduino:avr 1.8.8, --warnings all): the size-test sketch in its four variants and robot_ch7.ino. The flash and RAM figures are the compiler’s for the real chip. Time per pass was not measured, and nothing was attached to a board: no sensor, motor or bumper. The warnings printed by the Arduino core’s own new.cpp (unused parameter tag) are the core’s, not the sketch’s.

1. A machine with enum class and switch

The obstacle avoider has three states. CRUISE: drive forward; if the bumper is pressed or something is closer than 0.25 m, go to BACKUP. BACKUP: reverse for 400 ms, then pick a random direction and a random turn time between 400 and 1200 ms and go to TURN. TURN: spin until the time is up, then go back to CRUISE. In Python you would write the state as an Enum member or a string and branch with if/match; in C++ the state is an enum class (a distinct type, so a state cannot be mixed up with an event or a number) stored in one byte, and the branch is a switch, whose cases the compiler can check: with -Wall it warns about a state you forgot to handle.

In PythonOn the Uno in C++
class State(Enum): CRUISE = 1 ...enum class AvoidState : uint8_t { CRUISE, BACKUP, TURN }; one byte, a type of its own
match state: or an if chainswitch (st_); a missing case is a compiler warning
a dict of state to function, built when the program starts, on the heapan array of function pointers, a const table fixed at compile time, which can live in flash instead of RAM (section 3)
time.time() for “how long have I been here”the time is passed in (now_ms) and the state remembers when it was entered (t0_); the machine never reads a clock, so a PC can test it
an exception when something goes wrongan explicit FAULT state and a time-out that leads to it (section 5)

Two design choices run through every behaviour in this chapter. First, a behaviour is a pure function of what the sensors said and the time: update(Sense, now) returns wheel speeds (Cmd), and it never touches a pin, so it can be driven by the simulator, by a test, or by the real sensors with no change. Second, the tick on which the state changes returns zero speeds, so a transition never carries out the old state’s action and the new one’s in the same step.

Here is the whole header: the avoider as a switch, the same machine as a table (section 3), the wall follower (section 4) and the line follower (section 6). Its one decision about sensor trouble is NearCheck: what to do when the front sensor returns “no echo”. The naive rule reads no echo as “nothing there”; the safe rule holds the last good reading for drop_limit control ticks and then assumes something is there. The unit matters and it is the control tick (20 ms), not the sensor reading (60 ms): drop_limit 3 holds for one reading.

// fsm.h -- state machines and behaviours (Programming for Robotics with Arduino C++ 7). Plain C++11: no Arduino calls, no heap. // Behaviours are pure: they take what the sensors said (Sense) and the time, and return wheel speeds (Cmd). They never touch a pin, so a PC can test them. #pragma once #include <stdint.h> #include "calib.h" #if defined(__AVR__) && !defined(FSM_NO_PROGMEM) // define FSM_NO_PROGMEM to keep the tables in RAM instead (for the size comparison) #include <avr/pgmspace.h> #define FSM_PROGMEM PROGMEM inline uint8_t fsm_read8(const uint8_t* p) { return pgm_read_byte(p); } #define FSM_READ_PTR(p) pgm_read_ptr(p) #else #define FSM_PROGMEM inline uint8_t fsm_read8(const uint8_t* p) { return *p; } #define FSM_READ_PTR(p) (*(p)) #endif struct Sense { float front_m; float right_m; bool bump; }; // distances in metres; negative means "no echo" struct Cmd { float vl, vr; }; // a tiny random generator, so a behaviour that picks a random turn is reproducible from its seed struct Xor32 { uint32_t s; explicit Xor32(uint32_t seed) : s(seed ? seed : 1u) {} uint32_t next() { s ^= s << 13; s ^= s >> 17; s ^= s << 5; return s; } }; inline Cmd spin(float w, float track) { Cmd c = {-0.5f * w * track, 0.5f * w * track}; return c; } // w > 0 turns left inline Cmd arc(float v, float w, float track) { Cmd c = {v - 0.5f * w * track, v + 0.5f * w * track}; return c; } // ---- "is something close?": what to do with a front reading of -1 (no echo) ---- // naive: no echo means nothing there (far). safe: hold the last good reading for drop_limit CONTROL TICKS (20 ms each, so drop_limit 3 is one 60 ms sensor reading), then assume the worst (near). class NearCheck { public: NearCheck(float stop_m, uint8_t drop_limit, bool safe) : stop_(stop_m), limit_(drop_limit), safe_(safe), last_(4.0f), drops_(0) {} bool near(float front_m, bool bump) { if (front_m < 0.0f) { if (drops_ < 250) ++drops_; if (!safe_) return bump; // naive: only the bumper can say "near" if (drops_ > limit_) return true; // too long without an echo: assume the worst } else { drops_ = 0; last_ = front_m; } return bump || last_ < stop_; } private: float stop_; uint8_t limit_; bool safe_; float last_; uint8_t drops_; }; // ============ 1. a switch-based machine: an obstacle avoider ============ enum class AvoidState : uint8_t { CRUISE, BACKUP, TURN }; struct AvoidConfig { float v, stop_m, back_v, turn_w, track; uint16_t back_ms, turn_min_ms, turn_max_ms; uint8_t drop_limit; bool safe; }; class Avoider { public: Avoider(const AvoidConfig& c, uint32_t seed) : c_(c), near_(c.stop_m, c.drop_limit, c.safe), rng_(seed), st_(AvoidState::CRUISE), t0_(0), dur_(0), dir_(1.0f) {} Cmd update(const Sense& s, uint32_t now_ms) { bool near = near_.near(s.front_m, s.bump); uint32_t el = now_ms - t0_; switch (st_) { case AvoidState::CRUISE: if (near) { st_ = AvoidState::BACKUP; t0_ = now_ms; break; } return arc(c_.v, 0.0f, c_.track); case AvoidState::BACKUP: if (el >= c_.back_ms) { st_ = AvoidState::TURN; t0_ = now_ms; uint32_t r = rng_.next(); dur_ = c_.turn_min_ms + (r >> 8) % (uint32_t)(c_.turn_max_ms - c_.turn_min_ms + 1); dir_ = (r & 1) ? 1.0f : -1.0f; break; } return arc(-c_.back_v, 0.0f, c_.track); case AvoidState::TURN: if (el >= dur_) { st_ = AvoidState::CRUISE; t0_ = now_ms; break; } return spin(dir_ * c_.turn_w, c_.track); } Cmd stop = {0.0f, 0.0f}; // the tick on which the state changed: stand still for one step return stop; } AvoidState state() const { return st_; } private: AvoidConfig c_; NearCheck near_; Xor32 rng_; AvoidState st_; uint32_t t0_, dur_; float dir_; }; // ============ 2. the same machine as a TABLE: rows of (state, event, next state, action) plus a function per state ============ // Events are bits of a mask; for the current state the first row (in table order) whose event bit is set wins. A state with no matching row stays where it is. namespace tbl { enum State : uint8_t { CRUISE, BACKUP, TURN, NSTATES }; enum Event : uint8_t { EV_BUMP, EV_NEAR, EV_TIMER }; enum Action : uint8_t { A_NONE, A_START_BACK, A_START_TURN }; const uint8_t ROWS[][4] FSM_PROGMEM = { // from, event, to, action { CRUISE, EV_BUMP, BACKUP, A_START_BACK }, { CRUISE, EV_NEAR, BACKUP, A_START_BACK }, { BACKUP, EV_TIMER, TURN, A_START_TURN }, { TURN, EV_TIMER, CRUISE, A_NONE }, }; const uint8_t NROWS = sizeof(ROWS) / sizeof(ROWS[0]); // the engine: returns the action of the row that fired (A_NONE if none did, and `fired` tells which) inline uint8_t step(const uint8_t (*rows)[4], uint8_t nrows, uint8_t& state, uint8_t events, bool& fired) { for (uint8_t i = 0; i < nrows; ++i) { if (fsm_read8(&rows[i][0]) == state && ((events >> fsm_read8(&rows[i][1])) & 1)) { state = fsm_read8(&rows[i][2]); fired = true; return fsm_read8(&rows[i][3]); } } fired = false; return A_NONE; } } // namespace tbl struct AvoidCtx; typedef Cmd (*StateFn)(const AvoidCtx&); struct AvoidCtx { AvoidConfig c; float dir; }; inline Cmd do_cruise(const AvoidCtx& x) { return arc(x.c.v, 0.0f, x.c.track); } inline Cmd do_backup(const AvoidCtx& x) { return arc(-x.c.back_v, 0.0f, x.c.track); } inline Cmd do_turn(const AvoidCtx& x) { return spin(x.dir * x.c.turn_w, x.c.track); } const StateFn DO_FN[tbl::NSTATES] FSM_PROGMEM = { do_cruise, do_backup, do_turn }; // a function pointer per state, in flash on the Uno class TableAvoider { public: TableAvoider(const AvoidConfig& c, uint32_t seed, const uint8_t (*rows)[4] = tbl::ROWS, uint8_t nrows = tbl::NROWS) : near_(c.stop_m, c.drop_limit, c.safe), rng_(seed), state_(tbl::CRUISE), t0_(0), dur_(0), rows_(rows), nrows_(nrows) { x_.c = c; x_.dir = 1.0f; } Cmd update(const Sense& s, uint32_t now_ms) { uint8_t ev = 0; bool near = near_.near(s.front_m, s.bump); if (s.bump) ev |= 1 << tbl::EV_BUMP; if (near) ev |= 1 << tbl::EV_NEAR; uint32_t el = now_ms - t0_; uint32_t limit = state_ == tbl::BACKUP ? x_.c.back_ms : dur_; if (state_ != tbl::CRUISE && el >= limit) ev |= 1 << tbl::EV_TIMER; bool fired; uint8_t act = tbl::step(rows_, nrows_, state_, ev, fired); if (fired) { t0_ = now_ms; if (act == tbl::A_START_TURN) { uint32_t r = rng_.next(); dur_ = x_.c.turn_min_ms + (r >> 8) % (uint32_t)(x_.c.turn_max_ms - x_.c.turn_min_ms + 1); x_.dir = (r & 1) ? 1.0f : -1.0f; } Cmd stop = {0.0f, 0.0f}; return stop; } StateFn f = (StateFn)FSM_READ_PTR(&DO_FN[state_]); return f(x_); } uint8_t state() const { return state_; } private: NearCheck near_; Xor32 rng_; uint8_t state_; uint32_t t0_, dur_; const uint8_t (*rows_)[4]; uint8_t nrows_; AvoidCtx x_; }; // ============ 3. a wall follower (the wall on the RIGHT) ============ enum class WallState : uint8_t { FOLLOW, CORNER, SEARCH, FAULT }; struct WallConfig { float v, target_m, kp, corner_front_m, corner_clear_m, corner_w, search_v, search_w, track; uint16_t side_hold_ms, corner_timeout_ms, search_timeout_ms; bool full; // false: the naive version (steer on the side distance only; no corner, no lost-wall states) }; class WallFollower { public: explicit WallFollower(const WallConfig& c) : c_(c), st_(WallState::FOLLOW), t0_(0), side_(c.target_m), side_t_(0) {} Cmd update(const Sense& s, uint32_t now) { if (s.right_m >= 0.0f) { side_ = s.right_m; side_t_ = now; } bool side_ok = (now - side_t_) <= c_.side_hold_ms; // a reading no older than side_hold_ms, so single dropouts are bridged bool front_near = s.bump || (s.front_m >= 0.0f && s.front_m < c_.corner_front_m); if (!c_.full) return arc(c_.v, side_ok ? -c_.kp * (side_ - c_.target_m) : 0.0f, c_.track); uint32_t el = now - t0_; switch (st_) { case WallState::FOLLOW: if (front_near) { st_ = WallState::CORNER; t0_ = now; break; } if (!side_ok) { st_ = WallState::SEARCH; t0_ = now; break; } return arc(c_.v, -c_.kp * (side_ - c_.target_m), c_.track); case WallState::CORNER: if (s.front_m > c_.corner_clear_m) { st_ = WallState::FOLLOW; t0_ = now; break; } if (el > c_.corner_timeout_ms) { st_ = WallState::FAULT; break; } return spin(c_.corner_w, c_.track); case WallState::SEARCH: if (front_near) { st_ = WallState::CORNER; t0_ = now; break; } if (side_ok) { st_ = WallState::FOLLOW; t0_ = now; break; } if (el > c_.search_timeout_ms) { st_ = WallState::FAULT; break; } return arc(c_.search_v, -c_.search_w, c_.track); case WallState::FAULT: break; } Cmd stop = {0.0f, 0.0f}; return stop; } WallState state() const { return st_; } private: WallConfig c_; WallState st_; uint32_t t0_; float side_; uint32_t side_t_; }; // ============ 4. a line follower ============ enum class LineState : uint8_t { FOLLOW, SEARCH, FAULT }; struct LineConfig { float v, k_w, slow, search_w, track; uint16_t search_timeout_ms; }; // k_w: rad/s per mm off the line; slow: fraction of v lost at 40 mm off class LineFollower { public: explicit LineFollower(const LineConfig& c) : c_(c), st_(LineState::FOLLOW), t0_(0), last_side_(1.0f), lost_events_(0) { for (uint8_t i = 0; i < 5; ++i) scaled_[i] = 0; } LineCal<5>& cal() { return cal_; } Cmd update(const int16_t* raw, uint32_t now) { static const int16_t POS[5] = {40, 20, 0, -20, -40}; // mm, left positive for (uint8_t i = 0; i < 5; ++i) scaled_[i] = cal_.scaled(i, raw[i]); float pos = 0.0f; bool seen = line_position<5>(scaled_, POS, pos); Cmd stop = {0.0f, 0.0f}; switch (st_) { case LineState::FOLLOW: if (!seen) { st_ = LineState::SEARCH; t0_ = now; ++lost_events_; break; } last_side_ = pos >= 0 ? 1.0f : -1.0f; { float a = pos < 0 ? -pos : pos; float v = c_.v * (1.0f - c_.slow * (a > 40.0f ? 1.0f : a / 40.0f)); return arc(v, c_.k_w * pos, c_.track); } case LineState::SEARCH: if (seen) { st_ = LineState::FOLLOW; break; } if (now - t0_ > c_.search_timeout_ms) { st_ = LineState::FAULT; break; } return spin(last_side_ * c_.search_w, c_.track); case LineState::FAULT: break; } return stop; } LineState state() const { return st_; } uint32_t lost_events() const { return lost_events_; } private: LineConfig c_; LineState st_; uint32_t t0_; float last_side_; uint32_t lost_events_; LineCal<5> cal_; int16_t scaled_[5]; };

2. Trying it: how an obstacle avoider behaves

The experiment runs the avoider for 60 s in the 3 × 2 m arena, 200 seeded runs per row, and scores the bumper presses (collisions), the share of the arena’s 600 cells of 10 cm that the robot visited, and the seconds spent outside the walls (a robot that has pushed through is a failed robot). The sensor is read every 60 ms; the control tick is 20 ms.

// e_avoid.cpp -- a wandering obstacle avoider in the 3 x 2 m arena, 60 s, 200 seeded runs per row (host build; sensor noise and dropouts are the simulator's, assumed). // Machine: CRUISE -> (something near or bumper) -> BACKUP for 400 ms -> TURN for 400..1200 ms in a random direction -> CRUISE. The front sensor is read every 60 ms. // "naive": a reading of -1 (no echo) means nothing is there. "safe": hold the last good reading for 3 control ticks (20 ms each: one 60 ms sensor reading), then assume something IS there. // Scored: collisions (the bumper going from released to pressed), and the share of the arena's 600 cells of 10 cm that the robot visited. #include <cstdio> #include <cmath> #include <set> #include <initializer_list> #include "sim.h" #include "fsm.h" struct R { double bumps, coverage, stuck; }; static R run(bool safe, double dropout, int seeds, int limit = 3) { R r = {0, 0, 0}; for (int seed = 1; seed <= seeds; ++seed) { RobotParams rp; rp.tau = 0.1; SensorParams sp; sp.dropout = dropout; SimHW w(rp, sp, Arena(), seed); w.th = (seed % 8) * 0.785; AvoidConfig c = {0.3f, 0.25f, 0.2f, 2.0f, 0.15f, 400, 400, 1200, (uint8_t)limit, safe}; Avoider av(c, (uint32_t)seed); Sense s = {-1.0f, -1.0f, false}; bool was_bumped = false; std::set<int> cells; double bumps = 0, outside = 0; for (int tick = 0; tick < 3000; ++tick) { uint32_t now = tick * 20; if (tick % 3 == 0) { s.front_m = w.range_m(); } s.bump = w.bumped(); Cmd cmd = av.update(s, now); w.drive(cmd.vl, cmd.vr); for (int k = 0; k < 20; ++k) w.step(0.001); bool b = w.bumped(); if (b && !was_bumped) ++bumps; was_bumped = b; if (w.x > 0 && w.x < 3.0 && w.y > 0 && w.y < 2.0) cells.insert((int)(w.x / 0.1) * 100 + (int)(w.y / 0.1)); else outside += 0.02; } r.bumps += bumps; r.coverage += cells.size() / 600.0; r.stuck += outside; } r.bumps /= seeds; r.coverage = 100.0 * r.coverage / seeds; r.stuck /= seeds; return r; } int main() { std::printf("obstacle avoider, 60 s, mean over 200 seeded runs\n"); std::printf(" front sensor dropouts handling collisions per run arena visited (%%) seconds outside the arena\n"); for (double dp : {0.02, 0.30}) for (bool safe : {false, true}) { R r = run(safe, dp, 200); std::printf(" %20.0f %% %-8s %18.2f %17.1f %25.2f\n", dp * 100, safe ? "safe" : "naive", r.bumps, r.coverage, r.stuck); } for (int lim : {6, 10}) { R r = run(true, 0.30, 200, lim); std::printf(" %20.0f %% safe, hold %-2d %14.2f %17.1f %25.2f", 30.0, lim, r.bumps, r.coverage, r.stuck); std::puts(""); } return 0; }
obstacle avoider, 60 s, mean over 200 seeded runs front sensor dropouts handling collisions per run arena visited (%) seconds outside the arena 2 % naive 0.08 22.4 0.00 2 % safe 0.03 22.3 0.00 30 % naive 0.10 22.4 0.00 30 % safe 0.02 8.1 0.16 30 % safe, hold 6 0.00 16.5 0.00 30 % safe, hold 10 0.03 20.6 0.00

Collisions are rare in every row, between 0 and 0.10 per run, because the only obstacles are the arena walls and the sensor sees the wall almost always; at 30 % dropouts the naive rule does not collide more (0.10) than at 2 % (0.08), and I would not read a difference in those hundredths. What does change is coverage: safe handling with a hold of 3 ticks (one reading) visits 8.1 % of the arena at 30 % dropouts against 22.4 % for the naive rule, because the robot keeps seeing “something near” where nothing is and spends its time backing and turning. Raising the hold to 6 ticks recovers 16.5 %, 10 ticks 20.6 %. So the safe rule buys fewer collisions at the price of coverage, and the hold is the knob; challenge 2 sweeps it. The safe, hold-3 row also spent 0.16 s per run outside the arena, which no other row did: on some runs the robot got through a wall. I did not trace why, so it stays a loose end, and a reminder that the number to watch is not only the average.

3. The same machine as a table

Three states fit a switch well. At fifteen they do not: the transitions are scattered through the cases, and adding one means editing code. A table-driven machine holds the transitions as data: one row per transition, {from, event, to, action}, and one small engine that looks up the row. In fsm.h the rows are four bytes each, the events are bits of a mask (bumper, something near, timer expired), and the first row whose state and event match wins:

const uint8_t ROWS[][4] FSM_PROGMEM = { // from, event, to, action { CRUISE, EV_BUMP, BACKUP, A_START_BACK }, { CRUISE, EV_NEAR, BACKUP, A_START_BACK }, { BACKUP, EV_TIMER, TURN, A_START_TURN }, { TURN, EV_TIMER, CRUISE, A_NONE }, };

What the robot does in a state is a function, and the table of functions (DO_FN, one pointer per state) is also const. On the Uno, PROGMEM keeps those tables in flash, and they are read with pgm_read_byte and pgm_read_ptr instead of a plain load, because the Uno’s flash and RAM are separate address spaces. That is the point of the “no dynamic allocation” comparison with Python: the whole machine is a few dozen bytes of constants known at compile time, with no heap and no object to build when the program starts.

What does it cost? The same avoider was compiled for the Uno in four ways into a sketch that reads A3 and the bumper pin and writes two PWM outputs (so the compiler cannot discard the machine). The first row has no machine at all:

VariantFlash (bytes)RAM (bytes)Over the baseline
no machine (baseline)21589 
switch (Avoider)340293+1244 flash, +84 RAM
table, tables in RAM3850118+1692 flash, +109 RAM
table, tables in flash (PROGMEM)387696+1718 flash, +87 RAM

Two things stand out. The table version is 474 bytes of flash larger than the switch for this three-state machine: the engine, the lookup and the function-pointer call are code that a hand-written switch does not need, and it only pays when the machine has many more states or rows. And putting the tables in flash saves exactly 22 bytes of RAM (118 against 96): the 16 bytes of the four rows plus the 6 bytes of the three function pointers, at a cost of 26 bytes more flash for the pgm_read calls. Twenty-two bytes is a minor saving for this table (about 1 % of the Uno’s 2048), but a table of 60 rows of four bytes is 240 bytes, and that is where the flash tables earn their place. The figures include the config struct and the state of NearCheck, which every machine variant carries.

// s_fsm.ino -- size test for chapter 7: the same obstacle avoider as a switch, as a table in RAM, and as a table in flash (PROGMEM). // Compile-checked for the Uno only; NOT run on a board. The "sensor" is analogRead(A3) and the "motors" are two analogWrite calls, so the compiler cannot drop the machine. // VARIANT 0: no machine (the baseline), 1: switch, 2: table. Add -DFSM_NO_PROGMEM to keep the table in RAM. #include "fsm.h" #include "pins.h" #ifndef VARIANT #define VARIANT 1 #endif static AvoidConfig CFG = {0.3f, 0.25f, 0.2f, 2.0f, 0.15f, 400, 400, 1200, 3, true}; #if VARIANT == 1 static Avoider machine(CFG, 1); #elif VARIANT == 2 static TableAvoider machine(CFG, 1); #endif void setup() { pinMode(PIN_ML_PWM, OUTPUT); pinMode(PIN_MR_PWM, OUTPUT); pinMode(PIN_BUMP, INPUT_PULLUP); } void loop() { Sense s; s.front_m = (float)analogRead(A3) * (4.0f / 1023.0f); s.right_m = -1.0f; s.bump = digitalRead(PIN_BUMP) == LOW; uint32_t now = millis(); #if VARIANT == 0 Cmd c = {s.front_m, s.bump ? 0.0f : s.front_m}; (void)now; #else Cmd c = machine.update(s, now); #endif analogWrite(PIN_ML_PWM, (int)((c.vl < 0 ? -c.vl : c.vl) * 100.0f)); analogWrite(PIN_MR_PWM, (int)((c.vr < 0 ? -c.vr : c.vr) * 100.0f)); delay(20); }

4. Testing a machine on the host

A state machine has two kinds of bug that a robot is a bad place to find: one in what it does (a wrong speed), and one in its structure (a state with no way out). Because the behaviours never touch a pin, both can be tested on a PC in a second. The experiment below does three things.

Part 1: does the table behave like the switch? Two simulators with the same seed, one driving the switch avoider and one the table avoider, are compared command by command (the bytes of the two Cmds) over 50 seeds at each of three settings. Part 2: a checker for the table itself: rows that point outside the table, a repeated (state, event) pair (the second can never fire), states not reachable from CRUISE, and states from which CRUISE can never be reached again. It is run on the good table and on three tables with one mistake each, and each is then driven in the simulator to see what the mistake looks like on a robot. Part 3: a time-out, in section 5.

// e_fsmcheck.cpp -- testing state machines on the host (no robot, no hardware). // Part 1: the switch-based Avoider and the table-driven TableAvoider must give the SAME wheel commands tick for tick, over 50 seeds and two dropout rates. // Part 2: a checker that reads a transition table and looks for: rows that point outside the table, duplicate (state, event) rows, states that cannot be reached // from CRUISE, and states from which CRUISE can never be reached again. It is run on the good table and on two tables with one mistake each, // and each table is then also driven in the simulator to show what the mistake looks like on the robot. // Part 3: a timeout. The line follower is put 200 mm away from the line (it cannot find it by spinning): with a 3 s search timeout it stops in FAULT; with the longest timeout // that fits its 16-bit field (65.5 s) it spins for the whole run. #include <cstdio> #include <cstring> #include <cmath> #include <set> #include "sim.h" #include "fsm.h" using namespace tbl; // ---------- part 2: the table checker ---------- struct Report { int out_of_range, duplicates, unreachable, cannot_return; }; static Report check(const uint8_t (*rows)[4], int n, int nstates, int start, bool verbose) { Report r = {0, 0, 0, 0}; for (int i = 0; i < n; ++i) { if (rows[i][0] >= nstates || rows[i][2] >= nstates) { ++r.out_of_range; if (verbose) std::printf(" row %d points outside the table\n", i); } for (int j = 0; j < i; ++j) if (rows[i][0] == rows[j][0] && rows[i][1] == rows[j][1]) { ++r.duplicates; if (verbose) std::printf(" row %d repeats (state %d, event %d) of row %d: row %d can never fire\n", i, rows[i][0], rows[i][1], j, i); } } bool reach[8] = {false}; reach[start] = true; for (int pass = 0; pass < nstates; ++pass) for (int i = 0; i < n; ++i) if (rows[i][0] < nstates && rows[i][2] < nstates && reach[rows[i][0]]) reach[rows[i][2]] = true; bool back[8] = {false}; // which states can get back to `start` back[start] = true; for (int pass = 0; pass < nstates; ++pass) for (int i = 0; i < n; ++i) if (rows[i][0] < nstates && rows[i][2] < nstates && back[rows[i][2]]) back[rows[i][0]] = true; for (int s = 0; s < nstates; ++s) { if (!reach[s]) { ++r.unreachable; if (verbose) std::printf(" state %d cannot be reached from state %d\n", s, start); } if (!back[s]) { ++r.cannot_return; if (verbose) std::printf(" state %d can never get back to state %d (a trap)\n", s, start); } } return r; } const uint8_t BAD_MISSING[][4] = { // the TURN -> CRUISE row was forgotten { CRUISE, EV_BUMP, BACKUP, A_START_BACK }, { CRUISE, EV_NEAR, BACKUP, A_START_BACK }, { BACKUP, EV_TIMER, TURN, A_START_TURN }, }; const uint8_t BAD_TYPO[][4] = { // BACKUP's timer row goes to BACKUP (typed the wrong state): TURN is never entered { CRUISE, EV_BUMP, BACKUP, A_START_BACK }, { CRUISE, EV_NEAR, BACKUP, A_START_BACK }, { BACKUP, EV_TIMER, BACKUP, A_START_TURN }, { TURN, EV_TIMER, CRUISE, A_NONE }, }; const uint8_t BAD_DUP[][4] = { // a second CRUISE/EV_NEAR row, copied and pasted, with a different target { CRUISE, EV_BUMP, BACKUP, A_START_BACK }, { CRUISE, EV_NEAR, BACKUP, A_START_BACK }, { CRUISE, EV_NEAR, TURN, A_START_TURN }, { BACKUP, EV_TIMER, TURN, A_START_TURN }, { TURN, EV_TIMER, CRUISE, A_NONE }, }; static AvoidConfig cfg(bool safe) { AvoidConfig c = {0.3f, 0.25f, 0.2f, 2.0f, 0.15f, 400, 400, 1200, 3, safe}; return c; } struct Sim { double coverage, cruise_pct, bumps; int final_state; }; static Sim drive_table(const uint8_t (*rows)[4], int n, int seeds) { Sim out = {0, 0, 0, 0}; for (int seed = 1; seed <= seeds; ++seed) { RobotParams rp; rp.tau = 0.1; SimHW w(rp, SensorParams(), Arena(), seed); w.th = (seed % 8) * 0.785; TableAvoider av(cfg(true), (uint32_t)seed, rows, (uint8_t)n); Sense s = {-1.0f, -1.0f, false}; std::set<int> cells; int cruise = 0; bool was = false; for (int tick = 0; tick < 3000; ++tick) { if (tick % 3 == 0) s.front_m = w.range_m(); s.bump = w.bumped(); Cmd c = av.update(s, tick * 20); w.drive(c.vl, c.vr); for (int k = 0; k < 20; ++k) w.step(0.001); bool b = w.bumped(); if (b && !was) out.bumps += 1; was = b; if (av.state() == CRUISE) ++cruise; if (w.x > 0 && w.x < 3.0 && w.y > 0 && w.y < 2.0) cells.insert((int)(w.x / 0.1) * 100 + (int)(w.y / 0.1)); } out.coverage += cells.size() / 600.0; out.cruise_pct += cruise / 3000.0; out.final_state += av.state(); } out.coverage = 100.0 * out.coverage / seeds; out.cruise_pct = 100.0 * out.cruise_pct / seeds; out.bumps /= seeds; out.final_state = out.final_state; return out; } // ---------- part 1: equivalence ---------- static void equivalence(double dropout, bool safe) { int diverged = 0; long ticks = 0; long first = -1; for (int seed = 1; seed <= 50; ++seed) { SensorParams sp; sp.dropout = dropout; RobotParams rp; rp.tau = 0.1; SimHW w1(rp, sp, Arena(), seed), w2(rp, sp, Arena(), seed); w1.th = w2.th = (seed % 8) * 0.785; Avoider a(cfg(safe), (uint32_t)seed); TableAvoider b(cfg(safe), (uint32_t)seed); Sense s1 = {-1.0f, -1.0f, false}, s2 = s1; bool bad = false; for (int tick = 0; tick < 3000 && !bad; ++tick) { if (tick % 3 == 0) { s1.front_m = w1.range_m(); s2.front_m = w2.range_m(); } s1.bump = w1.bumped(); s2.bump = w2.bumped(); Cmd c1 = a.update(s1, tick * 20), c2 = b.update(s2, tick * 20); if (std::memcmp(&c1, &c2, sizeof c1) != 0) { bad = true; if (first < 0) first = tick; } w1.drive(c1.vl, c1.vr); w2.drive(c2.vl, c2.vr); for (int k = 0; k < 20; ++k) { w1.step(0.001); w2.step(0.001); } ++ticks; } if (bad) ++diverged; } std::printf(" %8.0f %% %-5s %12d %16ld %s\n", dropout * 100, safe ? "safe" : "naive", 50, ticks, diverged == 0 ? "identical in every run" : "DIFFERENT"); if (diverged) std::printf(" %d runs diverged, first at tick %ld\n", diverged, first); } // ---------- part 3: a timeout ---------- static void timeout_demo(uint16_t timeout_ms) { RobotParams rp; rp.tau = 0.1; SimHW w(rp, SensorParams(), Arena(), 7); w.line.on = true; LineConfig c = {0.25f, 0.05f, 0.5f, 1.5f, 0.15f, timeout_ms}; LineFollower f(c); w.x = w.line.cx + w.line.R; w.y = w.line.cy; w.th = SIM_PI / 2; int16_t raw[5]; for (int i = -70; i <= 70; ++i) { double x0 = w.x; w.x = x0 + i * 0.001; w.line_read(raw); f.cal().learn(raw); w.x = x0; } w.x = w.line.cx + w.line.R + 0.2; w.y = w.line.cy; w.th = SIM_PI / 2; // 200 mm outside the line std::printf(" search timeout %5u ms:", (unsigned)timeout_ms); const double marks[] = {1, 2, 4, 10, 30}; int mi = 0; double turned = 0, prev = w.th; for (int tick = 0; tick < 1500; ++tick) { w.line_read(raw); Cmd cmd = f.update(raw, tick * 20); w.drive(cmd.vl, cmd.vr); for (int k = 0; k < 20; ++k) w.step(0.001); turned += std::fabs(w.th - prev); prev = w.th; if (mi < 5 && (tick + 1) * 0.02 >= marks[mi] - 1e-9) { std::printf(" %2.0f s: %-6s", marks[mi], f.state() == LineState::FOLLOW ? "FOLLOW" : f.state() == LineState::SEARCH ? "SEARCH" : "FAULT"); ++mi; } } std::printf(" turned %.1f revolutions in total\n", turned / (2 * SIM_PI)); } int main() { std::printf("part 1: does the table behave like the switch? (60 s per run, 3000 control ticks)\n"); std::printf(" dropouts mode runs compared ticks compared result\n"); equivalence(0.02, false); equivalence(0.02, true); equivalence(0.30, true); std::printf("\npart 2: the table checker\n"); struct { const char* name; const uint8_t (*rows)[4]; int n; } T[] = { {"good table", ROWS, (int)NROWS}, {"TURN -> CRUISE row missing", BAD_MISSING, (int)(sizeof BAD_MISSING / 4)}, {"BACKUP timer row typed as BACKUP", BAD_TYPO, (int)(sizeof BAD_TYPO / 4)}, {"duplicate CRUISE/EV_NEAR row", BAD_DUP, (int)(sizeof BAD_DUP / 4)}, }; std::printf(" states: 0 CRUISE, 1 BACKUP, 2 TURN; events: 0 BUMP, 1 NEAR, 2 TIMER\n"); for (auto& t : T) { Report r = check(t.rows, t.n, NSTATES, CRUISE, false); std::printf(" %s: %d rows, problems found: %d\n", t.name, t.n, r.out_of_range + r.duplicates + r.unreachable + r.cannot_return); check(t.rows, t.n, NSTATES, CRUISE, true); } std::printf("\n the same tables driven in the simulator (60 s, 50 seeds, 2%% dropouts, safe handling)\n"); std::printf(" table arena visited (%%) time in CRUISE (%%) collisions per run\n"); for (auto& t : T) { Sim s = drive_table(t.rows, t.n, 50); std::printf(" %-34s %16.1f %18.1f %18.2f\n", t.name, s.coverage, s.cruise_pct, s.bumps); } std::printf("\npart 3: line follower 200 mm off the line (it spins in place looking for it)\n"); timeout_demo(3000); timeout_demo(65535); return 0; }
part 1: does the table behave like the switch? (60 s per run, 3000 control ticks) dropouts mode runs compared ticks compared result 2 % naive 50 150000 identical in every run 2 % safe 50 150000 identical in every run 30 % safe 50 150000 identical in every run part 2: the table checker states: 0 CRUISE, 1 BACKUP, 2 TURN; events: 0 BUMP, 1 NEAR, 2 TIMER good table: 4 rows, problems found: 0 TURN -> CRUISE row missing: 3 rows, problems found: 2 state 1 can never get back to state 0 (a trap) state 2 can never get back to state 0 (a trap) BACKUP timer row typed as BACKUP: 4 rows, problems found: 2 state 1 can never get back to state 0 (a trap) state 2 cannot be reached from state 0 duplicate CRUISE/EV_NEAR row: 5 rows, problems found: 1 row 2 repeats (state 0, event 1) of row 1: row 2 can never fire the same tables driven in the simulator (60 s, 50 seeds, 2% dropouts, safe handling) table arena visited (%) time in CRUISE (%) collisions per run good table 22.9 72.0 0.02 TURN -> CRUISE row missing 1.4 4.3 0.00 BACKUP timer row typed as BACKUP 3.2 4.3 1.00 duplicate CRUISE/EV_NEAR row 22.9 72.0 0.02 part 3: line follower 200 mm off the line (it spins in place looking for it) search timeout 3000 ms: 1 s: SEARCH 2 s: SEARCH 4 s: FAULT 10 s: FAULT 30 s: FAULT turned 0.7 revolutions in total search timeout 65535 ms: 1 s: SEARCH 2 s: SEARCH 4 s: SEARCH 10 s: SEARCH 30 s: SEARCH turned 7.1 revolutions in total

Part 1: the two implementations produced bit-identical commands in all 150 000 control ticks at each of three settings (2 % and 30 % dropouts, naive and safe). That proves the two agree on those inputs; it does not prove they agree on inputs the simulator did not produce, which is what the checker is for.

Part 2: the checker reports nothing for the good table and one or two problems for each broken one. The three bugs look very different on the robot. With the TURN → CRUISE row missing, the robot reaches its first obstacle, backs up, turns, and then spins in TURN forever: 1.4 % of the arena visited and 4.3 % of the time in CRUISE (the time before the first obstacle), against 22.9 % and 72.0 % for the good table. With the BACKUP row typed as BACKUP, it reverses forever (by the code, blindly), visits 3.2 % and ends every run with a collision (1.00 per run, against 0.02). The duplicate row, a copy-and-paste of the CRUISE / near row with a different target, is the instructive one: the simulator shows no difference at all (22.9 %, 72.0 %, 0.02, the same digits as the good table) because the engine takes the first matching row and the copy is never reached. A test that only watches behaviour cannot see it; the checker flags it in a line. That is the argument for checking a table as data: some bugs are not behaviours until the day someone reorders the rows.

5. Time-outs: every state needs a way out

A machine that waits for something (an echo, a wall, a line) must not wait forever. The rule that follows from the checker is: every state that depends on the world must also have an exit that depends only on the clock, and the last resort is a FAULT state that stops the robot and says so. Part 3 of the experiment puts the line follower 200 mm away from the line, where spinning in place cannot find it (the sensors sweep a circle of 80 mm radius around the robot), and compares a 3 s search time-out with the longest one the 16-bit field allows, 65.5 s:

With the 3 s time-out the robot is in SEARCH at 1 s and 2 s, in FAULT from 4 s on, and has turned 0.7 revolutions in total (3 s at the search rate of 1.5 rad/s). With 65 535 ms it is still in SEARCH at 30 s and has turned 7.1 revolutions: a robot that spins on the spot until the battery is flat, which for a robot that is not on a line is not harmless. The FAULT state is not an admission of failure but a design decision: a robot that stops is safe, and the person who reads “FAULT” on the serial port knows where to look. Note also what a time-out costs: a state with a time-out has to remember when it was entered (t0_), and the rows of a table machine need a TIMER event, which section 3’s engine gets from comparing now - t0_ to the state’s limit.

6. Following a wall

The wall follower keeps the wall on its right. Its states: FOLLOW (steer on the side distance), CORNER (the front is blocked: spin left until the front is clear), SEARCH (the wall has gone: arc to the right to find it), FAULT (a time-out in CORNER or SEARCH). The side sensor is read every 60 ms and its last good reading is held for 300 ms, so a single missing echo does not send the machine into SEARCH. The experiment compares the naive controller (steer on the side distance and nothing else) with the machine, at 2 % and at 30 % dropouts, over 100 seeded runs of 100 s each:

// e_wall.cpp -- a right-hand wall follower around the 3 x 2 m arena, 100 s at 0.3 m/s, 100 seeded runs per row (host build; sensor noise and dropouts are the simulator's). // "naive": steer on the right-hand distance only (P control, target 0.30 m); nothing else. "machine": FOLLOW, CORNER (spin left until the front is clear), SEARCH (arc right when the wall is lost), // FAULT (stop after a time-out). Both sensors are read every 60 ms; the side reading is held for 300 ms if one echo is missing. // Scored: laps of the arena, collisions (bumper pressed), the rms error of the true side distance (mm) while the robot is inside the arena, and the share of runs that ended in FAULT. #include <cstdio> #include <cmath> #include <initializer_list> #include "sim.h" #include "fsm.h" struct R { double laps, bumps, rms_mm, faults; }; static R run(bool full, double dropout, int seeds) { R r = {0, 0, 0, 0}; double sq = 0; long n = 0; for (int seed = 1; seed <= seeds; ++seed) { RobotParams rp; rp.tau = 0.1; SensorParams sp; sp.dropout = dropout; SimHW w(rp, sp, Arena(), seed); w.x = 0.5; w.y = 0.3; w.th = 0.0; WallConfig c = {0.3f, 0.30f, 4.0f, 0.40f, 0.70f, 1.5f, 0.15f, 0.8f, 0.15f, 300, 3000, 3000, full}; WallFollower f(c); Sense s = {-1.0f, -1.0f, false}; bool was_bumped = false; double angle = 0, prev_a = std::atan2(w.y - 1.0, w.x - 1.5); double bumps = 0; for (int tick = 0; tick < 5000; ++tick) { uint32_t now = tick * 20; if (tick % 3 == 0) { s.front_m = w.range_m(); s.right_m = w.range_right_m(); } s.bump = w.bumped(); Cmd cmd = f.update(s, now); w.drive(cmd.vl, cmd.vr); for (int k = 0; k < 20; ++k) w.step(0.001); bool b = w.bumped(); if (b && !was_bumped) ++bumps; was_bumped = b; double a = std::atan2(w.y - 1.0, w.x - 1.5); double da = std::remainder(a - prev_a, 2 * SIM_PI); angle += da; prev_a = a; if (tick > 250 && w.x > 0 && w.x < 3 && w.y > 0 && w.y < 2) { double d = w.ray_from(w.x + 0.075 * std::sin(w.th), w.y - 0.075 * std::cos(w.th), w.th - SIM_PI / 2); double e = std::fmin(d, 1.0) - 0.30; sq += e * e; ++n; } } r.laps += angle / (2 * SIM_PI); r.bumps += bumps; if (full && f.state() == WallState::FAULT) r.faults += 1; } r.laps /= seeds; r.bumps /= seeds; r.rms_mm = std::sqrt(sq / n) * 1000; r.faults = 100.0 * r.faults / seeds; return r; } int main() { std::printf("right-hand wall follower, 100 s, mean over 100 seeded runs\n"); std::printf(" dropouts controller laps (counter-clockwise) collisions per run side error rms (mm) runs ending in FAULT (%%)\n"); for (double dp : {0.02, 0.30}) for (bool full : {false, true}) { R r = run(full, dp, 100); std::printf(" %6.0f %% %-10s %24.2f %18.2f %19.1f %24.0f\n", dp * 100, full ? "machine" : "naive", r.laps, r.bumps, r.rms_mm, r.faults); } return 0; }
right-hand wall follower, 100 s, mean over 100 seeded runs dropouts controller laps (counter-clockwise) collisions per run side error rms (mm) runs ending in FAULT (%) 2 % naive 0.41 1.00 95.9 0 2 % machine 3.52 0.00 106.4 0 30 % naive 0.42 1.00 105.5 0 30 % machine 3.53 0.00 100.6 0

The naive controller has one collision per run (the first corner) and gets only 0.41 of a lap; the machine goes round 3.5 times with no collisions and no FAULT, at both dropout rates. The state machine is what makes the difference. But look at the last column but one: the side error is about 100 mm for both, against a target of 300 mm, and that is large enough to be a finding, not a rounding. I first guessed it was the corners. A trace of the true side error and heading on the first wall, without noise or dropouts and then with them, says otherwise:

// d_wall.cpp -- diagnostic: the TRUE side error (mm) and heading (deg) every 0.5 s along the first wall, with and without sensor noise/dropouts (kp 4). #include <cstdio> #include <cmath> #include "sim.h" #include "fsm.h" static void trace(const char* name, double sigma, double dropout) { RobotParams rp; rp.tau = 0.1; SensorParams sp; sp.sigma_m = sigma; sp.dropout = dropout; SimHW w(rp, sp, Arena(), 3); w.x = 0.5; w.y = 0.3; w.th = 0.0; WallConfig c = {0.3f, 0.30f, 4.0f, 0.40f, 0.70f, 1.5f, 0.15f, 0.8f, 0.15f, 300, 3000, 3000, true}; WallFollower f(c); Sense s = {-1.0f, -1.0f, false}; std::printf("%s\n t(s):", name); for (int tick = 0; tick < 500; ++tick) { if (tick % 3 == 0) { s.front_m = w.range_m(); s.right_m = w.range_right_m(); } s.bump = w.bumped(); Cmd cmd = f.update(s, tick * 20); w.drive(cmd.vl, cmd.vr); for (int k = 0; k < 20; ++k) w.step(0.001); if (tick % 25 == 24) { double d = w.ray_from(w.x + 0.075 * std::sin(w.th), w.y - 0.075 * std::cos(w.th), w.th - SIM_PI / 2); std::printf(" %4.0f(%+4.0f)", (d - 0.30) * 1000, w.th * 57.2958); } } std::puts(""); } int main() { trace("noise-free, no dropouts", 0.0, 0.0); trace("default noise and 2% dropouts", 0.005, 0.02); return 0; }
noise-free, no dropouts t(s): -65( +7) -27( +15) 21( +17) 59( +14) 80( +8) 86( -1) 79( -10) 56( -17) 14( -22) -48( -21) -106( -12) -127( +2) -92( +16) -13( +25) 82( +33) 30( +68) -27( +70) -84( +76) -115( +88) -97(+102) default noise and 2% dropouts t(s): -64( +8) -23( +15) 27( +18) 66( +15) 85( +7) 89( -2) 80( -11) 56( -18) 11( -23) -56( -22) -119( -13) -139( +3) -97( +19) -6( +28) 83( +32) 29( +69) -24( +72) -76( +77) -104( +88) -89(+100)

Even with a perfect sensor the robot swings from −127 mm to +86 mm and back, with the heading going ±20°; the noisy trace is within about 12 mm of the clean one at every sample, so the sensor is not the cause: the controller is. Steering by a turn rate proportional to the distance error makes the heading the integral of the error and the lateral position the integral of the heading: a double integrator with a proportional gain is an oscillator with no damping, with period 2π/√(v·kp) = 5.7 s for v = 0.3 m/s and kp = 4. The upward crossings of the trace are 5.8 s apart (one seed, one trace; I would not claim the match to 0.1 s). Challenge 1 sweeps kp. The cure the theory gives is a term that damps (a heading or a rate-of-change term); I did not build or test one, so the chapter does not claim it works here.

7. Following a line

The line follower reads five reflectance sensors 80 mm ahead of the robot’s centre, calibrates each one on a sweep across the line (Programming for Robotics with Arduino C++ 4), forms the weighted position of the line in millimetres, and steers on it. FOLLOW steers and slows down when the line is far off-centre; if no sensor sees the line it goes to SEARCH, spinning toward the side where the line was last seen, with the time-out of section 5; SEARCH ends in FAULT. The line here is a circle of radius 0.6 m with a response 25 mm either side; the score is the true distance of the robot’s centre from the line, which only the simulator knows.

// e_line.cpp -- a line follower on a circular line (radius 0.6 m, 50 mm of response either side) with the five-sensor array of chapter 4, calibrated by a sweep (host build). // Machine: FOLLOW (steer on the weighted line position, slow down off the line), SEARCH (line lost: spin toward the side it was last seen, up to 3 s), FAULT (stop). // 30 s, 20 seeded runs per row. Scored on the TRUE distance of the robot's centre from the line (rms, mm, over the whole run), the number of times the line was lost, laps, and runs ending in FAULT. #include <cstdio> #include <cmath> #include <initializer_list> #include "sim.h" #include "fsm.h" struct R { double rms_mm, lost, laps, faults; }; static R run(float v, float k_w, int seeds) { R r = {0, 0, 0, 0}; double sq = 0; long n = 0; for (int seed = 1; seed <= seeds; ++seed) { RobotParams rp; rp.tau = 0.1; SimHW w(rp, SensorParams(), Arena(), seed); w.line.on = true; LineConfig c = {v, k_w, 0.5f, 1.5f, 0.15f, 3000}; LineFollower f(c); w.x = w.line.cx + w.line.R; w.y = w.line.cy; w.th = SIM_PI / 2; // on the line, heading counter-clockwise int16_t raw[5]; for (int i = -70; i <= 70; ++i) { // the calibration sweep: the array is moved 70 mm across the line, both ways double x0 = w.x; w.x = x0 + i * 0.001; w.line_read(raw); f.cal().learn(raw); w.x = x0; } double angle = 0, prev_a = std::atan2(w.y - w.line.cy, w.x - w.line.cx); for (int tick = 0; tick < 1500; ++tick) { w.line_read(raw); Cmd cmd = f.update(raw, tick * 20); w.drive(cmd.vl, cmd.vr); for (int k = 0; k < 20; ++k) w.step(0.001); double e = w.line_error(); sq += e * e; ++n; double a = std::atan2(w.y - w.line.cy, w.x - w.line.cx); angle += std::remainder(a - prev_a, 2 * SIM_PI); prev_a = a; } r.lost += f.lost_events(); r.laps += angle / (2 * SIM_PI); if (f.state() == LineState::FAULT) r.faults += 1; } r.rms_mm = std::sqrt(sq / n) * 1000; r.lost /= seeds; r.laps /= seeds; r.faults = 100.0 * r.faults / seeds; return r; } int main() { std::printf("line follower, 30 s, mean over 20 runs\n"); std::printf(" speed (m/s) steering gain (rad/s per mm) rms distance from the line (mm) times the line was lost laps runs in FAULT (%%)\n"); for (float v : {0.15f, 0.25f, 0.35f, 0.50f}) { R r = run(v, 0.05f, 20); std::printf(" %11.2f %28.2f %31.1f %23.2f %4.2f %16.0f\n", v, 0.05, r.rms_mm, r.lost, r.laps, r.faults); } for (float k : {0.02f, 0.10f, 0.20f}) { R r = run(0.25f, k, 20); std::printf(" %11.2f %28.2f %31.1f %23.2f %4.2f %16.0f\n", 0.25, (double)k, r.rms_mm, r.lost, r.laps, r.faults); } return 0; }
line follower, 30 s, mean over 20 runs speed (m/s) steering gain (rad/s per mm) rms distance from the line (mm) times the line was lost laps runs in FAULT (%) 0.15 0.05 1.5 0.00 1.12 0 0.25 0.05 1.2 0.00 1.79 0 0.35 0.05 5.3 0.00 2.40 0 0.50 0.05 9.9 0.00 3.24 0 0.25 0.02 11.8 0.00 1.55 0 0.25 0.10 2.0 0.00 1.89 0 0.25 0.20 3.6 0.00 1.94 0

Over this circle the follower never lost the line, not even at 0.50 m/s, the top speed of this robot; what changes with speed is the distance from the line, from about 1.2–1.5 mm at 0.15 and 0.25 m/s to 5.3 mm at 0.35 and 9.9 mm at 0.50 m/s. The 1.5 against 1.2 at the two slow speeds is a difference of 0.3 mm that I would not read as a trend. The gain matters more than the speed: at 0.25 m/s, 0.02 rad/s per mm leaves 11.8 mm (too weak to hold a curve), 0.05 gives 1.2, 0.10 gives 2.0 and 0.20 gives 3.6, which begins to ring. This is a favourable test: one smooth circle, with no gaps, sharp corners or crossings, a simulated array whose gains and offsets I made up, and a line wide enough for the array. A real track is harder, and the SEARCH and FAULT states exist for the part that I did not test on one.

8. On the Uno

robot_ch7.ino puts the table-driven avoider on the pin plan of Programming for Robotics with Arduino C++ 2: the non-blocking ultrasonic driver of the same chapter on pins 8 and 12, a median-of-five filter at the seam (a dropout passed on as a dropout), the bumper on pin 11, the motors through the dead-zone mapping of Programming for Robotics with Arduino C++ 5, and a 20 ms think_task on the scheduler of Programming for Robotics with Arduino C++ 1 that calls machine.update() and prints the state when it changes.

// robot_ch7.ino -- Programming for Robotics with Arduino C++, chapter 7: the obstacle avoider as a table-driven state machine (table in flash). // Compile-checked for the Uno (arduino:avr:uno). NOT run on a board: no board, motor, sensor or bumper was attached; every number in AvoidConfig comes from the SIMULATOR. #include "scheduler.h" #include "conv.h" #include "echo.h" #include "pins.h" #include "filters.h" #include "motion.h" #include "fsm.h" const float V_MAX_MPS = 0.5f; const uint8_t DEAD_DUTY = 40; // ASSUMED: measure yours (Programming for Robotics with Arduino C++ 5, challenge 3) 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 Scheduler<3> sch; static bool trig_level = false; static float g_range = -1.0f; // the filtered front distance; negative after a dropout static uint8_t g_last_state = 255; static void drive(float vl, float vr) { digitalWrite(PIN_ML_DIR, vl >= 0.0f ? HIGH : LOW); digitalWrite(PIN_MR_DIR, vr >= 0.0f ? HIGH : LOW); analogWrite(PIN_ML_PWM, speed_to_pwm_dz(vl >= 0.0f ? vl : -vl, V_MAX_MPS, DEAD_DUTY)); analogWrite(PIN_MR_PWM, speed_to_pwm_dz(vr >= 0.0f ? vr : -vr, V_MAX_MPS, DEAD_DUTY)); } static void echo_start_task(void*, uint32_t) { echo.start(); } static void think_task(void*, uint32_t now) { // every 20 ms: read, decide, act Sense s; s.front_m = g_range; s.right_m = -1.0f; s.bump = digitalRead(PIN_BUMP) == LOW; Cmd c = machine.update(s, now); drive(c.vl, c.vr); uint8_t st = machine.state(); if (st != g_last_state) { g_last_state = st; Serial.print(now); Serial.print(F(" ms state ")); Serial.println((int)st); } } 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(think_task, 0, 20); sch.add(echo_start_task, 0, 60); } void loop() { bool before = trig_level; Echo::Status st = echo.update(micros(), digitalRead(PIN_ECHO), trig_level); if (trig_level != before) digitalWrite(PIN_TRIG, trig_level); if (st == Echo::READY) g_range = (float)median.update((int16_t)(echo_us_to_m(echo.width_us()) * 1000.0f + 0.5f)) * 0.001f; else if (st == Echo::TIMEOUT) g_range = -1.0f; // a dropout is passed on as a dropout, not averaged in sch.run(millis()); }

It compiles for the Uno under --warnings all with no warning from the sketch to 7114 bytes of flash (22 %) and 381 bytes of RAM (18 %). For comparison, the earlier chapters’ sketches were 8626 bytes and 433 bytes (Programming for Robotics with Arduino C++ 4), 8868 and 409 (Programming for Robotics with Arduino C++ 5) and 7638 and 541 (Programming for Robotics with Arduino C++ 6). It was not run: the avoider’s gains (stop at 0.25 m, 400 ms backing, 400–1200 ms turning, a hold of 3 ticks) come from the simulator, the dead zone of 40 is an assumption, and how the real sensor reacts to a corner at a shallow angle is not in the simulator at all.

9. What the numbers can and cannot be trusted for

What they show. The shapes: the switch and the table give identical behaviour on 450 000 simulated ticks; the table is 474 bytes larger in flash for three states and flash tables save 22 bytes of RAM; a table can hold a bug (a shadowed row) that no simulation shows and a checker finds in a line; a missing exit or a mistyped state turns the robot into a spinner or a reverser; a machine without a time-out can spin for ever; the wall follower’s error is the controller’s own oscillation, not noise; the line follower holds a smooth circle to millimetres up to the robot’s top speed. The sizes are the compiler’s for the real chip.

What they do not show. The arena, the line, the sensor noise and the dropout rates, and the array’s gains and offsets, are assumptions; a real room has furniture at angles, soft obstacles that return no echo, a floor that is not uniformly reflective. The collision counts are small numbers from a simulator whose obstacles are straight walls, and I would not use them to rank the two dropout rules. No time per pass was measured and nothing ran on a board. The wall follower’s oscillation is diagnosed but not cured, and the line follower was not tried on a track with gaps, corners or crossings.

Challenge 1: The wall follower’s gain
Sweep the proportional gain kp of the wall follower (1, 2, 4, 8, 16 and 32 rad/s per metre) over 60 seeded runs of 100 s and report laps, collisions, the rms side error over the whole run, the rms side error in FOLLOW only (at least 2 s after the last corner) and the share of time in CORNER. Then trace the true side error on the first wall without noise and compare the swing’s period with 2π/√(v·kp). Say what the sweep does and does not explain.
View solution
Challenge 2: How long to trust the last echo
Sweep the avoider’s drop_limit (1, 2, 3, 6, 10 and 20 control ticks) at 2 % and at 30 % dropouts and report collisions, arena coverage and the share of time not in CRUISE. Convert each limit to sensor readings, and explain the drop in coverage at 2 % dropouts for limits of 1 and 2.
View solution
Challenge 3: How wide a calibration sweep
Sweep the line follower’s calibration width (no sweep, and ±10, 20, 30, 40, 50 and 70 mm) and report the rms distance from the line, the number of times the line was lost, laps and the share of runs ending in FAULT. Explain the width below which calibration is wrong, and say why the rms of 0.0 mm for the run with no calibration is not good news.
View solution

Quick reference

  • Switch machine. enum class state in one byte, switch with every case; the behaviour is a pure update(Sense, now) → Cmd; the transition tick returns zero speeds.
  • Table machine. Rows {from, event, to, action}, events as bits, the first matching row wins; tables in PROGMEM read with pgm_read_byte / pgm_read_ptr. Identical to the switch over 450 000 ticks.
  • Cost on the Uno. Baseline 2158 B flash, 9 B RAM. Switch +1244 / +84. Table in RAM +1692 / +109. Table in flash +1718 / +87. Flash tables save 22 B of RAM (16 rows + 6 pointers) for 26 B more flash; the table is 474 B larger than the switch at three states.
  • Checker. Out-of-range rows, duplicate (state, event), unreachable states, states that cannot return. Missing TURN→CRUISE: 1.4 % coverage. Mistyped BACKUP row: 3.2 %, one collision per run. Duplicate row: no visible difference in simulation, one line from the checker.
  • Time-out. Every state that waits on the world needs a clock exit and a FAULT: 3 s gives FAULT from 4 s on (0.7 revolutions); 65.5 s spins 7.1 revolutions in 30 s.
  • Avoider. drop_limit counts 20 ms ticks, 3 = one 60 ms reading. 30 % dropouts: naive 22.4 % coverage, safe hold 3 8.1 %, hold 6 16.5 %, hold 10 20.6 %; collisions 0.00–0.10 per run.
  • Wall follower. Naive: 1.00 collision, 0.41 laps. Machine: 3.52 laps, 0 collisions, 0 FAULT; side error about 100 mm is an oscillation of the P controller (period near 2π/√(v·kp) = 5.7 s), not noise. Damping term not built.
  • Line follower. Circle R 0.6 m: never lost up to 0.50 m/s; rms 1.2 mm at 0.25 m/s, 9.9 mm at 0.50; gain 0.05 best of four at 0.25 m/s. Calibration sweep needs at least the outer sensor offset (40 mm); with none, FAULT in every run.
  • Budget. robot_ch7.ino: 7114 bytes flash (22 %), 381 bytes RAM (18 %), compiled, not run.
  • Not run: anything on a board; time per pass; a track with gaps or crossings; a cure for the wall follower’s oscillation.

Next: Programming for Robotics with Arduino C++ 8, Concurrency and Real-Time Basics

Programming for Robotics with Arduino C++ 8 (planned; not yet written) looks at what happens when more than one thing wants the processor: interrupts and shared data, what a long task does to a short one, priorities in a cooperative scheduler, and how to find out whether the robot of this chapter still meets its 20 ms deadline once the sensors, the controllers and the machine all run together.