Planning in Kilobytes

Programming for Robotics with Arduino C++

Course 2 · Chapter 9 · Planning and Navigation

Programming for Robotics with Arduino C++ 7 gave the robot decisions and Programming for Robotics with Arduino C++ 8 the timing to carry them out; this chapter gives it a route. The robot has a map, a start and a goal, and must choose a path that avoids the obstacles and then follow it. Planners are usually taught with lists, dictionaries, sets and priority queues that grow as needed. Here none of that exists: every array has its size fixed at compile time, the Uno has 2048 bytes of RAM, and the question that decides the design is not “which algorithm is elegant?” but “which one fits?”.

The chapter builds a grid map held in one bit per cell (and, if it never changes, in flash with no RAM at all), a breadth-first search and an A* planner with fixed-size queues, a line-of-sight smoother, and a pure-pursuit path follower. As in the whole course, the numbers come from running the code, and this chapter has more than its share of my own mistakes: a test world with gaps that closed, and a path follower with two bugs that only the tests found.

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, in a simulated 3 × 2 m arena with four boxes. The map, the range sensor’s noise and “ghost” echoes, the robot’s 1 cm / 1° localisation error and its speeds are assumptions I chose, not measurements. Compiled for the Uno, not run (arduino-cli, core arduino:avr 1.8.8, --warnings all): the four-variant size-test sketch and robot_ch9.ino. The flash and RAM figures are the compiler’s; the symbol sizes come from avr-nm. Nothing was attached to a board and no time was measured: the chapter reports cells expanded and bytes used, not how long a plan takes on a 16 MHz chip.

1. The budget decides the algorithm

A path planner needs three things: a map (which cells are blocked), a frontier (the cells waiting to be explored) and some bookkeeping (how each cell was reached, so the path can be read back). In Python each is a convenient object that grows: a set of blocked (x, y) tuples, a deque or a heapq, a dictionary of parents. On the Uno each one is an array with a size you chose before the program ran, and what you chose is what you get.

In PythonOn the Uno in C++
a set of blocked cells, or a list of listsone bit per cell in a byte array: 600 cells are 75 bytes
a dictionary of parents, came_from[cell]2 bits per cell for the direction the cell was entered from: the parent is one step back
collections.deque, heapq: grow without limita ring buffer and a binary heap of fixed size; a planner that fills them gives up and says so, it never overruns
the map is read from a file at start-upthe map can stay in flash (PROGMEM) and be read with pgm_read_byte: no RAM at all
float costs, any size of gridbyte-sized costs (a path of up to 254 steps), a grid of a few hundred to a thousand cells

2. The grid, in bits

The whole of the chapter’s code is in one header. BitGrid<W, H> stores one bit per cell row by row; any class with a blocked(x, y) method is a map, and a cell outside the grid counts as blocked, so the planner never has to test the edges. FlashGrid has the same layout and reads from a table in flash. inflate() makes every obstacle one cell bigger in every direction, so that the planner can treat the robot as a point (the robot has a radius, and a path through the middle of a free cell next to an obstacle is a collision). Below are also the planners, the smoother and the path follower of the next sections.

// grid.h -- occupancy grids as bit arrays, breadth-first search and A* in a fixed memory budget, and pure pursuit (Programming for Robotics with Arduino C++ 9). // Plain C++11: no heap, no Arduino calls except pgm_read_byte for a map kept in flash. Every array has a size known at compile time, so its RAM cost can be read off. #pragma once #include <stdint.h> #include <math.h> #include "fsm.h" // Cmd, arc(), spin() #if defined(__AVR__) && !defined(GRID_NO_PROGMEM) #include <avr/pgmspace.h> #define GRID_PROGMEM PROGMEM #define GRID_READ8(p) pgm_read_byte(p) #else #define GRID_PROGMEM #define GRID_READ8(p) (*(p)) #endif // ---- 1. the grid: one BIT per cell, row by row. A map is anything with blocked(x, y) (outside the grid counts as blocked). ---- template <uint8_t W, uint8_t H> class BitGrid { public: static const uint16_t CELLS = (uint16_t)W * H; static const uint16_t BYTES = (uint16_t)((CELLS + 7) / 8); BitGrid() { clear(); } void clear() { for (uint16_t i = 0; i < BYTES; ++i) b_[i] = 0; } bool get(uint8_t x, uint8_t y) const { uint16_t i = (uint16_t)y * W + x; return (b_[i >> 3] >> (i & 7)) & 1; } void set(uint8_t x, uint8_t y, bool v) { uint16_t i = (uint16_t)y * W + x; if (v) b_[i >> 3] |= (uint8_t)(1u << (i & 7)); else b_[i >> 3] &= (uint8_t)~(1u << (i & 7)); } bool blocked(int16_t x, int16_t y) const { return x < 0 || y < 0 || x >= W || y >= H || get((uint8_t)x, (uint8_t)y); } const uint8_t* bytes() const { return b_; } private: uint8_t b_[BYTES]; }; // the same layout, read straight from a table in flash (PROGMEM): no RAM at all for the map template <uint8_t W, uint8_t H> class FlashGrid { public: explicit FlashGrid(const uint8_t* table) : p_(table) {} bool blocked(int16_t x, int16_t y) const { if (x < 0 || y < 0 || x >= W || y >= H) return true; uint16_t i = (uint16_t)y * W + (uint16_t)x; return (GRID_READ8(p_ + (i >> 3)) >> (i & 7)) & 1; } private: const uint8_t* p_; }; // grow every obstacle by r cells in every direction (a square neighbourhood), so the planner can treat the robot as a point template <class Src, uint8_t W, uint8_t H> inline void inflate(const Src& src, BitGrid<W, H>& dst, uint8_t r) { for (uint8_t y = 0; y < H; ++y) for (uint8_t x = 0; x < W; ++x) { bool b = false; for (int8_t dy = -(int8_t)r; dy <= (int8_t)r && !b; ++dy) for (int8_t dx = -(int8_t)r; dx <= (int8_t)r && !b; ++dx) if (src.blocked(x + dx, y + dy)) b = true; dst.set(x, y, b); } } // is the straight line between two cells free? (a grid walk: every cell the line crosses is checked, plus the diagonal neighbours) template <class Map> inline bool line_clear(const Map& m, int16_t x0, int16_t y0, int16_t x1, int16_t y1) { int16_t dx = x1 > x0 ? x1 - x0 : x0 - x1, dy = y1 > y0 ? y1 - y0 : y0 - y1; int16_t sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1, err = dx - dy; for (;;) { if (m.blocked(x0, y0)) return false; if (x0 == x1 && y0 == y1) return true; int16_t e2 = 2 * err; bool mx = e2 > -dy, my = e2 < dx; if (mx && my && (m.blocked(x0 + sx, y0) || m.blocked(x0, y0 + sy))) return false; // do not squeeze through a diagonal gap if (mx) { err -= dy; x0 += sx; } if (my) { err += dx; y0 += sy; } } } // ---- 2. breadth-first search. Memory: visited bits + 2 bits per cell for "which way did I arrive" + a ring buffer of Q cell numbers. ---- // plan() returns the number of steps, -1 if the goal cannot be reached, -2 if the queue was too small (the search is abandoned, never overrun). // the four neighbours as functions, not as a const table: on an AVR a const array still lives in RAM (a copy of 4 + 4 bytes) unless it is PROGMEM inline int8_t dx4(uint8_t d) { return d == 0 ? 1 : (d == 2 ? -1 : 0); } inline int8_t dy4(uint8_t d) { return d == 1 ? 1 : (d == 3 ? -1 : 0); } template <uint8_t W, uint8_t H, uint16_t Q> class Bfs { public: static const uint16_t CELLS = (uint16_t)W * H; uint16_t expanded() const { return expanded_; } uint16_t max_frontier() const { return maxq_; } template <class Map> int16_t plan(const Map& m, uint8_t sx, uint8_t sy, uint8_t gx, uint8_t gy, uint16_t* path, uint16_t path_cap) { seen_.clear(); expanded_ = 0; maxq_ = 0; if (m.blocked(sx, sy) || m.blocked(gx, gy)) return -1; uint16_t head = 0, count = 0; uint16_t start = (uint16_t)sy * W + sx, goal = (uint16_t)gy * W + gx; seen_.set(sx, sy, true); q_[0] = start; count = 1; maxq_ = 1; bool found = start == goal; while (count && !found) { uint16_t c = q_[head]; head = (uint16_t)((head + 1) % Q); --count; ++expanded_; uint8_t cx = (uint8_t)(c % W), cy = (uint8_t)(c / W); for (uint8_t d = 0; d < 4; ++d) { int16_t nx = cx + dx4(d), ny = cy + dy4(d); if (m.blocked(nx, ny) || seen_.get((uint8_t)nx, (uint8_t)ny)) continue; if (count >= Q) return -2; seen_.set((uint8_t)nx, (uint8_t)ny, true); set_dir((uint16_t)ny * W + nx, d); q_[(head + count) % Q] = (uint16_t)((uint16_t)ny * W + nx); ++count; if (count > maxq_) maxq_ = count; if ((uint16_t)ny * W + nx == goal) { found = true; break; } } } if (!found) return -1; return trace(start, goal, path, path_cap); } private: void set_dir(uint16_t i, uint8_t d) { uint8_t s = (uint8_t)((i & 3) * 2); dir_[i >> 2] = (uint8_t)((dir_[i >> 2] & ~(3u << s)) | ((uint32_t)d << s)); } uint8_t get_dir(uint16_t i) const { return (dir_[i >> 2] >> ((i & 3) * 2)) & 3; } int16_t trace(uint16_t start, uint16_t goal, uint16_t* path, uint16_t cap) const { uint16_t n = 0, c = goal; while (c != start) { ++n; uint8_t d = get_dir(c); c = (uint16_t)((int16_t)c - dx4(d) - (int16_t)W * dy4(d)); } if (n + 1 > cap) return -2; c = goal; for (int16_t k = (int16_t)n; k >= 0; --k) { path[k] = c; if (k) { uint8_t d = get_dir(c); c = (uint16_t)((int16_t)c - dx4(d) - (int16_t)W * dy4(d)); } } return (int16_t)n; } BitGrid<W, H> seen_; uint8_t dir_[(CELLS + 3) / 4]; uint16_t q_[Q]; uint16_t expanded_, maxq_; }; // ---- 3. A*. Memory: closed bits, 2 bits per cell for the arrival direction, ONE BYTE per cell for the cost so far (g, saturating at 254 steps), and a heap of HC entries of 4 bytes. ---- // f = 4 g + wq h, where h is the Manhattan distance to the goal: wq = 4 is the ordinary A* (optimal on this grid), wq > 4 is "weighted": faster, not always shortest, wq = 0 is no heuristic at all. // plan() returns the steps, -1 no path, -2 heap full (abandoned), -3 a path longer than 254 steps (the byte g would wrap). template <uint8_t W, uint8_t H, uint16_t HC> class AStar { public: static const uint16_t CELLS = (uint16_t)W * H; uint16_t expanded() const { return expanded_; } uint16_t max_open() const { return maxh_; } template <class Map> int16_t plan(const Map& m, uint8_t sx, uint8_t sy, uint8_t gx, uint8_t gy, uint16_t* path, uint16_t path_cap, uint8_t wq = 4) { closed_.clear(); expanded_ = 0; maxh_ = 0; n_ = 0; for (uint16_t i = 0; i < CELLS; ++i) g_[i] = 255; if (m.blocked(sx, sy) || m.blocked(gx, gy)) return -1; uint16_t start = (uint16_t)sy * W + sx, goal = (uint16_t)gy * W + gx; g_[start] = 0; push(f_of(0, sx, sy, gx, gy, wq), start); while (n_) { uint16_t c = pop(); uint8_t cx = (uint8_t)(c % W), cy = (uint8_t)(c / W); if (closed_.get(cx, cy)) continue; // a stale duplicate: this cell was already finished closed_.set(cx, cy, true); ++expanded_; if (c == goal) return trace(start, goal, path, path_cap); for (uint8_t d = 0; d < 4; ++d) { int16_t nx = cx + dx4(d), ny = cy + dy4(d); if (m.blocked(nx, ny) || closed_.get((uint8_t)nx, (uint8_t)ny)) continue; uint16_t ni = (uint16_t)ny * W + nx; if (g_[c] >= 254) return -3; uint8_t ng = (uint8_t)(g_[c] + 1); if (ng >= g_[ni]) continue; g_[ni] = ng; set_dir(ni, d); if (n_ >= HC) return -2; push(f_of(ng, (uint8_t)nx, (uint8_t)ny, gx, gy, wq), ni); } } return -1; } private: struct E { uint16_t f, idx; }; static uint16_t f_of(uint8_t g, uint8_t x, uint8_t y, uint8_t gx, uint8_t gy, uint8_t wq) { uint16_t h = (uint16_t)((x > gx ? x - gx : gx - x) + (y > gy ? y - gy : gy - y)); return (uint16_t)(4u * g + (uint16_t)wq * h); } void push(uint16_t f, uint16_t idx) { uint16_t i = n_++; h_[i].f = f; h_[i].idx = idx; while (i && h_[(i - 1) / 2].f > h_[i].f) { E t = h_[i]; h_[i] = h_[(i - 1) / 2]; h_[(i - 1) / 2] = t; i = (uint16_t)((i - 1) / 2); } if (n_ > maxh_) maxh_ = n_; } uint16_t pop() { uint16_t top = h_[0].idx; h_[0] = h_[--n_]; uint16_t i = 0; for (;;) { uint16_t l = (uint16_t)(2 * i + 1), r = (uint16_t)(2 * i + 2), s = i; if (l < n_ && h_[l].f < h_[s].f) s = l; if (r < n_ && h_[r].f < h_[s].f) s = r; if (s == i) break; E t = h_[i]; h_[i] = h_[s]; h_[s] = t; i = s; } return top; } void set_dir(uint16_t i, uint8_t d) { uint8_t s = (uint8_t)((i & 3) * 2); dir_[i >> 2] = (uint8_t)((dir_[i >> 2] & ~(3u << s)) | ((uint32_t)d << s)); } uint8_t get_dir(uint16_t i) const { return (dir_[i >> 2] >> ((i & 3) * 2)) & 3; } int16_t trace(uint16_t start, uint16_t goal, uint16_t* path, uint16_t cap) const { uint16_t n = 0, c = goal; while (c != start) { ++n; uint8_t d = get_dir(c); c = (uint16_t)((int16_t)c - dx4(d) - (int16_t)W * dy4(d)); } if (n + 1 > cap) return -2; c = goal; for (int16_t k = (int16_t)n; k >= 0; --k) { path[k] = c; if (k) { uint8_t d = get_dir(c); c = (uint16_t)((int16_t)c - dx4(d) - (int16_t)W * dy4(d)); } } return (int16_t)n; } BitGrid<W, H> closed_; uint8_t g_[CELLS]; uint8_t dir_[(CELLS + 3) / 4]; E h_[HC]; uint16_t n_, expanded_, maxh_; }; // ---- 4. path smoothing by line of sight: keep a waypoint only where the straight line to the next kept one would hit something ---- // in: `cells` (n cell numbers). out: waypoints in the same array (compacted); returns the new count. template <class Map> inline uint16_t shortcut(const Map& m, uint16_t* cells, uint16_t n, uint8_t W) { if (n < 3) return n; uint16_t out = 1, i = 0; while (i < n - 1) { uint16_t j = (uint16_t)(n - 1); while (j > i + 1 && !line_clear(m, (int16_t)(cells[i] % W), (int16_t)(cells[i] / W), (int16_t)(cells[j] % W), (int16_t)(cells[j] / W))) --j; cells[out++] = cells[j]; i = j; } return out; } // ---- 5. pure pursuit: aim at the point on the path one lookahead distance ahead, and steer along the circle through it ---- struct Pt { float x, y; }; class PurePursuit { public: PurePursuit(float lookahead_m, float v_mps, float track_m, float goal_tol_m) : L_(lookahead_m), v_(v_mps), track_(track_m), tol_(goal_tol_m), idx_(0), done_(false) {} bool done() const { return done_; } float target_x() const { return tx_; } float target_y() const { return ty_; } Cmd update(float x, float y, float th, const Pt* path, uint8_t n) { Cmd stop = {0.0f, 0.0f}; float gdx = path[n - 1].x - x, gdy = path[n - 1].y - y, gd = sqrtf(gdx * gdx + gdy * gdy); if (gd < tol_) { done_ = true; return stop; } while (idx_ + 2 < n && seg_d2(path[idx_ + 1], path[idx_ + 2], x, y) <= seg_d2(path[idx_], path[idx_ + 1], x, y)) ++idx_; // the SEGMENT the robot is nearest to (not the nearest waypoint) if (gd <= L_) { tx_ = path[n - 1].x; ty_ = path[n - 1].y; } // the goal is inside the circle: aim at it else { tx_ = path[idx_ + 1].x; ty_ = path[idx_ + 1].y; // fallback (off the path by more than L): the next waypoint for (uint8_t k = idx_; k + 1 < n; ++k) { // first segment, from the one we are on, that reaches the circle of radius L float ax = path[k].x - x, ay = path[k].y - y, bx = path[k + 1].x - x, by = path[k + 1].y - y; if (bx * bx + by * by <= L_ * L_) continue; // this segment ends inside the circle: look further on float dx = bx - ax, dy = by - ay, a = dx * dx + dy * dy, b = 2 * (ax * dx + ay * dy), c = ax * ax + ay * ay - L_ * L_; float disc = b * b - 4 * a * c; if (disc < 0) continue; float t = (-b + sqrtf(disc)) / (2 * a); // the far crossing of the circle if (t < 0 || t > 1) continue; tx_ = path[k].x + t * dx; ty_ = path[k].y + t * dy; break; } } float ang = atan2f(ty_ - y, tx_ - x) - th; while (ang > 3.14159265f) ang -= 6.2831853f; while (ang < -3.14159265f) ang += 6.2831853f; if (ang > 1.2f || ang < -1.2f) return spin(ang > 0 ? 1.5f : -1.5f, track_); // pointing the wrong way: turn first float dx = tx_ - x, dy = ty_ - y, d = sqrtf(dx * dx + dy * dy); if (d < 0.02f) d = 0.02f; float curv = 2.0f * sinf(ang) / d; float v = v_; if (gd < 0.3f) { float vs = 0.05f + 0.8f * gd; if (vs < v) v = vs; } // slow down for the goal return arc(v, v * curv, track_); } private: static float dist2(const Pt& p, float x, float y) { return (p.x - x) * (p.x - x) + (p.y - y) * (p.y - y); } static float seg_d2(const Pt& a, const Pt& b, float x, float y) { float dx = b.x - a.x, dy = b.y - a.y, l2 = dx * dx + dy * dy, t = l2 > 0 ? ((x - a.x) * dx + (y - a.y) * dy) / l2 : 0.0f; if (t < 0) t = 0; else if (t > 1) t = 1; float qx = a.x + t * dx - x, qy = a.y + t * dy - y; return qx * qx + qy * qy; } float L_, v_, track_, tol_, tx_ = 0, ty_ = 0; uint8_t idx_; bool done_; };

Building the map from range readings

A map is rarely typed in; it is built from sensor readings, which are wrong in two ways: the noise moves a hit into a neighbouring cell, and a “ghost” echo (a reading that is too short) marks a cell occupied where nothing is. The experiment scans the test world (four boxes, 158 cells occupied counting the 96 of the outer ring that stands for the arena wall) from eight positions with a sensor that turns through 360°, a reading every degree, 5 mm of noise, 2 % dropouts and ghosts at 0, 1 and 3 %, and keeps each cell in one of three ways: 1 bit (occupied once any reading ends there); a 2-bit hit counter (occupied when it reaches 2); an 8-bit score (+3 for a hit, −1 each time a ray passes through the cell, occupied while above 0). It is scored by the cells wrong in each direction and then by what matters: does the planner find a path on the map, with and without inflating it by one cell?

// world.h -- the chapter's test world (HOST ONLY): the 3 x 2 m arena of the simulator with four box obstacles, a 10 cm grid of it (30 x 20 cells), and a ray caster for the map-building experiment. #pragma once #include <math.h> #include <stdint.h> #include "grid.h" #include "sim.h" struct Box { double x0, y0, x1, y1; }; static const Box BOXES[4] = { {0.8, 0.0, 1.0, 1.2}, // a wall stub rising from the bottom edge {1.8, 0.8, 2.0, 2.0}, // a wall hanging from the top edge {1.4, 1.4, 1.7, 1.7}, // a block (0.4 m from the stub: wide enough to pass after inflation) {2.4, 1.2, 2.7, 1.5}, // a block }; typedef BitGrid<30, 20> World; static const double CELL = 0.1; inline bool in_box(double x, double y) { for (const Box& b : BOXES) if (x >= b.x0 && x <= b.x1 && y >= b.y0 && y <= b.y1) return true; return false; } // the truth grid: a cell is occupied if any box overlaps it, or if it is in the outermost ring (the wall) inline void truth_grid(World& w) { w.clear(); for (uint8_t y = 0; y < 20; ++y) for (uint8_t x = 0; x < 30; ++x) { double cx0 = x * CELL, cy0 = y * CELL, cx1 = cx0 + CELL, cy1 = cy0 + CELL; for (const Box& b : BOXES) if (b.x0 < cx1 - 1e-9 && b.x1 > cx0 + 1e-9 && b.y0 < cy1 - 1e-9 && b.y1 > cy0 + 1e-9) w.set(x, y, true); } for (uint8_t x = 0; x < 30; ++x) { w.set(x, 0, true); w.set(x, 19, true); } // the arena walls: the outermost ring of cells counts as occupied for (uint8_t y = 0; y < 20; ++y) { w.set(0, y, true); w.set(29, y, true); } } // distance along a ray from (px, py) at angle `ang` to the nearest box or arena wall inline double cast(double px, double py, double ang) { double dx = cos(ang), dy = sin(ang), best = 1e9; if (dx > 1e-12) best = fmin(best, (3.0 - px) / dx); else if (dx < -1e-12) best = fmin(best, (0.0 - px) / dx); if (dy > 1e-12) best = fmin(best, (2.0 - py) / dy); else if (dy < -1e-12) best = fmin(best, (0.0 - py) / dy); for (const Box& b : BOXES) { double t0 = 0, t1 = 1e9; double lo[2] = {b.x0, b.y0}, hi[2] = {b.x1, b.y1}, o[2] = {px, py}, d[2] = {dx, dy}; bool hit = true; for (int i = 0; i < 2; ++i) { if (fabs(d[i]) < 1e-12) { if (o[i] < lo[i] || o[i] > hi[i]) hit = false; } else { double a = (lo[i] - o[i]) / d[i], c = (hi[i] - o[i]) / d[i]; if (a > c) { double t = a; a = c; c = t; } if (a > t0) t0 = a; if (c < t1) t1 = c; } } if (hit && t0 <= t1 && t0 > 0) best = fmin(best, t0); } return best; }
// e_map.cpp -- building an occupancy grid from range readings, with three ways of remembering (host build; the sensor is the simulator's, ASSUMED, not measured). // Eight scan positions in free space; at each, a sensor that turns through 360 degrees takes a reading every 1 degree (2880 rays in all), each with 5 mm of noise, 2 % dropouts and "ghost" echoes // (a reading that is too short, uniformly between 0.1 m and the true distance) at a chosen rate. The grid is 30 x 20 cells of 10 cm. Three ways to keep a cell: // 1 bit occupied as soon as ONE reading ends in the cell. Never cleared. (75 bytes) // 2 bits a hit counter 0..3 per cell; occupied when it reaches 2. (150 bytes) // 8 bits a score per cell: +3 for a hit, -1 for each free cell a ray passes through, kept between -20 and +20; occupied when above 0. (600 bytes) // Scored against the true grid: cells wrongly occupied and cells wrongly free, mean over 20 seeded runs; then whether a planner (BFS, from (0.3, 0.3) to (2.7, 1.7)) finds a path on the map, with and without inflating it by 1 cell, and whether that path crosses a cell that is truly occupied. #include <cstdio> #include <cmath> #include <initializer_list> #include "world.h" struct Pose2 { double x, y; }; static const Pose2 SCAN[8] = {{0.4, 0.4}, {0.4, 1.6}, {1.4, 0.5}, {1.2, 1.1}, {1.6, 1.9}, {2.2, 0.5}, {2.6, 0.7}, {2.7, 1.7}}; struct Score { double wrong_occ, wrong_free, ok1, hit1, ok0, hit0; }; static Score run(int mode, double ghost, int seeds) { Score s = {0, 0, 0, 0, 0, 0}; World truth; truth_grid(truth); for (int seed = 1; seed <= seeds; ++seed) { Rng rng((uint32_t)seed * 40503u + 99u); int8_t score[600] = {0}; uint8_t hits[600] = {0}; World bit; for (const Pose2& p : SCAN) { for (int deg = 0; deg < 360; ++deg) { double ang = deg * SIM_PI / 180.0, d = cast(p.x, p.y, ang); if (rng.uniform() < 0.02) continue; // dropout double r = d + 0.005 * rng.normal(); if (rng.uniform() < ghost) r = 0.1 + rng.uniform() * (d - 0.1 > 0 ? d - 0.1 : 0.0); // a ghost echo if (r < 0.05) continue; for (double t = 0.0; t < r - 0.05; t += 0.05) { // cells the ray passes through: free int cx = (int)((p.x + t * cos(ang)) / CELL), cy = (int)((p.y + t * sin(ang)) / CELL); if (cx >= 0 && cx < 30 && cy >= 0 && cy < 20) { int8_t& q = score[cy * 30 + cx]; if (q > -20) --q; } } int hx = (int)((p.x + r * cos(ang)) / CELL), hy = (int)((p.y + r * sin(ang)) / CELL); if (hx >= 0 && hx < 30 && hy >= 0 && hy < 20 && r < d + 0.2) { // a hit (a reading that ends at or before the true wall) int i = hy * 30 + hx; bit.set((uint8_t)hx, (uint8_t)hy, true); if (hits[i] < 3) ++hits[i]; if (score[i] <= 17) score[i] += 3; else score[i] = 20; } } } World map; for (uint8_t y = 0; y < 20; ++y) for (uint8_t x = 0; x < 30; ++x) { bool occ = mode == 0 ? bit.get(x, y) : mode == 1 ? hits[y * 30 + x] >= 2 : score[y * 30 + x] > 0; map.set(x, y, occ); if (occ && !truth.get(x, y)) s.wrong_occ += 1; if (!occ && truth.get(x, y)) s.wrong_free += 1; } for (int infl = 1; infl >= 0; --infl) { World inf; inflate(map, inf, (uint8_t)infl); static Bfs<30, 20, 600> bfs; uint16_t path[600]; int16_t n = bfs.plan(inf, 3, 3, 27, 17, path, 600); if (n >= 0) { bool hit = false; for (int k = 0; k <= n; ++k) if (truth.get((uint8_t)(path[k] % 30), (uint8_t)(path[k] / 30))) hit = true; (infl ? s.ok1 : s.ok0) += 1; if (hit) (infl ? s.hit1 : s.hit0) += 1; } } } s.wrong_occ /= seeds; s.wrong_free /= seeds; s.ok1 = 100.0 * s.ok1 / seeds; s.hit1 = 100.0 * s.hit1 / seeds; s.ok0 = 100.0 * s.ok0 / seeds; s.hit0 = 100.0 * s.hit0 / seeds; return s; } int main() { World truth; truth_grid(truth); int occ = 0; for (uint8_t y = 0; y < 20; ++y) for (uint8_t x = 0; x < 30; ++x) occ += truth.get(x, y); std::printf("occupancy grid from 8 scans of 360 rays; the true grid has %d occupied cells of 600 (the outer ring of cells is the arena wall)\n", occ); std::printf(" planner on the map inflated by 1 cell planner on the map as it is (no inflation)\n"); std::printf(" ghost echoes memory wrongly occupied wrongly free path found (%%) path crosses a true obstacle (%%) path found (%%) path crosses a true obstacle (%%)\n"); const char* names[3] = {"1 bit ", "2-bit count", "8-bit score"}; const int bytes[3] = {75, 150, 600}; for (double g : {0.0, 0.01, 0.03}) for (int mode = 0; mode < 3; ++mode) { Score s = run(mode, g, 20); std::printf(" %10.0f %% %s %4d B %16.1f %12.1f %13.0f %31.0f %13.0f %31.0f\n", g * 100, names[mode], bytes[mode], s.wrong_occ, s.wrong_free, s.ok1, s.hit1, s.ok0, s.hit0); } return 0; }
occupancy grid from 8 scans of 360 rays; the true grid has 158 occupied cells of 600 (the outer ring of cells is the arena wall) planner on the map inflated by 1 cell planner on the map as it is (no inflation) ghost echoes memory wrongly occupied wrongly free path found (%) path crosses a true obstacle (%) path found (%) path crosses a true obstacle (%) 0 % 1 bit 75 B 67.8 4.4 0 0 100 0 0 % 2-bit count 150 B 62.8 5.3 0 0 100 0 0 % 8-bit score 600 B 15.5 35.1 100 0 100 0 1 % 1 bit 75 B 84.5 4.3 0 0 100 0 1 % 2-bit count 150 B 63.5 5.3 0 0 100 0 1 % 8-bit score 600 B 16.1 35.1 100 0 100 0 3 % 1 bit 75 B 117.0 4.2 0 0 60 0 3 % 2-bit count 150 B 67.2 5.2 0 0 100 0 3 % 8-bit score 600 B 15.2 35.3 100 0 100 0

The cell counts are not the interesting column: with the world’s edges aligned to cell borders, noise puts hits on both sides of every edge, and the 1-bit and 2-bit maps have 63 to 117 cells wrongly occupied against 15 for the 8-bit score. The planner column shows what that costs. With the map inflated by one cell (the safe thing to do) the 1-bit and 2-bit maps leave no path at all, in every run at every ghost rate: each obstacle has swollen by about a cell, inflation adds another, and the 0.4 m gap the route must go through is closed. Only the 8-bit score keeps it, because a cell that rays pass through often is cleared again. Without inflation the 1-bit map finds a path in all runs at 0 and 1 % ghosts and in only 60 % at 3 %, where phantom cells sit across the corridor. No planned path went through a truly occupied cell on any map; the 8-bit map has 35 cells wrongly free (thin obstacles thinned by the passing rays: I did not check which cells), and none of them mattered here. So a bit is enough to store a map and not always enough to build one: 75 bytes against 600 is what a map that can forget costs. A common compromise is to build with scores (or in a reduced area) and keep only the thresholded bit grid for planning.

3. Breadth-first search and A*

Breadth-first search (BFS) explores the cells in rings of equal distance from the start, so the first time it reaches the goal the path is the shortest. It needs a queue of cells waiting to be explored, a bit per cell for “seen” and two bits per cell for how it got there. A* explores the cell with the lowest f = g + h, where g is the steps taken so far and h a guess of the steps to go (here the Manhattan distance, which never over-estimates on a 4-connected grid, so A* is still optimal). It explores fewer cells but needs more memory: a priority queue (a binary heap), a closed bit and a byte of g per cell, and the arrival direction. In the code, an entry of the heap is 4 bytes, and a cell can be pushed again when a better route to it is found.

The experiment compares them on 300 random 32 × 32 grids per obstacle density, start at one corner and goal at the other:

// e_plan.cpp -- breadth-first search against A* on random 32 x 32 grids (host build; seeded; nothing here ran on a board). // 300 grids per obstacle density, start (0, 0), goal (31, 31) (both kept free). Compared: whether both find a path, whether the paths are equally long (the grid is 4-connected with equal steps, so // both are optimal and must agree), cells expanded, and the biggest queue / open list each needed. Then the capacity question: what if the queue or heap is too small? #include <cstdio> #include <cstring> #include <initializer_list> #include "sim.h" #include "grid.h" typedef BitGrid<32, 32> Map; static void random_map(Map& m, double density, uint32_t seed) { Rng rng(seed * 2654435761u + 17u); m.clear(); for (uint8_t y = 0; y < 32; ++y) for (uint8_t x = 0; x < 32; ++x) if (rng.uniform() < density) m.set(x, y, true); m.set(0, 0, false); m.set(31, 31, false); } template <uint16_t Q, uint16_t HC> struct Planners { Bfs<32, 32, Q> bfs; AStar<32, 32, HC> as; }; static Planners<1024, 1024> P; // big enough that capacity never matters in the main table int main() { std::printf("breadth-first search against A* (Manhattan heuristic), 32 x 32 grid, 4-connected, 300 random grids per row\n"); std::printf(" obstacle density solvable same path length mean steps BFS expanded A* expanded A* / BFS BFS max queue A* max open\n"); for (double dens : {0.10, 0.20, 0.30, 0.35}) { int solv = 0, same = 0; double steps = 0, eb = 0, ea = 0; uint16_t qmax = 0, hmax = 0; for (int seed = 1; seed <= 300; ++seed) { Map m; random_map(m, dens, (uint32_t)seed); uint16_t pb[1024], pa[1024]; int16_t rb = P.bfs.plan(m, 0, 0, 31, 31, pb, 1024), ra = P.as.plan(m, 0, 0, 31, 31, pa, 1024); if (rb >= 0 && ra >= 0) { ++solv; if (rb == ra) ++same; steps += rb; eb += P.bfs.expanded(); ea += P.as.expanded(); if (P.bfs.max_frontier() > qmax) qmax = P.bfs.max_frontier(); if (P.as.max_open() > hmax) hmax = P.as.max_open(); } else if ((rb >= 0) != (ra >= 0)) std::printf(" DISAGREE on solvability, seed %d\n", seed); } std::printf(" %15.0f %% %8d %16d %10.1f %12.1f %11.1f %8.2f %13u %11u\n", dens * 100, solv, same, steps / solv, eb / solv, ea / solv, ea / eb, qmax, hmax); } std::printf("\ncapacity: the same 300 grids at 20 %% density, planners with a SMALL queue (BFS) or heap (A*): how many searches are abandoned?\n"); std::printf(" capacity (entries) BFS abandoned A* abandoned\n"); static Bfs<32, 32, 32> b32; static Bfs<32, 32, 64> b64; static Bfs<32, 32, 128> b128; static AStar<32, 32, 32> a32; static AStar<32, 32, 64> a64; static AStar<32, 32, 128> a128; int ab[3] = {0, 0, 0}, aa[3] = {0, 0, 0}; for (int seed = 1; seed <= 300; ++seed) { Map m; random_map(m, 0.20, (uint32_t)seed); uint16_t pt[1024]; if (P.bfs.plan(m, 0, 0, 31, 31, pt, 1024) < 0) continue; // only grids that have a path if (b32.plan(m, 0, 0, 31, 31, pt, 1024) == -2) ++ab[0]; if (b64.plan(m, 0, 0, 31, 31, pt, 1024) == -2) ++ab[1]; if (b128.plan(m, 0, 0, 31, 31, pt, 1024) == -2) ++ab[2]; if (a32.plan(m, 0, 0, 31, 31, pt, 1024) == -2) ++aa[0]; if (a64.plan(m, 0, 0, 31, 31, pt, 1024) == -2) ++aa[1]; if (a128.plan(m, 0, 0, 31, 31, pt, 1024) == -2) ++aa[2]; } const int caps[3] = {32, 64, 128}; for (int i = 0; i < 3; ++i) std::printf(" %18d %13d %12d\n", caps[i], ab[i], aa[i]); return 0; }
breadth-first search against A* (Manhattan heuristic), 32 x 32 grid, 4-connected, 300 random grids per row obstacle density solvable same path length mean steps BFS expanded A* expanded A* / BFS BFS max queue A* max open 10 % 292 292 62.0 920.0 407.0 0.44 38 275 20 % 248 248 62.0 816.2 317.9 0.39 40 177 30 % 152 152 63.6 682.6 282.4 0.41 39 122 35 % 71 71 67.9 583.5 277.1 0.47 36 81 capacity: the same 300 grids at 20 % density, planners with a SMALL queue (BFS) or heap (A*): how many searches are abandoned? capacity (entries) BFS abandoned A* abandoned 32 121 248 64 0 247 128 0 70

First, they agree: on every solvable grid (292, 248, 152 and 71 of 300 as the density rises) BFS and A* find paths of exactly the same length, and agree on which grids have no path. That is the test of the code as much as of the algorithms: two different implementations that must give the same answer. Second, A* expands 0.39 to 0.47 times as many cells as BFS (407 against 920 at 10 % obstacles). Third, and this is the table that decides the design: the memory goes the other way. The biggest queue BFS ever needed was 36 to 40 cells (2 bytes each: 80 bytes), while the biggest open list A* needed was 275 entries at 10 % obstacles (4 bytes each: about 1100 bytes). A* explores fewer cells but holds many more of them, because it pushes duplicates, and its heap is the largest array in the planner.

The second table asks what happens when the queue or the heap is too small: the planner stops with an error code, rather than writing past the end of its array. A BFS queue of 32 entries abandoned 121 of the searches; 64 entries abandoned none. A* with a heap of 32 abandoned 248, 64 abandoned 247, and even 128 abandoned 70 of the roughly 248 solvable grids. Choosing HC is the programmer’s job and the test is to measure it, as above; the safe choice is the largest ever seen plus a margin, and the error code is the net under it.

4. What fits in 2048 bytes

The sizes follow from the arrays. BFS needs the seen bits (cells/8 bytes), 2 bits per cell (cells/4) and 2 bytes per queue entry. A* needs the closed bits, one byte per cell for g, 2 bits per cell, and 4 bytes per heap entry. The experiment below applies them to the test world (the 30 × 20 grid inflated by one cell, from cell (3, 3) to (27, 17)) and to several grid sizes, with the queue and heap sized from the largest ever needed on 100 random grids at 10 % obstacles plus 25 %, and a budget of 1500 bytes for map, planner and path buffer (chapter 8’s sketch already uses 327 of the 2048):

// e_budget.cpp -- what do the planners cost in RAM, and what fits on an Uno? (host build; the byte counts are the real sizes of the real classes on the PC; the Uno pads nothing, so a class can be a byte smaller there) // Part 1: the chapter's world (30 x 20 cells, four boxes, inflated by one cell), start (3, 3), goal (27, 17): steps, cells expanded and the biggest queue / open list, for BFS, A*, weighted A* and A* with no heuristic. // Part 2: for several grid sizes, the RAM the planner and the map need. The queue and heap sizes are the largest ever needed on 100 random grids at 10 % obstacles, plus 25 %. // RAM = map + planner + a path buffer of 2 x 2(W+H) bytes. "fits" means at most 1500 bytes: an Uno has 2048, and chapter 8's sketch already uses 327 of them before any planner. #include <cstdio> #include <cmath> #include <initializer_list> #include "world.h" template <uint8_t W, uint8_t H> struct Stat { uint16_t q, h; }; template <uint8_t W, uint8_t H> static Stat<W, H> measure() { static Bfs<W, H, (uint16_t)(W * H)> bfs; static AStar<W, H, (uint16_t)(W * H * 3 / 2 > 4000 ? 4000 : W * H * 3 / 2)> as; static uint16_t path[W * H]; Stat<W, H> s = {0, 0}; for (int seed = 1; seed <= 100; ++seed) { BitGrid<W, H> m; Rng rng((uint32_t)seed * 2654435761u + 17u); for (uint8_t y = 0; y < H; ++y) for (uint8_t x = 0; x < W; ++x) if (rng.uniform() < 0.10) m.set(x, y, true); m.set(0, 0, false); m.set(W - 1, H - 1, false); int16_t rb = bfs.plan(m, 0, 0, W - 1, H - 1, path, W * H), ra = as.plan(m, 0, 0, W - 1, H - 1, path, W * H); if (rb >= 0 && ra >= 0) { if (bfs.max_frontier() > s.q) s.q = bfs.max_frontier(); if (as.max_open() > s.h) s.h = as.max_open(); } } return s; } template <uint8_t W, uint8_t H> static void row() { Stat<W, H> s = measure<W, H>(); uint16_t cells = (uint16_t)(W * H), q = (uint16_t)std::ceil(s.q * 1.25), hc = (uint16_t)std::ceil(s.h * 1.25); uint16_t mapb = (uint16_t)((cells + 7) / 8), pathb = (uint16_t)(2 * 2 * (W + H)); uint16_t bfs = (uint16_t)(mapb + (cells + 3) / 4 + 2 * q + 4), as = (uint16_t)(mapb + cells + (cells + 3) / 4 + 4 * hc + 6); uint16_t tb = (uint16_t)(mapb + bfs + pathb), ta = (uint16_t)(mapb + as + pathb); std::printf(" %2d x %-2d %5u %5u %4u / %-4u %5u B %5u B %-4s %5u B %-4s\n", W, H, cells, mapb, q, hc, bfs, as, tb <= 1500 ? "fits" : "no", ta, ta <= 1500 ? "fits" : "no"); } int main() { World truth; truth_grid(truth); World inf; inflate(truth, inf, 1); static Bfs<30, 20, 600> bfs; static AStar<30, 20, 600> as; uint16_t path[600]; std::printf("the chapter's world, inflated by 1 cell, from cell (3, 3) to (27, 17)\n"); std::printf(" planner steps cells expanded biggest queue / open list\n"); int16_t n = bfs.plan(inf, 3, 3, 27, 17, path, 600); std::printf(" BFS %5d %14u %25u\n", n, bfs.expanded(), bfs.max_frontier()); for (int wq : {4, 8, 0}) { n = as.plan(inf, 3, 3, 27, 17, path, 600, (uint8_t)wq); std::printf(" A* (h weight %d/4) %5d %14u %25u\n", wq, n, as.expanded(), as.max_open()); } std::printf("\nRAM for the planners (bytes), by grid size\n"); std::printf(" grid cells map B Q / HC BFS RAM A* RAM BFS total A* total\n"); row<16, 16>(); row<24, 24>(); row<30, 20>(); row<32, 32>(); row<40, 40>(); row<64, 64>(); std::printf("\nchecks: sizeof(Bfs<32,32,64>) = %u (formula %u); sizeof(AStar<32,32,300>) = %u (formula %u)\n", (unsigned)sizeof(Bfs<32, 32, 64>), 128u + 256u + 128u + 4u, (unsigned)sizeof(AStar<32, 32, 300>), 128u + 1024u + 256u + 1200u + 6u); return 0; }
the chapter's world, inflated by 1 cell, from cell (3, 3) to (27, 17) planner steps cells expanded biggest queue / open list BFS 52 281 12 A* (h weight 4/4) 52 212 47 A* (h weight 8/4) 54 173 59 A* (h weight 0/4) 52 283 14 RAM for the planners (bytes), by grid size grid cells map B Q / HC BFS RAM A* RAM BFS total A* total 16 x 16 256 32 27 / 97 154 B 746 B fits 906 B fits 24 x 24 576 72 35 / 190 290 B 1558 B fits 1822 B no 30 x 20 600 75 33 / 192 295 B 1599 B fits 1874 B no 32 x 32 1024 128 47 / 320 482 B 2694 B fits 3078 B no 40 x 40 1600 200 58 / 473 720 B 4098 B fits 4618 B no 64 x 64 4096 512 90 / 1123 1720 B 10130 B no 11154 B no checks: sizeof(Bfs<32,32,64>) = 516 (formula 516); sizeof(AStar<32,32,300>) = 2614 (formula 2614)

On the test world BFS expands 281 cells, A* 212, A* with a heuristic weighted 2 (wq = 8, so h counts double) 173 cells, but with a path of 54 steps instead of 52; and A* without a heuristic expands 283, as BFS does. The table by size is the real message. BFS fits up to 40 × 40 cells (720 bytes for the planner) and is out of budget at 64 × 64 (1720). A* fits only at 16 × 16: at 24 × 24 it needs 1558 bytes for the planner alone and at 30 × 20 1599, almost all of it the one-byte-per-cell g array and the heap. The two closing checks show the formulas are exact: sizeof of the real classes (measured on the PC, which pads a class to an even size; the Uno does not) gives 516 and 2614 bytes, the formulas’ 516 and 2614.

The same planners were compiled into a sketch for the Uno, to see what the compiler says. The first row has no planner (it has Serial, which takes 188 bytes of RAM by itself). The two 30 × 20 rows keep the map in flash, so it costs no RAM:

VariantFlash (bytes)RAM (bytes)RAM left
no planner (baseline, Serial only)17101881860
BFS 30 × 20, queue of 40, map in flash29906971351
A* 30 × 20, heap of 192, map in flash3582198761
A* 16 × 16, heap of 97, map in RAM34701166882

The A* on the test world compiles and links without a warning, and leaves 61 bytes for the stack and everything else. The compiler does not know the stack’s depth, so it reports a success for a program that will, sooner or later, overwrite its own variables. This is the point of working out the budget first. The planner’s own symbol, read with avr-nm, is 0x63F = 1599 bytes, exactly the formula’s figure for A* on 30 × 20 with a heap of 192:

avr-nm --size-sort -S -C b_p2/s_plan.ino.elf (variant 2: A* on 30 x 20, map in flash), RAM symbols (b = zero-initialised, d = initialised data), size in hex bytes 008001df 00000004 b timer0_millis 008001e3 00000004 b timer0_overflow_count 00800100 00000012 d vtable for HardwareSerial 008001e7 0000009d b Serial 00800116 000000c8 b path 00800284 0000063f b planner

My first build of this sketch said 705, 1995 and 1174 bytes, 8 more in each than the formula, and the formula was exact for the planner and the path buffer. avr-nm found the 8 bytes: the four-neighbour offsets, written as static const int8_t DX4[4], DY4[4]. On an AVR a const array is not in flash; it is a variable in RAM that is initialised from flash at start-up, which is why PROGMEM exists. I replaced the tables by two tiny functions (dx4() and dy4()), and the RAM fell to 697, 1987 and 1166, exactly the predicted figures; the flash grew by two bytes. Challenge 1 asks you to predict these before compiling.

5. Smoothing, and following the path

The grid path is a staircase of 52 steps. A robot could follow the cell centres, but it would turn at every corner, and the path is longer than it needs to be. Line-of-sight smoothing keeps a waypoint only where the straight line to the next kept waypoint would cross a blocked cell: the 53 cells become 7 waypoints and the path 4.76 m instead of 5.20 m. Pure pursuit follows a path by always steering toward the point on it one lookahead distance ahead, along the circle that passes through that point: a curvature of 2 sin α / d, where α is the angle between the heading and the target and d the distance to it, and a turn rate of speed times curvature. A short lookahead hugs the path and wobbles; a long one is smooth and cuts corners. The experiment drives the planned path at 0.25 m/s on the chapter-3 simulator with an assumed 1 cm and 1° of localisation error, for five lookaheads, on the raw staircase and on the smoothed path:

// e_pursuit.cpp -- following a planned path with pure pursuit, for several lookahead distances, on the raw grid path and on the line-of-sight smoothed path (host build). // World: world.h (30 x 20 cells of 10 cm, four boxes). The path is A* on the TRUE grid inflated by 1 cell, from (0.35, 0.35) to (2.75, 1.75). The robot is the chapter-3 simulator (0.1 s motor lag), // 0.25 m/s; its pose comes from the simulator PLUS an assumed localisation error (1 cm in x and y, 1 degree in heading, new every 20 ms control step), 20 seeds per row. // Scored: reached the goal within 60 s (%), time (s), the true distance of the robot from the path it follows (rms, mm), the smallest distance from the robot's centre to any obstacle (mm), // and collisions (the centre closer than 75 mm, the robot's radius, to a box or a wall: runs with at least one, %). #include <cstdio> #include <cmath> #include <initializer_list> #include "world.h" static double seg_dist(double px, double py, const Pt& a, const Pt& b) { double dx = b.x - a.x, dy = b.y - a.y, l2 = dx * dx + dy * dy, t = l2 > 0 ? ((px - a.x) * dx + (py - a.y) * dy) / l2 : 0; if (t < 0) t = 0; if (t > 1) t = 1; double qx = a.x + t * dx, qy = a.y + t * dy; return std::hypot(px - qx, py - qy); } static double clearance(double x, double y) { // distance from the centre to the nearest box or wall double best = std::fmin(std::fmin(x, 3.0 - x), std::fmin(y, 2.0 - y)); for (const Box& b : BOXES) { double dx = std::fmax(std::fmax(b.x0 - x, 0.0), x - b.x1), dy = std::fmax(std::fmax(b.y0 - y, 0.0), y - b.y1); best = std::fmin(best, std::hypot(dx, dy)); } return best; } struct R { double reached, time, xtrack, clear, crash; }; static R run(float lookahead, bool smooth, int seeds) { World truth; truth_grid(truth); World inf; inflate(truth, inf, 1); static AStar<30, 20, 300> as; uint16_t cells[600]; int16_t n = as.plan(inf, 3, 3, 27, 17, cells, 600); if (n < 0) { std::printf("no path\n"); R z = {0, 0, 0, 0, 0}; return z; } uint16_t m = (uint16_t)(n + 1); if (smooth) m = shortcut(inf, cells, m, 30); Pt path[64]; for (uint16_t i = 0; i < m && i < 64; ++i) { path[i].x = ((cells[i] % 30) + 0.5f) * 0.1f; path[i].y = ((cells[i] / 30) + 0.5f) * 0.1f; } R r = {0, 0, 0, 0, 0}; double sq = 0; long cnt = 0; double clr = 0; for (int seed = 1; seed <= seeds; ++seed) { Rng rng((uint32_t)seed * 31337u); RobotParams rp; rp.tau = 0.1; SimHW w(rp, SensorParams(), Arena(), (uint32_t)seed); w.x = path[0].x; w.y = path[0].y; w.th = 0.0; PurePursuit pp(lookahead, 0.25f, 0.15f, 0.06f); double minclr = 9.0; bool crashed = false; int tick = 0; for (; tick < 3000 && !pp.done(); ++tick) { float ex = (float)(w.x + 0.01 * rng.normal()), ey = (float)(w.y + 0.01 * rng.normal()), eth = (float)(w.th + 0.01745 * rng.normal()); Cmd c = pp.update(ex, ey, eth, path, (uint8_t)m); w.drive(c.vl, c.vr); for (int k = 0; k < 20; ++k) w.step(0.001); double d = 1e9; for (uint16_t i = 0; i + 1 < m; ++i) d = std::fmin(d, seg_dist(w.x, w.y, path[i], path[i + 1])); sq += d * d; ++cnt; double cl = clearance(w.x, w.y); if (cl < minclr) minclr = cl; if (cl < 0.075) crashed = true; } if (pp.done()) { r.reached += 1; r.time += tick * 0.02; } clr += minclr; if (crashed) r.crash += 1; } r.time = r.reached ? r.time / r.reached : 0; r.reached = 100.0 * r.reached / seeds; r.xtrack = std::sqrt(sq / cnt) * 1000; r.clear = clr / seeds * 1000; r.crash = 100.0 * r.crash / seeds; return r; } int main() { World truth; truth_grid(truth); World inf; inflate(truth, inf, 1); static AStar<30, 20, 300> as; uint16_t cells[600]; int16_t n = as.plan(inf, 3, 3, 27, 17, cells, 600); uint16_t m = (uint16_t)(n + 1), ms = shortcut(inf, cells, m, 30); double len = 0; for (uint16_t i = 0; i + 1 < ms; ++i) len += std::hypot(((cells[i + 1] % 30) - (cells[i] % 30)) * 0.1, ((cells[i + 1] / 30) - (cells[i] / 30)) * 0.1); std::printf("A* path on the inflated grid: %d steps (%.2f m along the grid); after line-of-sight smoothing: %u waypoints, %.2f m long\n", n, n * 0.1, (unsigned)ms, len); std::printf("pure pursuit at 0.25 m/s, 20 seeds, assumed 1 cm / 1 degree localisation error\n"); std::printf(" path lookahead (m) reached (%%) time (s) rms distance from path (mm) closest approach to an obstacle (mm) runs with a collision (%%)\n"); for (int smooth = 0; smooth < 2; ++smooth) for (float L : {0.10f, 0.20f, 0.30f, 0.50f, 0.80f}) { R r = run(L, smooth != 0, 20); std::printf(" %-9s %13.2f %11.0f %8.1f %27.1f %36.0f %26.0f\n", smooth ? "smoothed" : "raw grid", L, r.reached, r.time, r.xtrack, r.clear, r.crash); } return 0; }
A* path on the inflated grid: 52 steps (5.20 m along the grid); after line-of-sight smoothing: 7 waypoints, 4.76 m long pure pursuit at 0.25 m/s, 20 seeds, assumed 1 cm / 1 degree localisation error path lookahead (m) reached (%) time (s) rms distance from path (mm) closest approach to an obstacle (mm) runs with a collision (%) raw grid 0.10 100 19.6 7.3 138 0 raw grid 0.20 100 18.6 17.1 130 0 raw grid 0.30 100 18.0 29.6 83 0 raw grid 0.50 95 17.0 114.3 0 100 raw grid 0.80 100 13.8 172.0 0 100 smoothed 0.10 100 19.0 6.9 115 0 smoothed 0.20 100 18.3 20.1 125 0 smoothed 0.30 100 17.8 38.5 83 0 smoothed 0.50 100 15.7 102.7 0 100 smoothed 0.80 100 12.1 206.7 0 100

On both paths the pattern is the same: a lookahead of 0.10 to 0.30 m follows the path (7 to 39 mm rms) with no collisions, and one of 0.50 m or more cuts the corners and every run collides (the robot centre closer than its 75 mm radius to an obstacle; the closest approach is 0, the centre inside the obstacle). The lookahead is also the price of smoothness: the staircase path at 0.10 m takes 19.6 s and at 0.30 m 18.0 s. The smoothed path, 9 % shorter, saves less time than that (19.0 s at 0.10 m) because the speed is fixed and the turns are the same; what it saves is waypoints, 7 against 53. The closest approach at 0.30 m is 83 mm, 8 mm over the limit: the usable range ends there, and challenge 3 maps it against speed.

That table is the third version of it. The first run said that every run on the smoothed path collided at every lookahead, even 0.10 m, with an rms distance from the path of 130 mm, which no sensible controller does on a straight segment. The cause was in PurePursuit, and it was two bugs in series. First, the code picked “the segment the robot is on” as the one whose end waypoint was nearest, which is correct for a dense staircase and wrong for 7 waypoints a metre apart: halfway along a segment the next waypoint is the nearer, so the lookahead started on the following segment and cut the corner. Fixing that (the nearest segment) changed nothing visible, because of the second bug: when the robot was more than one lookahead from the start of its segment, the circle test found nothing and the target silently defaulted to the goal, so the robot drove at the goal through the obstacles. The fix is in the header above: aim at the goal only when it is inside the circle, otherwise at the far crossing of the circle with the nearest segment, and otherwise at the next waypoint. What went wrong: a default that does something drastic, and a test (the dense staircase) that never reached the case. How to avoid it: test a follower on a sparse path as well as a dense one, and make a default the safe action, not the end of the route.

6. On the Uno

For a map that does not change, there is no need to build the grid on the robot at all. The program e_gen.cpp builds the test world on the PC, inflates it by one cell and writes the map as a C++ table, 75 bytes in flash:

// world_pm.h -- generated by e_gen.cpp: the 30 x 20 world inflated by one cell, one bit per cell, row by row, in flash const uint8_t WORLD_PM[75] GRID_PROGMEM = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x78, 0x00, 0x00, 0x0F, 0x1E, 0x00, 0xC0, 0x83, 0x07, 0x00, 0xF0, 0xE0, 0x01, 0x00, 0x3C, 0x78, 0x00, 0x00, 0x0F, 0x1E, 0x78, 0xC0, 0x83, 0x07, 0x1E, 0xF0, 0xE0, 0x81, 0x07, 0x3C, 0x78, 0xE0, 0x01, 0x0F, 0x1E, 0x78, 0xFE, 0x83, 0x07, 0x9E, 0xFF, 0x00, 0xF8, 0xE7, 0x3F, 0x00, 0xFE, 0xF9, 0x0F, 0x80, 0x7F, 0xFE, 0x03, 0xE0, 0x1F, 0xF0, 0x00, 0xF8, 0x07, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, };

robot_ch9.ino plans once at start-up with BFS (the 309-byte planner of the table; the biggest queue ever needed on this map was 12 cells, the queue holds 40) over a FlashGrid, smooths the route, and then follows it with pure pursuit at a 0.2 m lookahead on a pose from the wheel encoders (the midpoint update of Programming for Robotics with Arduino C++ 5), at 20 ms steps on the scheduler of Programming for Robotics with Arduino C++ 1. The wheels get the speeds as open-loop commands, without the speed controllers of Programming for Robotics with Arduino C++ 6.

// robot_ch9.ino -- Programming for Robotics with Arduino C++, chapter 9: plan a route over a map held in flash, smooth it, and follow it with pure pursuit on odometry. // Compile-checked for the Uno (arduino:avr:uno). NOT run on a board: nothing was attached; the map, the speeds and the 0.25 m/s are the SIMULATOR's. The wheels get open-loop speeds (no speed PI of chapter 6). #include <avr/io.h> #include <avr/interrupt.h> #include <util/atomic.h> #include "scheduler.h" #include "conv.h" #include "pins.h" #include "motion.h" #include "grid.h" #include "world_pm.h" // WORLD_PM: the 30 x 20 map inflated by one cell, generated by e_gen.cpp, in flash const float V_MAX_MPS = 0.5f; const uint8_t DEAD_DUTY = 40; // ASSUMED: measure yours const float WHEEL_R = 0.033f, TRACK = 0.150f; const float PER_TICK = 6.2831853f * WHEEL_R / 360.0f; const float CELL_M = 0.1f; volatile int32_t g_ticks_l = 0, g_ticks_r = 0; ISR(INT0_vect) { bool a = (PIND & _BV(PD2)) != 0, b = (PINC & _BV(PC1)) != 0; g_ticks_l += (a == b) ? 1 : -1; } ISR(INT1_vect) { bool a = (PIND & _BV(PD3)) != 0, b = (PINC & _BV(PC2)) != 0; g_ticks_r += (a == b) ? 1 : -1; } static 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 Bfs<30, 20, 40> planner; // 309 bytes of RAM (the queue holds 40 cells; the biggest ever needed on this map was 12) static uint16_t cells[100]; // the planned route, as cell numbers static Pt waypoints[16]; // the smoothed route in metres static uint8_t n_way = 0; static PurePursuit pursuit(0.20f, 0.25f, TRACK, 0.06f); static Pose pose = {0.35f, 0.35f, 0.0f}; static int32_t last_l = 0, last_r = 0; static Scheduler<2> sch; static void control_task(void*, uint32_t) { int32_t l, r; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { l = g_ticks_l; r = g_ticks_r; } float dl = (float)(l - last_l) * PER_TICK, dr = (float)(r - last_r) * PER_TICK; last_l = l; last_r = r; pose_midpoint(pose, 0.5f * (dl + dr), (dr - dl) / TRACK); if (n_way < 2 || pursuit.done()) { drive(0.0f, 0.0f); return; } Cmd c = pursuit.update(pose.x, pose.y, pose.th, waypoints, n_way); drive(c.vl, c.vr); } static void report_task(void*, uint32_t now) { Serial.print(now); Serial.print(F(" ms pose ")); Serial.print(pose.x, 2); Serial.print(' '); Serial.print(pose.y, 2); Serial.print(F(" waypoints ")); Serial.print(n_way); Serial.println(pursuit.done() ? F(" done") : F("")); } 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_ENC_L, INPUT_PULLUP); pinMode(PIN_ENC_R, INPUT_PULLUP); pinMode(PIN_ENC_L_B, INPUT_PULLUP); pinMode(PIN_ENC_R_B, INPUT_PULLUP); EICRA = _BV(ISC00) | _BV(ISC10); EIFR = _BV(INTF0) | _BV(INTF1); EIMSK = _BV(INT0) | _BV(INT1); FlashGrid<30, 20> map(WORLD_PM); int16_t steps = planner.plan(map, 3, 3, 27, 17, cells, 100); // plan once, at start-up, before the robot moves if (steps >= 0) { uint16_t m = shortcut(map, cells, (uint16_t)(steps + 1), 30); for (uint16_t i = 0; i < m && i < 16; ++i) { waypoints[i].x = ((cells[i] % 30) + 0.5f) * CELL_M; waypoints[i].y = ((cells[i] / 30) + 0.5f) * CELL_M; n_way = (uint8_t)(i + 1); } } Serial.print(F("plan: ")); Serial.print(steps); Serial.print(F(" steps, ")); Serial.print(n_way); Serial.println(F(" waypoints")); sch.add(control_task, 0, 20); sch.add(report_task, 0, 500); } void loop() { sch.run(millis()); }

It compiles for the Uno under --warnings all with no warning from the sketch to 11 388 bytes of flash (35 %) and 943 bytes of RAM (46 %). The flash is the largest of the course so far, because sinf, atan2f and sqrtf of the path follower and the float printing come from the floating-point library; the RAM is the planner (309), the route (200 and 128 bytes) and the rest of the robot. It was not run: no time per plan or per control step was measured, and whether BFS and A* choose the same route among equally short ones, so that the smoothed waypoints are the ones of section 5, was not checked.

7. What the numbers can and cannot be trusted for

What they show. The sizes: the formulas for BFS and A* are exact against sizeof and the compiler’s own symbol sizes, and A* on a 600-cell grid leaves the Uno with 61 bytes. The shapes: A* expands fewer cells and holds more; the two planners agree on every path length; a bit map with a 1-cell inflation can close a corridor that a score map keeps; a lookahead beyond about 0.3 m cuts corners in this world.

What they do not show. The world is one small arena with four boxes whose edges happen to align with the grid, which is the worst case for the bit maps; the random grids are not realistic rooms; the sensor, the ghosts, the localisation error and the 0.25 m/s are assumptions; the pure pursuit used a robot pose with only random noise, not the drift of real odometry (Programming for Robotics with Arduino C++ 5). No time was measured, so the claim that A* “is faster” is a claim about cells expanded, not about seconds, and with a heap in the loop it may not hold on a chip that cannot afford the heap.

Challenge 1: Predict the RAM
From the sizes of the arrays in grid.h, predict the “Global variables” figure the compiler will report for each of the four variants of the size-test sketch (baseline of 188 bytes, a path buffer of 200 bytes, the 30 × 20 map in flash, a 16 × 16 map in RAM), then compare with sizeof and with the compiler’s report. Say how much stack the A* variants leave.
View solution
Challenge 2: A weighted heuristic
Run A* with the heuristic weighted by 0, 1, 1.25, 1.5, 2, 3 and 4 on 300 random 32 × 32 grids at 20 % obstacles. Report the cells expanded, the longest open list, the mean path, the share of grids on which the path is longer than the optimal one, and the worst excess. Choose a weight for a robot that cannot afford a heap of 177 entries, and say what you give up.
View solution
Challenge 3: Lookahead against speed
Drive the planned path at 0.15, 0.25, 0.35 and 0.50 m/s with lookaheads of 0.10, 0.20, 0.30 and 0.40 m, 20 runs each, and report the share of runs with a collision and the time to the goal. Find the largest safe lookahead at each speed and say what happens to the time as the lookahead grows.
View solution

Quick reference

  • Grid. One bit per cell (600 cells = 75 bytes); outside counts as blocked; a map in flash with PROGMEM costs no RAM; inflate by the robot’s radius so the planner can treat it as a point.
  • Building a map. 1-bit and 2-bit maps spill across edges (63–117 wrong cells against 15 for an 8-bit score) and, inflated by 1 cell, closed the only corridor in every run; the 8-bit score kept it in every run.
  • BFS against A*. Same path length on every grid; A* expands 0.39–0.47 of the cells (407 against 920 at 10 %) but its heap needed 275 entries (about 1100 bytes) against 40 queue cells (80 bytes).
  • Capacity. A planner whose queue or heap is full returns an error, never overruns: BFS queue 32 abandoned 121 searches, 64 none; A* heap 128 abandoned 70.
  • RAM formulas. BFS = cells/8 + cells/4 + 2Q + 4. A* = cells/8 + cells + cells/4 + 4HC + 6. Exact against sizeof (516, 2614) and avr-nm (1599 for A* 30 × 20, heap 192).
  • Fits in 1500 bytes. BFS up to 40 × 40; A* only at 16 × 16. A* 30 × 20 compiles and leaves 61 bytes of stack.
  • const is RAM on an AVR. Two 4-byte const tables cost 8 bytes of RAM; two inline functions cost none (RAM 705→697).
  • Smoothing and pure pursuit. 53 cells → 7 waypoints, 5.20 m → 4.76 m. Lookahead 0.10–0.30 m: 7–39 mm rms, no collisions; 0.50 m and up: collisions in every run. Target the goal only when it is inside the circle; test on a sparse path.
  • Budget. robot_ch9.ino: 11 388 bytes flash (35 %), 943 bytes RAM (46 %), compiled, not run; no time measured.
  • Not run: anything on a board; time per plan or per step; real odometry drift; any map built from a real sensor.

Next: Programming for Robotics with Arduino C++ 10, State Estimation

Programming for Robotics with Arduino C++ 10 (planned; not yet written) is about knowing where the robot is: the complementary filter, a one-dimensional Kalman filter and a two-by-two position-and-speed filter with the matrices written out, fusing odometry with an IMU, and the count of operations that makes float against fixed-point the central question on a chip with no floating-point unit.