Programming for Robotics 1 (the Python course) built every robot idea on a computer with a gigabyte of memory and a clock nobody thought about. This course builds the same twelve chapters again for the kind of computer that sits inside a robot: an Arduino Uno R3, an 8-bit AVR chip with 2 KB of RAM, 32 KB of flash for the program, 16 MHz, and no floating-point hardware. Nothing here is slower than it needs to be by accident, and nothing is hidden: you will see what a log costs in bytes, what a mistake in a timer does to a robot, and why a habit that is harmless on a laptop (delay(), a String, a virtual function) is not harmless on a board.
The chapter assumes no C++. The language is taught in boxes as it is needed, and section 2 is a short tour for someone who knows Python. The robot is a very small one on purpose: it drives toward a wall and stops 0.25 m short of it. The interesting part is the architecture around it: how time is kept, how tasks are scheduled, how code is split into files and how the board's memory is budgeted.
What was run, and what was not
Run on a PC (g++ 16.2, C++11, -Wall -Wextra -pedantic, no warnings): every block below that has an output under it. These programs use a fake clock (an integer that the program itself advances), so their millisecond figures are exact and repeatable, but they are simulations of timing, not measurements of a board. The headers (timing.h, scheduler.h, log.h, robot.h) contain no Arduino calls, so the very same text is compiled both for the PC and for the board. Compiled for the Uno, not run (arduino-cli 1.6.0, core arduino:avr 1.8.8): the sketch robot_ch1.ino. The “Sketch uses” and “Global variables use” figures in section 11 are the real compiler's reports; they are static sizes. No board was attached, so no timing, no serial output and no stack depth on a real Uno is claimed anywhere in this chapter.
1. What changes when the computer is a chip
The robot code of the Python course was the same in spirit: read a sensor, decide, command a motor, repeat at a fixed rate. What changes is the setting.
Python on a PC (Programming for Robotics 1)
C++ on an Uno
Memory
gigabytes; a list grows as needed
2048 bytes of RAM; every array has a size fixed when the program is built
Program space
effectively unlimited
32,256 bytes of flash after the bootloader
Numbers
int never overflows; float is a 64-bit double
int is 16 bits and wraps; double is only 32 bits (section 2)
Errors
an exception, with a traceback
usually nothing: a wrong index or a stack that runs out silently corrupts something else
Time
an operating system schedules you; time.sleep() is polite
nobody schedules you; your loop()is the operating system
Checking
run it and look
the compiler reports memory use before it ever runs: use it (section 11)
2. C++ for Python programmers
Eight ideas carry most of what this chapter needs. Each is shown by running something.
1 · Types are declared and have a size
Python's x = 7 works out the type at run time; C++ fixes it at compile time (int x = 7;, float y = 0.5f;, uint8_t n = 200;). The size depends on the machine, and that is the first trap: the program below, run on the PC, prints the PC's sizes, and the sketch of section 11 proves the board's with static_assert (a check the compiler makes while building, with no cost at run time).
// e_types.cpp -- what C++ does that Python does not (host build; the board's sizes are checked by static_assert in the sketch of section 11)
#include <cstdio>
#include <cstdint>
int main() {
std::printf("host sizes in bytes: int %zu, long %zu, long long %zu, float %zu, double %zu, pointer %zu\n",
sizeof(int), sizeof(long), sizeof(long long), sizeof(float), sizeof(double), sizeof(void*));
uint8_t a = 250;
a = (uint8_t)(a + 10); // a uint8_t holds 0..255 and WRAPS
std::printf("uint8_t 250 + 10 = %d\n", a);
unsigned int u = 0;
u = u - 1; // unsigned arithmetic is modulo 2^N: defined, and used on purpose (section 4)
std::printf("unsigned 0 - 1 = %u\n", u);
std::printf("7 / 2 = %d 7 / 2.0f = %.2f -7 / 2 = %d -7 %% 3 = %d\n", 7 / 2, 7 / 2.0f, -7 / 2, -7 % 3);
float big = 16777216.0f; // 2^24: the end of the float's exact whole numbers
std::printf("float 16777216 + 1 = %.1f (float has a 24-bit mantissa)\n", big + 1.0f);
float tenth = 0.1f, sum = 0.0f;
for (int i = 0; i < 10; ++i) sum += tenth;
std::printf("0.1f is stored as %.10f; ten of them sum to %.10f\n", tenth, sum);
int truncated = (int)-3.9f;
std::printf("(int)-3.9 = %d (it truncates toward zero)\n", truncated);
return 0;
}
host sizes in bytes: int 4, long 4, long long 8, float 4, double 8, pointer 8
uint8_t 250 + 10 = 4
unsigned 0 - 1 = 4294967295
7 / 2 = 3 7 / 2.0f = 3.50 -7 / 2 = -3 -7 % 3 = -1
float 16777216 + 1 = 16777216.0 (float has a 24-bit mantissa)
0.1f is stored as 0.1000000015; ten of them sum to 1.0000001192
(int)-3.9 = -3 (it truncates toward zero)
The same questions in Python, for comparison:
# the same lines in Python
print("7 // 2 =", 7 // 2, " 7 / 2 =", 7 / 2, " -7 // 2 =", -7 // 2, " -7 % 3 =", -7 % 3)
print("250 + 10 =", 250 + 10, " (an int never wraps) 2**24 + 1.0 =", 2**24 + 1.0, " (a Python float is a 53-bit double)")
print("int(-3.9) =", int(-3.9))
7 // 2 = 3 7 / 2 = 3.5 -7 // 2 = -4 -7 % 3 = 2
250 + 10 = 260 (an int never wraps) 2**24 + 1.0 = 16777217.0 (a Python float is a 53-bit double)
int(-3.9) = -3
Type
This PC (run)
Uno R3 (compile-time checked)
int
4 bytes
2 bytes (so 32767 + 1 wraps)
long
4 bytes
4 bytes
long long
8 bytes
8 bytes
float
4 bytes
4 bytes
double
8 bytes
4 bytes: the same as float
pointer
8 bytes
2 bytes
Three results in the output matter for the rest of the chapter: uint8_t and unsigned arithmetic wrap around (250 + 10 is 4; 0 - 1 is 4294967295), integer division truncates toward zero (-7 / 2 is -3, where Python's // floors to -4), and a 32-bit float cannot count past 16,777,216 (+ 1 changes nothing). Python never does any of these to an int.
2 · Classes, and a header file instead of an import
A class bundles data with the functions that use it, as in Python, but its members are declared with a type and an access level (public: / private:). C++ has no import; a .hheader is pasted into the file by #include, and #pragma once at the top stops it being pasted twice. The headers of this chapter hold their code in full, which is the simple way to share code in a small Arduino project.
3 · References, pointers and const
HW& hw is a reference: the object itself, not a copy (what every Python variable already is). void* ctx is a pointer: the address of something, used where a plain function must be handed an object. const on a function (int size() const) promises that it changes nothing.
4 · Templates: code generated for a type
template <class HW> class WallRobot is a recipe; WallRobot<SimHW> makes the compiler write a copy of the class for that one hardware type, calls and all. A Python class works with any object that has the right methods, decided while the program runs; a template gets the same freedom decided while compiling, so it costs nothing at run time (section 8 measures this). template <uint8_t N> takes a number, which is how a buffer gets its size.
The rest (the setup()/loop() pair, millis(), Serial, F("...")) are Arduino's, and appear where they are first used.
3. The first loop: sense, think, act
An Arduino program is two functions. setup() runs once. loop() is then called again and again, forever, as fast as it can run. There is no main() to write and no while True:: the loop is the board's own.
The robot is three small methods on a class, the same sense-think-act shape as the robots of Programming for Robotics 1: sense reads the world (a range), think turns the range into a speed with a proportional controller limited to a top speed, act writes the speed. The hardware is a template parameter, so the same robot runs against a simulated world on the PC and the board:
// robot.h -- the sense-think-act pieces of a robot that drives toward a wall and stops 0.25 m short of it.
// The hardware is a TEMPLATE parameter HW with two functions, range_m() and drive(speed): the compiler builds the call straight in, so the
// abstraction costs no RAM and no time (section 8 measures a virtual-function version for comparison).
#pragma once
#include <stdint.h>
inline float clampf(float v, float lo, float hi) { return v < lo ? lo : (v > hi ? hi : v); }
template <class HW>
class WallRobot {
public:
WallRobot(HW& hw, float stop_m, float gain, float vmax_mps)
: hw_(hw), stop_m_(stop_m), gain_(gain), vmax_(vmax_mps), range_(0.0f), cmd_(0.0f) {}
void sense(uint32_t) { range_ = hw_.range_m(); } // SENSE: read the world
void think(uint32_t) { cmd_ = clampf(gain_ * (range_ - stop_m_), 0.0f, vmax_); } // THINK: a proportional controller with a speed limit
void act(uint32_t) { hw_.drive(cmd_); } // ACT: write the world
float range() const { return range_; }
float command() const { return cmd_; }
// Scheduler trampolines: a TaskFn is a plain function pointer, so the object travels in `ctx`.
static void sense_task(void* c, uint32_t now) { static_cast<WallRobot*>(c)->sense(now); }
static void think_task(void* c, uint32_t now) { static_cast<WallRobot*>(c)->think(now); }
static void act_task(void* c, uint32_t now) { static_cast<WallRobot*>(c)->act(now); }
private:
HW& hw_;
float stop_m_, gain_, vmax_, range_, cmd_;
};
// A simulated world for the PC and for the board: a wall 1.00 m ahead, a robot that moves by speed x dt.
struct SimHW {
float x_m, speed_mps, wall_m;
explicit SimHW(float wall = 1.0f) : x_m(0.0f), speed_mps(0.0f), wall_m(wall) {}
float range_m() { return wall_m - x_m; }
void drive(float v) { speed_mps = v; }
void advance(float dt_s) { x_m += speed_mps * dt_s; }
};
Run for six simulated seconds with all three at 20 ms (50 Hz), against a wall 1.00 m away:
// e_robot.cpp -- the wall robot in closed loop: sense, think and act every 20 ms, a world that advances every millisecond (host build)
#include <cstdio>
#include "scheduler.h"
#include "robot.h"
int main() {
SimHW world(1.0f); // a wall 1.00 m ahead, the robot at 0
WallRobot<SimHW> robot(world, 0.25f, 1.5f, 0.5f); // stop 0.25 m short; gain 1.5 per second; at most 0.5 m/s
Scheduler<3> sch;
sch.add(WallRobot<SimHW>::sense_task, &robot, 20);
sch.add(WallRobot<SimHW>::think_task, &robot, 20);
sch.add(WallRobot<SimHW>::act_task, &robot, 20);
std::printf(" t s range m speed m/s\n");
for (uint32_t t = 0; t <= 6000; ++t) {
sch.run(t);
world.advance(0.001f);
if (t % 500 == 0) std::printf(" %3.1f %7.3f %8.3f\n", t / 1000.0, world.range_m(), world.speed_mps);
}
std::printf("at 6 s the robot is %.3f m from the wall (the stop line is 0.250 m); sense, think and act each ran %u times\n",
world.range_m(), (unsigned)sch.task(0).timer.runs());
return 0;
}
t s range m speed m/s
0.0 0.999 0.500
0.5 0.750 0.500
1.0 0.508 0.388
1.5 0.371 0.181
2.0 0.306 0.085
2.5 0.276 0.040
3.0 0.262 0.018
3.5 0.256 0.009
4.0 0.253 0.004
4.5 0.251 0.002
5.0 0.251 0.001
5.5 0.250 0.000
6.0 0.250 0.000
at 6 s the robot is 0.250 m from the wall (the stop line is 0.250 m); sense, think and act each ran 301 times
The robot drives at the top speed, slows as the error shrinks, and settles on the stop line at 0.250 m (0.253 at 4 s; 0.250 by 5.5 s). It is a first-order approach: each second removes about the same fraction of what is left. All three tasks ran 301 times: once per 20 ms plus the first call.
4. Time on a microcontroller, and the wrap-around
millis() returns the milliseconds since power-on as an unsigned long, 32 bits. It is a number that wraps to 0 after 232 ms, which is 49.71 days; micros() does the same after 232 microseconds, which is only 71.58 minutes (both figures are the first line of the output below). The wrap is not an unlikely event: it is certain, and a robot that is left switched on will meet it. The standard code that looks right is if (now >= next); the correct code subtracts: now - then is computed modulo 232, so it gives the right elapsed time even when now has wrapped past then. The header holds both, the wrong one only so it can be shown failing, and a drift-free timer built on the correct one:
// timing.h -- time on a microcontroller (Programming for Robotics with Arduino C++ 1). Plain C++11: no Arduino calls, so it builds on the board and on a PC.
#pragma once
#include <stdint.h>
// Time is an unsigned 32-bit counter that WRAPS: millis() after 2^32 ms (49.7 days), micros() after 2^32 us (71.6 minutes).
// In C++ unsigned arithmetic is defined modulo 2^32, so this subtraction is correct even when `now` has wrapped past `then`.
inline uint32_t elapsed(uint32_t now, uint32_t then) { return now - then; }
// WRONG, and very common: it compares two times as if the counter never wrapped. It is here only to be shown failing.
inline bool naive_due(uint32_t now, uint32_t next) { return now >= next; }
// A fixed-rate timer that does not drift and does not burst. due(now) is true at most once per call.
class Periodic {
public:
explicit Periodic(uint32_t period) : period_(period), last_(0), started_(false), runs_(0), skipped_(0) {}
uint32_t lateness(uint32_t now) const { // how long after its moment the timer is being asked (0 if not yet due)
if (!started_) return 0;
uint32_t dt = elapsed(now, last_);
return dt >= period_ ? dt - period_ : 0;
}
bool due(uint32_t now) {
if (!started_) { started_ = true; last_ = now; ++runs_; return true; }
uint32_t dt = elapsed(now, last_);
if (dt < period_) return false;
if (dt < 2 * period_) {
last_ += period_; // on time, or a little late: step along the grid, never "to now" (that is drift)
} else {
uint32_t n = dt / period_; // late by whole periods: stay on the grid, count what was missed, do NOT run n times
last_ += n * period_;
skipped_ += n - 1;
}
++runs_;
return true;
}
uint32_t period() const { return period_; }
uint32_t runs() const { return runs_; }
uint32_t skipped() const { return skipped_; }
private:
uint32_t period_, last_;
bool started_;
uint32_t runs_, skipped_;
};
A fake clock is started a few milliseconds before the wrap, and a 5 ms timer is run both ways. start = 4294967290 is 6 ms before the wrap; 4294967293 is 3 ms before it:
// e_wrap.cpp -- a 5 ms timer across the wrap of the millisecond counter, done right and done wrong (host build, a fake clock)
#include <cstdio>
#include "timing.h"
static void run(uint32_t start, bool verbose) {
Periodic good(5);
uint32_t next = start; // the naive timer: "run when now has reached next, then next += 5"
int good_n = 0, naive_n = 0;
uint32_t gl = 0, nl = 0, gmin = 999, gmax = 0, nmin = 999, nmax = 0; // last run time and shortest/longest gap, for each timer
bool gseen = false, nseen = false;
if (verbose) std::printf(" k now Periodic naive\n");
for (uint32_t k = 0; k <= 30; ++k) {
uint32_t now = start + k; // wraps to 0, 1, 2 ... in unsigned arithmetic
bool g = good.due(now);
bool n = naive_due(now, next);
if (n) next += 5;
good_n += g;
naive_n += n;
if (g) { if (gseen) { uint32_t d = now - gl; if (d < gmin) gmin = d; if (d > gmax) gmax = d; } gl = now; gseen = true; }
if (n) { if (nseen) { uint32_t d = now - nl; if (d < nmin) nmin = d; if (d > nmax) nmax = d; } nl = now; nseen = true; }
if (verbose && (k <= 8 || g || n))
std::printf("%3u %-11u %-8s %s\n", (unsigned)k, (unsigned)now, g ? "RUN" : "", n ? "RUN" : "");
}
std::printf("start = %u (%u ms before the wrap): Periodic ran %d times, gaps %u..%u ms; naive ran %d times, gaps %u..%u ms (wanted 5..5)\n",
(unsigned)start, (unsigned)(0u - start), good_n, (unsigned)gmin, (unsigned)gmax, naive_n, (unsigned)nmin, (unsigned)nmax);
}
int main() {
std::printf("millis() wraps after %.2f days; micros() after %.2f minutes\n", 4294967296.0 / 86400000.0, 4294967296.0 / 60000000.0);
run(4294967290u, false); // 6 ms before the wrap: by luck, next and now wrap together and the naive timer works
run(4294967293u, true); // 3 ms before the wrap: next wraps first, and the naive timer fires on every pass
std::printf("elapsed(2, 4294967290) = %u (the true gap is 8 ms)\n", (unsigned)elapsed(2u, 4294967290u));
return 0;
}
millis() wraps after 49.71 days; micros() after 71.58 minutes
start = 4294967290 (6 ms before the wrap): Periodic ran 7 times, gaps 5..5 ms; naive ran 7 times, gaps 5..5 ms (wanted 5..5)
k now Periodic naive
0 4294967293 RUN RUN
1 4294967294 RUN
2 4294967295 RUN
3 0
4 1
5 2 RUN
6 3
7 4
8 5
10 7 RUN
15 12 RUN RUN
20 17 RUN RUN
25 22 RUN RUN
30 27 RUN RUN
start = 4294967293 (3 ms before the wrap): Periodic ran 7 times, gaps 5..5 ms; naive ran 7 times, gaps 1..13 ms (wanted 5..5)
elapsed(2, 4294967290) = 8 (the true gap is 8 ms)
Read the first line carefully, because it is the more dangerous one: 6 ms before the wrap the naive timer works perfectly (gaps 5..5), because the timer's target and the clock wrap in step. A test that happened to start there would pass. 3 ms before the wrap it fails: the target (4294967298) wrapped to 2 while the clock was still at 4294967293, so now >= next is true on three consecutive passes (k = 0, 1, 2 in the table), and then the timer stays silent for 12 ms. Its count of runs is still 7, the same as the correct timer's; only the gaps (1..13 ms, against 5..5) show the fault. Judge a timer by the gaps between its runs, not by how many times it ran.
Challenge 1 shows how bad this is: of 40 possible start offsets, the naive timer misbehaves for 37. elapsed(), the last line of the output, is the whole cure: elapsed(2, 4294967290) is 8, the true gap, with no special case for the wrap.
5. A fixed rate without drift
The loop most beginners write is work(); delay(20);. It aims at 50 Hz, but each pass takes the work plus 20 ms, so the rate is lower and, worse, wanders with the work. A Periodic timer instead keeps a schedule of moments (0, 20, 40 ms ...) and asks each pass whether the next moment has arrived; it advances by exactly one period, never to “now”, which is what removes drift. If a pass is late by whole periods, it stays on the grid, counts the periods it missed (skipped) and runs once, not in a burst.
// e_drift.cpp -- delay(20) after the work, against a Periodic timer, with 1 to 6 ms of work per pass (host build, a fake clock)
#include <cstdio>
#include <random>
#include <algorithm>
#include "timing.h"
struct Stats {
uint32_t n = 0, last = 0, lo = 0xFFFFFFFFu, hi = 0;
double sum = 0;
void tick(uint32_t t) {
if (n > 0) { uint32_t d = t - last; lo = std::min(lo, d); hi = std::max(hi, d); sum += d; }
++n;
last = t;
}
};
int main() {
const uint32_t seconds = 10, end_ms = seconds * 1000;
std::mt19937 rng(1);
std::uniform_int_distribution<int> work(1, 6); // ms of work per pass, different every time
Stats a; // loop 1: work(); delay(20);
for (uint32_t t = 0; t < end_ms;) {
a.tick(t);
t += work(rng); // the work
t += 20; // delay(20)
}
rng.seed(1);
Stats b; // loop 2: if (timer.due(now)) work(); polled every millisecond
Periodic timer(20);
for (uint32_t t = 0; t < end_ms; ++t) {
if (timer.due(t)) {
b.tick(t);
t += work(rng) - 1; // the work uses the clock up (the -1 allows for the loop's own ++t)
}
}
std::printf("10 s of a nominal 50 Hz loop, work 1 to 6 ms per pass:\n");
std::printf(" loop passes mean ms shortest longest\n");
std::printf(" work(); delay(20) %6u %7.2f %8u %7u\n", (unsigned)a.n, a.sum / (a.n - 1), (unsigned)a.lo, (unsigned)a.hi);
std::printf(" Periodic(20) %6u %7.2f %8u %7u (skipped %u)\n", (unsigned)b.n, b.sum / (b.n - 1), (unsigned)b.lo, (unsigned)b.hi, (unsigned)timer.skipped());
return 0;
}
10 s of a nominal 50 Hz loop, work 1 to 6 ms per pass:
loop passes mean ms shortest longest
work(); delay(20) 428 23.42 21 26
Periodic(20) 500 20.00 20 20 (skipped 0)
With 1 to 6 ms of work per pass, the delay(20) loop managed 428 passes in 10 s instead of 500: a mean of 23.42 ms, intervals anywhere from 21 to 26 ms. A controller that assumes a 20 ms step is wrong by 17 % on average here and by a different amount every pass. The Periodic loop ran 500 passes at exactly 20.00 ms, none skipped. (The work is the same random sequence in both loops, and the “work” here is a fake clock jump, so these are exact for the model and say nothing about how long a real servo write takes.)
6. Never block
delay(500) is the most dangerous function in the Arduino toolbox for a robot, because it does nothing for 500 ms: no sensor is read, no button is seen, no emergency stop is noticed. A robot that blinks a light with delay cannot also watch for a bump. The cost, measured on a button pressed at 20 random times:
// e_block.cpp -- how long does a button press wait to be noticed? 20 presses at random times in 20 s, an LED that blinks at 1 Hz (host build)
#include <cstdio>
#include <random>
#include <vector>
#include <algorithm>
#include "timing.h"
int main() {
std::mt19937 rng(7);
std::uniform_int_distribution<uint32_t> when(500, 19500);
std::vector<uint32_t> presses;
for (int i = 0; i < 20; ++i) presses.push_back(when(rng));
std::sort(presses.begin(), presses.end());
// Version 1: blocking. loop() { led(HIGH); delay(500); led(LOW); delay(500); if (button) react(); } the button is read once per 1000 ms
double sum1 = 0; uint32_t max1 = 0;
for (uint32_t p : presses) {
uint32_t next_look = ((p / 1000) + 1) * 1000; // the end of the current 1000 ms pass
uint32_t lat = next_look - p;
sum1 += lat; max1 = std::max(max1, lat);
}
// Version 2: non-blocking; the loop spins and looks at the button every pass (about 1 ms), the LED is toggled by a timer.
double sum2 = 0; uint32_t max2 = 0;
for (size_t i = 0; i < presses.size(); ++i) { uint32_t lat = 1; sum2 += lat; max2 = std::max(max2, lat); }
// Version 3: non-blocking, the button polled by a Periodic(10) timer.
double sum3 = 0; uint32_t max3 = 0;
for (uint32_t p : presses) {
Periodic poll(10);
uint32_t t = 0;
while (true) { if (poll.due(t) && t >= p) break; ++t; }
uint32_t lat = t - p;
sum3 += lat; max3 = std::max(max3, lat);
}
std::printf("20 presses; time from the press to the program noticing it (ms):\n");
std::printf(" version mean worst\n");
std::printf(" blocking: delay(500) twice per pass %5.1f %6u\n", sum1 / 20, (unsigned)max1);
std::printf(" non-blocking, polled every pass (1 ms) %5.1f %6u\n", sum2 / 20, (unsigned)max2);
std::printf(" non-blocking, Periodic(10) poll %5.1f %6u\n", sum3 / 20, (unsigned)max3);
return 0;
}
20 presses; time from the press to the program noticing it (ms):
version mean worst
blocking: delay(500) twice per pass 496.1 979
non-blocking, polled every pass (1 ms) 1.0 1
non-blocking, Periodic(10) poll 3.6 9
With the blocking blink the press waited a mean of 496.1 ms and as much as 979 ms before the program looked. Polling every pass noticed in 1 ms (that row is assumed to be one pass of a 1 ms loop, not measured). Polling from a 10 ms timer averaged 3.6 ms and never took more than 9. The cure is not clever: replace every delay with a timer and let loop() spin, so that the time between looks at the sensors is short and bounded.
7. A static scheduler
Once there are several jobs at several rates, one Periodic each, checked in turn, is a scheduler. This one has a fixed table of tasks (a plain array, size known at compile time, no heap), each a function pointer, a context pointer and a timer. Tasks earlier in the table are looked at first, so they have priority when two are due at once. It records each task's worst lateness, which is the number a real-time programmer actually wants.
// scheduler.h -- a cooperative scheduler with a fixed task table: no heap, no threads, no delay().
#pragma once
#include <stdint.h>
#include "timing.h"
typedef void (*TaskFn)(void* ctx, uint32_t now);
struct Task {
TaskFn fn;
void* ctx;
Periodic timer;
uint32_t worst_late; // the largest lateness at which this task was started (same unit as `now`)
Task() : fn(0), ctx(0), timer(1), worst_late(0) {}
};
// N is the capacity, fixed at compile time: the table is a plain array, so its RAM cost is known before the program runs.
template <uint8_t N>
class Scheduler {
public:
Scheduler() : n_(0) {}
bool add(TaskFn fn, void* ctx, uint32_t period) { // earlier tasks have priority: they are looked at first on every pass
if (n_ >= N) return false;
tasks_[n_].fn = fn;
tasks_[n_].ctx = ctx;
tasks_[n_].timer = Periodic(period);
++n_;
return true;
}
void run(uint32_t now) { // call this from loop(); each task runs at most once per call
for (uint8_t i = 0; i < n_; ++i) {
Task& t = tasks_[i];
uint32_t late = t.timer.lateness(now);
if (t.timer.due(now)) {
if (late > t.worst_late) t.worst_late = late;
t.fn(t.ctx, now);
}
}
}
uint8_t size() const { return n_; }
const Task& task(uint8_t i) const { return tasks_[i]; }
private:
Task tasks_[N];
uint8_t n_;
};
Three tasks (sense every 10 ms costing 1 ms, control every 20 ms costing 3 ms, a log every 100 ms costing 2 ms) over one simulated second, then the same with a control task that takes 35 ms, longer than its own period:
// e_sched.cpp -- a Scheduler with three tasks over one simulated second, then the same with a task that takes too long (host build)
#include <cstdio>
#include "scheduler.h"
static uint32_t g_now = 0; // the fake clock; a task that takes time moves it forward
struct Counter { const char* name; uint32_t cost_ms; uint32_t calls; };
static void work(void* ctx, uint32_t) { Counter* c = static_cast<Counter*>(ctx); ++c->calls; g_now += c->cost_ms; }
static void run(uint32_t control_cost) {
Counter sense = {"sense 10 ms", 1, 0}, control = {"control 20 ms", control_cost, 0}, log = {"log 100 ms", 2, 0};
Scheduler<4> sch;
sch.add(work, &sense, 10);
sch.add(work, &control, 20);
sch.add(work, &log, 100);
for (g_now = 0; g_now < 1000; ++g_now) sch.run(g_now);
std::printf(" task period runs skipped worst lateness ms\n");
Counter* all[3] = {&sense, &control, &log};
for (uint8_t i = 0; i < sch.size(); ++i)
std::printf(" %-14s %5u %4u %7u %8u\n", all[i]->name, (unsigned)sch.task(i).timer.period(), (unsigned)sch.task(i).timer.runs(),
(unsigned)sch.task(i).timer.skipped(), (unsigned)sch.task(i).worst_late);
}
int main() {
std::printf("tasks cost 1, 3 and 2 ms (control takes 3 ms):\n");
run(3);
std::printf("the same, but control now takes 35 ms, more than its own 20 ms period:\n");
run(35);
return 0;
}
tasks cost 1, 3 and 2 ms (control takes 3 ms):
task period runs skipped worst lateness ms
sense 10 ms 10 100 0 0
control 20 ms 20 50 0 0
log 100 ms 100 10 0 0
the same, but control now takes 35 ms, more than its own 20 ms period:
task period runs skipped worst lateness ms
sense 10 ms 10 27 72 37
control 20 ms 20 27 23 36
log 100 ms 100 10 0 30
With honest costs everything runs on time: 100, 50 and 10 runs, nothing skipped, lateness 0. With the 35 ms task, every task suffers: sense should have run 100 times and ran 27, with 72 periods skipped; control itself ran 27 times with 23 skipped; and even the 100 ms log, which skips none, started up to 30 ms late. A cooperative scheduler cannot interrupt a task that is running, so one slow task spoils the timing of all the others. This is why the rule of the rest of the course is that a task does a small amount of work and returns.
8. Templates against virtual functions
The robot reaches the hardware through HW. There are two ways to do that. A template parameter (as in robot.h) lets the compiler build the call directly. A virtual interface (an abstract base class with virtual functions, as Python programmers expect) makes every call go through a table of function pointers, looked up while running. Both were compiled for the Uno, with everything else identical:
Version
Flash (of 32,256)
RAM (of 2,048)
template WallRobot<SimHW>
4950 bytes
473 bytes
virtual WallRobot<IHW>
5002 bytes (+52)
483 bytes (+10)
The virtual version costs 52 more bytes of flash and 10 more bytes of RAM (compile-time figures; the compiler's report does not say which part of the 10 is the object's pointer and which is the table). On a board with 2 KB that is half a percent of the RAM, so it is not a reason to avoid virtual functions in a place where they make the code clearer. It also does not show how much time each call costs, because the program was not run on a board. The honest rule: measure, do not guess; and a template is the default because its cost is zero by construction.
9. Project layout
An Arduino sketch is a folder; the .ino file has the same name as the folder, and every other file in the folder is compiled with it. Keeping the pure logic in headers with no Arduino calls is what lets the PC test the code that runs on the robot:
robot_ch1/
├── robot_ch1.ino setup() and loop(); the only file that calls Arduino functions
├── timing.h elapsed(), Periodic (plain C++, builds on a PC)
├── scheduler.h Task, Scheduler<N> (plain C++)
├── log.h LogEntry, RingLog<N> (plain C++)
└── robot.h WallRobot<HW>, SimHW (plain C++)
The result is that every number in sections 3 to 7 and 10 came from compiling these same headers with g++ on a PC, which can be done in a second with strict warnings, and they were then compiled unchanged for the Uno.
10. Logging: a ring buffer of codes
A robot has no screen and, once it moves, no cable. Its record of what happened is a black-box log: a fixed-size buffer of small records where the newest entry overwrites the oldest when it is full, so the log always holds the last N events, which are the ones that matter after a crash. A message is stored as a one-byte code, not a string, because on this board each character of a string costs a byte of RAM. A record is 8 bytes: a 4-byte time, a level, a code and a 16-bit value.
// log.h -- a black-box log: a ring buffer of small fixed-size records. Messages are CODES, not strings: a string costs RAM per character.
#pragma once
#include <stdint.h>
enum LogLevel : uint8_t { LOG_DEBUG = 0, LOG_INFO = 1, LOG_WARN = 2, LOG_FAULT = 3 };
struct LogEntry { // 8 bytes on the board and on the PC
uint32_t t;
uint8_t level;
uint8_t code;
int16_t value;
};
template <uint8_t N>
class RingLog {
static_assert(N > 0, "RingLog capacity must be 1..255: a larger value was truncated to fit the uint8_t template parameter");
public:
RingLog() : head_(0), count_(0), dropped_(0) {}
void add(uint32_t t, LogLevel level, uint8_t code, int16_t value) {
if (count_ == N) ++dropped_; else ++count_; // when full, the oldest record is overwritten and counted
buf_[head_].t = t;
buf_[head_].level = level;
buf_[head_].code = code;
buf_[head_].value = value;
head_ = (uint8_t)((head_ + 1) % N);
}
uint8_t size() const { return count_; }
uint32_t dropped() const { return dropped_; }
const LogEntry& at(uint8_t i) const { // i = 0 is the oldest record still held
uint8_t first = (uint8_t)((head_ + N - count_) % N);
return buf_[(first + i) % N];
}
private:
LogEntry buf_[N];
uint8_t head_, count_;
uint32_t dropped_;
};
Eight records, twelve events:
// e_log.cpp -- a RingLog of 8 records, 12 events added: the oldest 4 are overwritten and counted (host build)
#include <cstdio>
#include "log.h"
static const char* const LEVEL[] = {"DEBUG", "INFO", "WARN", "FAULT"};
static const char* const MESSAGE[] = {"boot", "range read", "speed set", "range timeout", "safe stop"}; // codes index this table (flash on the board)
int main() {
RingLog<8> log;
std::printf("a LogEntry is %zu bytes, a RingLog<8> is %zu bytes\n", sizeof(LogEntry), sizeof(RingLog<8>));
for (int i = 0; i < 12; ++i) {
uint8_t code = (i == 0) ? 0 : (i == 10) ? 3 : (i == 11) ? 4 : (uint8_t)(1 + i % 2);
LogLevel lv = (i == 10) ? LOG_WARN : (i == 11) ? LOG_FAULT : (i == 0) ? LOG_INFO : LOG_DEBUG;
log.add(100u * (uint32_t)i, lv, code, (int16_t)(i * 10));
}
std::printf("kept %u, dropped %u\n", (unsigned)log.size(), (unsigned)log.dropped());
for (uint8_t i = 0; i < log.size(); ++i) {
const LogEntry& e = log.at(i);
std::printf("%6u ms %-5s %-14s [%d]\n", (unsigned)e.t, LEVEL[e.level], MESSAGE[e.code], e.value);
}
return 0;
}
a LogEntry is 8 bytes, a RingLog<8> is 72 bytes
kept 8, dropped 4
400 ms DEBUG range read [40]
500 ms DEBUG speed set [50]
600 ms DEBUG range read [60]
700 ms DEBUG speed set [70]
800 ms DEBUG range read [80]
900 ms DEBUG speed set [90]
1000 ms WARN range timeout [100]
1100 ms FAULT safe stop [110]
Four events were overwritten and counted (dropped is 4), and the dump shows the last eight, ending with the fault and the safe stop. The log reports its own loss: a log that silently loses events cannot be trusted. On the PC RingLog<8> is 72 bytes: 8 records of 8 bytes plus two counters and padding.
A real mistake the compiler hid
The capacity N is a uint8_t, so it can be at most 255. I tried a log of 256 records for the Uno, and it compiled: “Global variables use 329 bytes”, less than the 473 bytes of a 16-record log. 256 had been silently truncated to 0, so the log had shrunk to nothing, and the only hint was a -Woverflow warning that arduino-cli does not show by default (it appeared with --warnings all). What went wrong: a size too big for its type is converted without a word. How to avoid it: make the compiler refuse impossible values; the header now has static_assert(N > 0, ...), and the same build now stops with static assertion failed: RingLog capacity must be 1..255.
11. The sketch, and the memory budget
The sketch ties it together: the simulated world advances by the real time that passed, the scheduler runs the three robot tasks at 20 ms and a report task every 500 ms that writes to the log and to Serial.
// robot_ch1.ino -- Programming for Robotics with Arduino C++, chapter 1: a wall-stopping robot in a simulated world.
// Compile-checked for the Arduino Uno R3 (arduino:avr:uno). NOT run on a board: no board was attached.
#include "scheduler.h"
#include "log.h"
#include "robot.h"
// These checks cost nothing at run time: if the board's types are not what the chapter says, the build fails.
static_assert(sizeof(int) == 2, "int is 16 bits on an Uno");
static_assert(sizeof(void*) == 2, "a pointer is 16 bits on an Uno");
static_assert(sizeof(long) == 4, "long is 32 bits");
static_assert(sizeof(float) == 4, "float is 32 bits");
static_assert(sizeof(double) == 4, "double is the SAME as float on AVR");
static_assert(sizeof(long long) == 8, "long long is 64 bits");
static_assert(sizeof(LogEntry) == 8, "a log record is 8 bytes");
#ifndef LOGN
#define LOGN 16 // log capacity in records; change with -DLOGN=64 and watch the RAM figure
#endif
#ifndef VIRTUAL
#define VIRTUAL 0 // 1 = the hardware is reached through virtual functions
#endif
#if VIRTUAL
struct IHW { // an interface: every call goes through a table of function pointers
virtual float range_m() = 0;
virtual void drive(float v) = 0;
};
struct VSim : IHW {
SimHW w;
float range_m() override { return w.range_m(); }
void drive(float v) override { w.drive(v); }
};
static VSim hw;
static SimHW& world = hw.w;
typedef WallRobot<IHW> Robot;
#else
static SimHW hw(1.0f);
static SimHW& world = hw;
typedef WallRobot<SimHW> Robot;
#endif
static Robot robot(hw, 0.25f, 1.5f, 0.5f);
static Scheduler<4> sch;
static RingLog<LOGN> blackbox;
static uint32_t last_ms = 0;
static void report_task(void*, uint32_t now) {
blackbox.add(now, LOG_DEBUG, 1, (int16_t)(world.range_m() * 1000.0f)); // range in millimetres
Serial.print(now);
Serial.print(F(" ms range "));
Serial.print(world.range_m(), 3);
Serial.println(F(" m"));
}
void setup() {
Serial.begin(115200);
sch.add(Robot::sense_task, &robot, 20);
sch.add(Robot::think_task, &robot, 20);
sch.add(Robot::act_task, &robot, 20);
sch.add(report_task, 0, 500);
last_ms = millis();
}
void loop() {
uint32_t now = millis();
world.advance((now - last_ms) / 1000.0f); // the simulated world moves by the real time that passed
last_ms = now;
sch.run(now);
}
The compiler's report for the Uno, for different log sizes (-DLOGN=...), and for the virtual variant of section 8:
Build
Flash used (of 32,256)
RAM used by globals (of 2,048)
Left for the stack
16 records
4950 bytes (15 %)
473 bytes (23 %)
1575 bytes
64 records
4950 bytes
857 bytes (41 %)
1191 bytes
128 records
4950 bytes
1369 bytes (66 %)
679 bytes
192 records
5034 bytes
1881 bytes (91 %)
167 bytes
200 records
5034 bytes
1945 bytes (94 %)
103 bytes
256 records
refused by the static_assert (the earlier build was a log of 0 records)
One record costs exactly 8 bytes (857 - 473 over 48 more records) and everything else in the program costs 345. The “left for the stack” column is 2048 minus the globals, which is what is available; the stack's real depth was not measured, because the sketch was not run. RAM is the scarce thing: a program with a 64-record log already uses 41 % of the RAM, and the 200-record one leaves a hundred bytes for every function call, local variable and interrupt, with no warning from the compiler if it runs out. Flash is not scarce: the whole program is 15 %.
Every chapter of this course ends with such a table: the program's RAM, flash and time budget, from the tools, not from guesses. Time is the one this chapter can only model.
12. Running it on the real board
None of this was run on a board. To do it: connect the Uno, find its port with arduino-cli board list, then arduino-cli compile --fqbn arduino:avr:uno robot_ch1 and arduino-cli upload -p COM3 --fqbn arduino:avr:uno robot_ch1 (replace COM3 with the port found), and arduino-cli monitor -p COM3 -c baudrate=115200 to watch the report lines. You should see a line every 500 ms with the range falling toward 0.250 m, but that is what the code says it will do, not something that was observed: if the board's lines look different, treat that as a finding to investigate.
Challenges
Challenge 1: How many start times does the naive timer survive?
Run a 20 ms timer, polled every millisecond for 201 ms, starting 0 to 39 ms before the wrap of the counter, both with Periodic and with the naive now >= next version. For each start report the shortest and longest gap between runs, and count how many of the 40 starts each timer got wrong. A timer is right only if every gap is exactly 20 ms.
The stack needs at least 512 bytes of the Uno's 2048 free. From only two compiler reports (a log of 16 and a log of 64 records), predict the largest log that is allowed, then compile with that size and the sizes either side of it to check the prediction.
Run the wall robot (stop line 0.25 m, top speed 0.5 m/s, the wall at 1.037 m) at loop periods of 20, 100 and 500 ms and gains of 1.5, 5, 20 and 60 per second. For each pair report how many millimetres it ends past the stop line, and look for the number (gain × period) at which the problem starts.
Time.millis() wraps after 49.71 days, micros() after 71.58 minutes. Compare with now - then (unsigned), never now >= next. The naive timer failed for 37 of 40 start offsets, and when it works at all it can be by luck (6 ms before the wrap).
Rate.work(); delay(20): 428 passes in 10 s, intervals 21 to 26 ms. A Periodic(20) timer: 500 passes, exactly 20.00 ms.
Blocking. A delay(500) blink noticed a button after a mean of 496.1 ms and as much as 979 ms; a 10 ms poll, 3.6 ms and 9.
Scheduler. One 35 ms task in a 20 ms slot made sense run 27 times instead of 100 and made a 100 ms task start up to 30 ms late. Tasks must be short.
Virtual functions cost +52 bytes of flash and +10 of RAM here (compile-time). Templates cost nothing.
Log. 8 bytes a record; 148 records is the largest that leaves 512 bytes for the stack (the check at 149 left 511). A capacity of 256 in a uint8_t became 0 without a warning until the static_assert was added.
Loop speed. At 20 ms the robot is safe up to a gain of 20/s and goes 1.4 mm past the line at 60/s; at 100 ms it goes 13 mm past from 20/s; at 500 ms it goes 55.5 mm past at 5/s and 213 mm at 20/s.
Not run: the sketch on a board (no board attached); every timing here is a fake clock.
Next: Programming for Robotics with Arduino C++ 2, Talking to Hardware
Programming for Robotics with Arduino C++ 2 (planned; not yet written) leaves the simulated world: it reads real pins, drives motors with PWM, and reads sensors, and it takes the PinHW that replaces SimHW in this chapter's template, the same robot code running against real hardware.