Programming for Robotics with Arduino C++ 5 drove the robot with proportional controllers and ended each move with a steady error (a heading hold that left 41 mm of drift) and a turn tolerance chosen by hand. This chapter replaces them with a proper controller: a PID class whose integral does not wind up and whose derivative does not amplify noise, tuned on the simulator and then tried on a robot it was not tuned for, a cascaded position and speed loop, a heading hold that removes the steady error, and an integer version of the controller for a chip with no floating-point unit.
The chapter keeps the habit of the whole course: every claim about a controller is a number from running it, and the numbers are as often against the textbook as for it. The cascade, for instance, did not beat a single loop here, and the setting with the best score was the one that broke on a different robot.
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 challenge solutions, on the simulator of Programming for Robotics with Arduino C++ 3: a wheel that follows its command with a 0.1 s lag, an 8-bit duty, and a speed measured from the encoder ticks over 100 ms. The “other robots” (heavier, lighter, a weak motor) are assumptions I chose, not measurements.
Compiled for the Uno, not run (arduino-cli, core arduino:avr 1.8.8, --warnings all): robot_ch6.ino and the one-controller-at-a-time sketch. Flash and RAM are the compiler’s; the instruction counts come from avr-objdump.
Time per pass was not measured: no board was attached, so the chapter counts instructions and library calls instead of microseconds, and says so where it matters.
1. A PID class, and a rig to test it in
A PID controller turns an error (setpoint minus measurement) into an output as the sum of three terms: P, proportional to the error now; I, proportional to the error accumulated so far, which removes a steady error; and D, proportional to how fast the error is changing, which damps. Written once as a class, it can run a wheel speed, a heading and a distance. In Python the same class is a dozen lines; here the differences are that every number has a type and a cost, and that the sample time is a parameter, not something a thread supplies.
In Python
On the Uno in C++
pid = PID(1.5, 6, 0.05), state in an object
Pid pid(config); a struct of numbers; about 50 bytes of RAM per controller (sizeof is 52 on the PC)
dt = time.time() - last
dt is the fixed control period (0.02 s), passed in: the scheduler of Programming for Robotics with Arduino C++ 1 guarantees it
floats are free
each float add, multiply or divide is a library call; section 7 counts them
an unbounded integer cannot overflow
an integer integral is an int32_t with limits chosen on purpose, and with guard bits (section 7)
Here is the whole of it: the float Pid with a choice of anti-windup, a filtered derivative that can act on the measurement instead of the error, and two integer versions of a PI(D) that section 7 compares.
// pid.h -- control loops (Programming for Robotics with Arduino C++ 6). Plain C++11: no Arduino calls, no heap, no float library beyond + - * /.
// Pid is the float controller; PidFixed and PidFixedNaive are integer versions of the same PI(D) for a chip with no floating-point unit.
#pragma once
#include <stdint.h>
inline float pid_clamp(float v, float lo, float hi) { return v < lo ? lo : (v > hi ? hi : v); }
enum AntiWindup : uint8_t { AW_NONE = 0, AW_CLAMP = 1, AW_BACKCALC = 2 };
struct PidConfig {
float kp, ki, kd; // proportional (output per unit error), integral (per unit error per second), derivative (per unit rate, in seconds)
float out_min, out_max; // the output the actuator can really take
float d_tau; // time constant (s) of the low-pass filter on the derivative; 0 = no filter
bool d_on_measurement; // true: differentiate the measurement, so a setpoint step does not kick the output
AntiWindup aw; // what to do with the integral while the output is saturated
float kb; // back-calculation gain (1/s), used by AW_BACKCALC
};
class Pid {
public:
explicit Pid(const PidConfig& c) : c_(c), i_(0.0f), d_f_(0.0f), prev_e_(0.0f), prev_m_(0.0f), first_(true) {}
void reset() { i_ = 0.0f; d_f_ = 0.0f; first_ = true; }
float update(float setpoint, float measurement, float dt) {
float e = setpoint - measurement;
if (first_) { prev_e_ = e; prev_m_ = measurement; first_ = false; }
float d_raw = c_.d_on_measurement ? -(measurement - prev_m_) / dt : (e - prev_e_) / dt;
if (c_.d_tau > 0.0f) d_f_ += (dt / (c_.d_tau + dt)) * (d_raw - d_f_); else d_f_ = d_raw;
prev_e_ = e; prev_m_ = measurement;
float p = c_.kp * e, d = c_.kd * d_f_;
float u = p + i_ + d;
float us = pid_clamp(u, c_.out_min, c_.out_max);
switch (c_.aw) {
case AW_NONE: i_ += c_.ki * e * dt; break; // keeps integrating while saturated: the integral "winds up"
case AW_CLAMP: if (!((u > c_.out_max && e > 0.0f) || (u < c_.out_min && e < 0.0f))) i_ += c_.ki * e * dt; break; // stop integrating while saturated and still pushing the same way
case AW_BACKCALC: i_ += (c_.ki * e + c_.kb * (us - u)) * dt; break; // pull the integral back by the amount the output was cut
}
return us;
}
float integral() const { return i_; }
private:
PidConfig c_;
float i_, d_f_, prev_e_, prev_m_;
bool first_;
};
// ---- the integer PI(D): error and output in the same small units (here mm/s), gains as scaled integers ----
// kp_q8 = Kp x 256, ki_dt_q16 = Ki x dt x 65536 (the integral gain already multiplied by the sample time), kd_q8 = Kd / dt x 256.
// The integral accumulator keeps 16 fractional bits ("guard bits"): rounding in the conversion cannot make it stall.
class PidFixed {
public:
PidFixed(int16_t kp_q8, int32_t ki_dt_q16, int16_t kd_q8, int16_t out_min, int16_t out_max)
: kp_(kp_q8), ki_(ki_dt_q16), kd_(kd_q8), lo_(out_min), hi_(out_max), acc_(0), prev_m_(0), first_(true) {}
int16_t update(int16_t setpoint, int16_t measurement) {
int32_t e = (int32_t)setpoint - measurement;
if (first_) { prev_m_ = measurement; first_ = false; }
int32_t p = (kp_ * e) >> 8;
int32_t d = -((int32_t)kd_ * (measurement - prev_m_)) >> 8;
prev_m_ = measurement;
acc_ += ki_ * e;
int32_t lo = (int32_t)lo_ * 65536L, hi = (int32_t)hi_ * 65536L;
if (acc_ > hi) acc_ = hi; else if (acc_ < lo) acc_ = lo; // clamp: the simplest anti-windup for an integer accumulator
int32_t u = p + d + (acc_ >> 16);
if (u > hi_) u = hi_; else if (u < lo_) u = lo_;
return (int16_t)u;
}
int32_t integral_q16() const { return acc_; }
private:
int16_t kp_; int32_t ki_; int16_t kd_; int16_t lo_, hi_;
int32_t acc_; int16_t prev_m_; bool first_;
};
// THE SAME WITHOUT GUARD BITS: the integral gain times the error is shifted down every step, so a small error adds nothing and the integral stalls (cf. the integer exponential filter of chapter 4).
class PidFixedNaive {
public:
PidFixedNaive(int16_t kp_q8, int16_t ki_dt_q8, int16_t out_min, int16_t out_max) : kp_(kp_q8), ki_(ki_dt_q8), lo_(out_min), hi_(out_max), i_(0) {}
int16_t update(int16_t setpoint, int16_t measurement) {
int32_t e = (int32_t)setpoint - measurement;
int32_t p = (kp_ * e) >> 8;
i_ += (ki_ * e) >> 8;
if (i_ > hi_) i_ = hi_; else if (i_ < lo_) i_ = lo_;
int32_t u = p + i_;
if (u > hi_) u = hi_; else if (u < lo_) u = lo_;
return (int16_t)u;
}
private:
int16_t kp_, ki_, lo_, hi_;
int32_t i_;
};
The experiments all run on one test rig: the simulator, a control step of 20 ms, and a speed estimate from the ticks over the last five control steps (100 ms). That estimate moves in steps of 5.76 mm/s and is on average 50 ms old, so the controller has to live with quantisation and delay, as a real one does.
// rig.h -- a test rig for speed and position loops on the simulator (HOST ONLY). One simulated robot with both wheels driven by the same command,
// a control step of 20 ms (20 simulator steps of 1 ms), and the measured speed taken from the encoder ticks over the last five control steps (100 ms): the resolution of
// that estimate is 5.76 mm/s and it is on average 50 ms old, which is what a real controller has to live with.
#pragma once
#include <cstdint>
#include <cmath>
#include "sim.h"
#include "motion.h"
struct SpeedRig {
SimHW w;
int32_t hist[6];
float pt;
explicit SpeedRig(const RobotParams& rp, uint32_t seed = 1) : w(rp, SensorParams(), Arena(), seed), pt((float)(2.0 * SIM_PI * rp.wheel_r / rp.ticks_per_rev)) {
for (int i = 0; i < 6; ++i) hist[i] = 0;
}
// one control step of 20 ms with both wheels commanded `left` and `right` (m/s)
void step(float left, float right) {
w.drive(left, right);
for (int k = 0; k < 20; ++k) w.step(0.001);
for (int i = 0; i < 5; ++i) hist[i] = hist[i + 1];
int32_t l, r; w.read_ticks(l, r);
hist[5] = l;
}
float speed() const { return (float)(hist[5] - hist[0]) * pt / 0.1f; } // measured speed of the left wheel (m/s)
double true_speed() const { return w.wheel_l(); }
float distance() const { int32_t l, r; w.read_ticks(l, r); return 0.5f * (float)(l + r) * pt; } // odometry distance of the centre
};
inline RobotParams default_robot() { RobotParams rp; rp.tau = 0.1; return rp; }
2. Integral windup
The integral term keeps adding while there is an error, and a motor has a limit: it cannot go faster than 0.5 m/s however large the command. If the setpoint is out of reach, the error stays large, the integral keeps growing, and when the setpoint finally comes back into reach the integral is still huge and holds the output at its limit long after the error has gone. That is windup. The experiment asks for 0.8 m/s (out of reach) for 1.5 s and then 0.2 m/s, with a PI controller (Kp 1.0, Ki 6.0), once with no protection, once stopping the integral while the output is saturated (clamping), and once with back-calculation, which pulls the integral back by the amount the output was cut:
// e_windup.cpp -- integral windup on a wheel speed loop (host build). PI controller (Kp 1.0, Ki 6.0 per second), output limited to the motor's 0.5 m/s.
// The setpoint is 0.8 m/s for 1.5 s (more than the motor can give), then 0.2 m/s for 3 s. The wheel follows its command with a 0.1 s lag; the speed is measured from the encoder.
#include <cstdio>
#include <cmath>
#include "rig.h"
#include "pid.h"
struct Out { double integral_at_drop, recover_s, speed_1s_after, undershoot; };
static Out run(AntiWindup aw, float ki) {
SpeedRig rig(default_robot());
PidConfig c = {1.0f, ki, 0.0f, 0.0f, 0.5f, 0.0f, true, aw, 8.0f};
Pid pid(c);
Out o = {0, -1, 0, 0};
const int hold = 75; // 1.5 s of 20 ms steps
for (int i = 0; i < 75 + 150; ++i) {
float sp = i < hold ? 0.8f : 0.2f;
if (i == hold) o.integral_at_drop = pid.integral();
float u = pid.update(sp, rig.speed(), 0.02f);
rig.step(u, u);
if (i >= hold) {
double t = (i - hold + 1) * 0.02;
if (o.recover_s < 0 && rig.true_speed() <= 0.22) o.recover_s = t;
if (std::fabs(t - 1.0) < 0.011) o.speed_1s_after = rig.true_speed();
if (rig.true_speed() < 0.2 - o.undershoot) o.undershoot = 0.2 - rig.true_speed();
}
}
return o;
}
int main() {
std::printf("setpoint 0.8 m/s (out of reach: the motor tops out at 0.5) for 1.5 s, then 0.2 m/s; PI, Kp 1.0, Ki 6.0, output limited to 0..0.5 m/s\n");
std::printf(" anti-windup integral when setpoint drops (m/s) time until speed <= 0.22 (s) speed 1 s after the drop (m/s) undershoot below 0.2 (m/s)\n");
const char* names[] = {"none", "clamp the integral", "back-calculation"};
for (int a = 0; a < 3; ++a) {
Out o = run((AntiWindup)a, 6.0f);
std::printf(" %-20s %34.2f %28.2f %30.3f %26.3f\n", names[a], o.integral_at_drop, o.recover_s, o.speed_1s_after, o.undershoot);
}
return 0;
}
setpoint 0.8 m/s (out of reach: the motor tops out at 0.5) for 1.5 s, then 0.2 m/s; PI, Kp 1.0, Ki 6.0, output limited to 0..0.5 m/s
anti-windup integral when setpoint drops (m/s) time until speed <= 0.22 (s) speed 1 s after the drop (m/s) undershoot below 0.2 (m/s)
none 3.18 1.98 0.500 0.001
clamp the integral 0.23 0.10 0.200 0.044
back-calculation 0.42 0.12 0.198 0.003
With no protection the integral reaches 3.18 (in m/s of output, six times the motor’s whole range), and after the setpoint drops to 0.2 the wheel is still at 0.500 m/s one second later; it takes 1.98 s to come back within 10 %. Clamping and back-calculation recover in 0.10 and 0.12 s. They are not the same: clamping stops the integral at 0.23 and then undershoots by 0.044 m/s, back-calculation leaves 0.42 in the integral and undershoots 0.003, because it cuts the integral only by what the saturation cut. Challenge 1 sweeps how long the setpoint was out of reach and how hard back-calculation should pull. The practical rule: every controller whose output is limited, which is every controller that drives a motor, needs one of these.
3. The derivative: kick and noise
The derivative term reacts to change, and there are two traps. First, if it differentiates the error, a step in the setpoint is a jump in the error and the derivative produces a huge one-step output, the kick. Differentiating the measurement instead gives the same damping without the kick, because the measurement cannot jump. Second, it amplifies noise: the speed measurement here moves in steps of 5.76 mm/s, and a step in 20 ms looks like a large rate. A low-pass filter on the derivative cuts that. The experiment steps the setpoint from 0.1 to 0.3 m/s at 1 s with Kd = 0.05 s:
// e_deriv.cpp -- the derivative term on a noisy, quantised speed measurement (host build). PID with Kp 1.5, Ki 6, Kd 0.05 s, integral clamp, on the wheel speed loop.
// The speed measure moves in steps of 5.76 mm/s (one tick over 100 ms) and each step is seen by the derivative as a jump in one 20 ms control period.
// Setpoint: 0.1 m/s for 1 s, then a step to 0.3 m/s. Measured: the command in the first 20 ms after the step (the kick; the limit is 0.5), the jitter of the command once settled
// (rms of its change from step to step over the last 2 s), and the overshoot of the true speed above 0.3.
#include <cstdio>
#include <cmath>
#include "rig.h"
#include "pid.h"
static void run(const char* name, float kd, bool on_meas, float tau) {
SpeedRig rig(default_robot());
PidConfig c = {1.5f, 6.0f, kd, 0.0f, 0.5f, tau, on_meas, AW_CLAMP, 8.0f};
Pid pid(c);
double first = 0, sq = 0, peak = 0; int n = 0; float prev_u = 0;
for (int i = 0; i < 300; ++i) {
float u = pid.update(i < 50 ? 0.1f : 0.3f, rig.speed(), 0.02f);
if (i == 50) first = u;
rig.step(u, u);
if (i >= 200) { double du = u - prev_u; sq += du * du; ++n; }
prev_u = u;
if (i >= 50 && rig.true_speed() > peak) peak = rig.true_speed();
}
std::printf(" %-34s %12.3f %20.2f %15.1f\n", name, first, std::sqrt(sq / n) * 1000.0, (peak - 0.3) / 0.3 * 100.0);
}
int main() {
std::printf("PID on a wheel speed loop, setpoint 0.1 -> 0.3 m/s at 1 s; Kd 0.05 s where used\n");
std::printf(" derivative command at step step-to-step jitter (mm/s) overshoot (%%)\n");
run("none (PI)", 0.0f, true, 0.0f);
run("on the error, unfiltered", 0.05f, false, 0.0f);
run("on the measurement, unfiltered", 0.05f, true, 0.0f);
run("on the measurement, filter 0.05 s", 0.05f, true, 0.05f);
run("on the measurement, filter 0.10 s", 0.05f, true, 0.10f);
return 0;
}
PID on a wheel speed loop, setpoint 0.1 -> 0.3 m/s at 1 s; Kd 0.05 s where used
derivative command at step step-to-step jitter (mm/s) overshoot (%)
none (PI) 0.400 3.89 0.6
on the error, unfiltered 0.500 14.68 1.4
on the measurement, unfiltered 0.378 17.01 1.4
on the measurement, filter 0.05 s 0.402 6.37 0.8
on the measurement, filter 0.10 s 0.402 5.97 0.6
The kick is plain: the derivative on the error drives the command to 0.500 (the limit) in the first step after the setpoint changes, where the plain PI gives 0.400 and the derivative on the measurement 0.378. The jitter of the settled command (its step-to-step change) is 3.89 mm/s for the PI and 17.01 mm/s with an unfiltered derivative: four times as much, from noise alone. A filter of 0.05 s brings it to 6.37. And look at what the derivative buys here: the overshoot of the true speed is 0.6 % without it and 1.4 % with it unfiltered. For a speed loop on a first-order motor the derivative adds noise and gains nothing; the cases where it earns its place (a position loop, section 5) have an extra lag to damp. Challenge 2 sweeps the filter.
4. Tuning in the simulator, and the robot you did not tune for
The simulator is where tuning is cheap, and the experiment below does it the plain way: a grid of Kp and Ki for the speed PI, scored by the IAE (the area between setpoint and true speed; smaller is better) and the overshoot, on a step from 0 to 0.3 m/s. Then the best setting is tried on two other robots, a heavier one with weaker motors and a lighter one with stronger motors (both assumed), as a stand-in for the step from the simulator to the hardware:
// e_tune.cpp -- tuning a wheel speed PI in the simulator, then trying it on a robot that is not the one it was tuned on (host build; the "other robot" is an ASSUMED change).
// Step 0 -> 0.3 m/s, 4 s, integral clamp. Score: IAE, the area between the setpoint and the TRUE speed (m/s x s; smaller is better), and the overshoot of the true speed.
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "rig.h"
#include "pid.h"
struct Score { double iae, over; };
static Score run(float kp, float ki, const RobotParams& rp) {
SpeedRig rig(rp);
PidConfig c = {kp, ki, 0.0f, 0.0f, 0.5f, 0.0f, true, AW_CLAMP, 8.0f};
Pid pid(c);
Score s = {0, 0}; double peak = 0;
for (int i = 0; i < 200; ++i) {
float u = pid.update(0.3f, rig.speed(), 0.02f);
rig.step(u, u);
s.iae += std::fabs(0.3 - rig.true_speed()) * 0.02;
if (rig.true_speed() > peak) peak = rig.true_speed();
}
s.over = (peak - 0.3) / 0.3 * 100.0;
return s;
}
int main() {
RobotParams nominal = default_robot();
std::printf("grid on the nominal robot (lag 0.1 s): IAE (m/s x s) / overshoot (%%)\n");
std::printf(" Kp / Ki 2 5 10 20\n");
double best_iae = 1e9, best_kp = 0, best_ki = 0, any_iae = 1e9, any_kp = 0, any_ki = 0;
for (float kp : {0.5f, 1.0f, 2.0f, 4.0f, 8.0f}) {
std::printf(" %8.1f", kp);
for (float ki : {2.0f, 5.0f, 10.0f, 20.0f}) {
Score s = run(kp, ki, nominal);
std::printf(" %6.3f/%5.1f", s.iae, s.over);
if (s.iae < any_iae) { any_iae = s.iae; any_kp = kp; any_ki = ki; }
if (s.over <= 10.0 && s.iae < best_iae) { best_iae = s.iae; best_kp = kp; best_ki = ki; }
}
std::printf("\n");
}
std::printf("lowest IAE of all: Kp %.1f, Ki %.0f (%.3f); lowest IAE with overshoot of at most 10 %%: Kp %.1f, Ki %.0f (%.3f)\n", any_kp, any_ki, any_iae, best_kp, best_ki, best_iae);
RobotParams heavy = default_robot(); heavy.tau = 0.2; heavy.gain_l = heavy.gain_r = 0.8; // a heavier robot with motors 20 % weaker: ASSUMED
RobotParams light = default_robot(); light.tau = 0.05; light.gain_l = light.gain_r = 1.25; // a lighter robot with motors 25 % stronger: ASSUMED
std::printf("\nthe lowest-IAE setting and a gentler one on three robots, IAE / overshoot:\n");
std::printf(" setting nominal heavy, weak motors light, strong motors\n");
for (int k = 0; k < 2; ++k) {
float kp = k == 0 ? (float)any_kp : 1.0f, ki = k == 0 ? (float)any_ki : 5.0f;
Score a = run(kp, ki, nominal), b = run(kp, ki, heavy), c = run(kp, ki, light);
std::printf(" Kp %.1f, Ki %2.0f %6.3f / %5.1f %6.3f / %5.1f %6.3f / %5.1f\n", kp, ki, a.iae, a.over, b.iae, b.over, c.iae, c.over);
}
(void)best_kp; (void)best_ki; (void)best_iae;
return 0;
}
grid on the nominal robot (lag 0.1 s): IAE (m/s x s) / overshoot (%)
Kp / Ki 2 5 10 20
0.5 0.129/ -0.0 0.040/ 0.4 0.047/ 28.7 0.109/ 37.2
1.0 0.127/ -0.4 0.040/ 0.5 0.022/ 13.3 0.043/ 31.8
2.0 0.137/ -1.8 0.057/ 0.6 0.029/ 0.6 0.020/ 7.5
4.0 0.127/ 14.5 0.071/ 14.5 0.053/ 14.5 0.062/ 14.9
8.0 0.253/ 23.9 0.245/ 25.5 0.241/ 27.3 0.235/ 26.9
lowest IAE of all: Kp 2.0, Ki 20 (0.020); lowest IAE with overshoot of at most 10 %: Kp 2.0, Ki 20 (0.020)
the lowest-IAE setting and a gentler one on three robots, IAE / overshoot:
setting nominal heavy, weak motors light, strong motors
Kp 2.0, Ki 20 0.020 / 7.5 0.036 / 5.5 0.091 / 45.6
Kp 1.0, Ki 5 0.040 / 0.5 0.055 / 0.2 0.030 / 1.7
The lowest IAE in the grid is Kp 2, Ki 20 (0.020, with 7.5 % overshoot), and it is the best of 20 settings. On the heavy robot it still works (0.036, 5.5 %). On the light robot, whose motors are stronger and quicker, it overshoots by 45.6 % and its IAE is 4.5 times worse: the loop gain went up by 25 % and the lag went down, and a setting tuned to the edge of stability on the first robot is over the edge on the second. The gentler Kp 1, Ki 5 scores twice the IAE on the nominal robot (0.040) and holds on all three (overshoots of 0.5, 0.2 and 1.7 %). The lesson is about what to optimise: a controller that will be moved to hardware should be tuned for margin (an overshoot well under the limit, a setting in the middle of a flat region of the grid), then checked on the perturbed plants, not for the best score on the one model.
The grid also shows a feature of this loop that a tidy theory would not predict: at Kp 4 the overshoot is 14.5 % whatever Ki is, and at Kp 8 it is 24–27 %. That is the 50 ms delay of the speed estimate: past some Kp the loop is fighting a measurement that is half a tick old. The simulator knows about the delay because the rig puts it there; a simulator that measured the speed directly would not have shown this.
5. Cascaded loops: do they help?
A distance move can be one loop, a PID on the distance that commands the wheels directly, or a cascade: an outer loop on the distance whose output is the setpoint of an inner speed loop, which is the PI of section 4. The textbook arguments for the cascade are that each loop is simple and fast, the inner loop hides the motor from the outer one, and a limit on the speed is one clamp. The experiment drives 1 m both ways, single loop with a filtered derivative and cascade with a proportional outer loop, and scores the true distance:
// e_cascade.cpp -- driving 1 m: one position loop that commands the motor directly, against a position loop that commands a SPEED loop (host build; same robot, same limits).
// Single loop: PID on the distance (Kd 0.3 s on the measurement, filtered 0.05 s), output = wheel speed command limited to +-0.4 m/s.
// Cascade: outer proportional loop on the distance gives a speed setpoint (limited to +-0.4 m/s); inner PI (Kp 1.0, Ki 5.0, tuned in e_tune) turns it into the command.
// Scored on the TRUE distance (the simulator's own position): overshoot, and the time after which it stays within 5 mm of 1 m (never = still outside at 8 s).
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "rig.h"
#include "pid.h"
struct R { double over_mm, settle_s, peak_v; };
static R score(SpeedRig& rig, double peak_v, double over, double last_outside) { (void)rig; R r; r.over_mm = over; r.settle_s = last_outside; r.peak_v = peak_v; return r; }
static R single(float kp, const RobotParams& rp = default_robot()) {
SpeedRig rig(rp);
PidConfig c = {kp, 0.0f, 0.3f, -0.4f, 0.4f, 0.05f, true, AW_CLAMP, 8.0f};
Pid pid(c);
double over = 0, peak_v = 0, last_out = 0;
for (int i = 0; i < 400; ++i) {
float u = pid.update(1.0f, rig.distance(), 0.02f);
rig.step(u, u);
double x = rig.w.x - 0.3;
if ((x - 1.0) * 1000 > over) over = (x - 1.0) * 1000;
if (rig.true_speed() > peak_v) peak_v = rig.true_speed();
if (std::fabs(x - 1.0) > 0.005) last_out = (i + 1) * 0.02;
}
return score(rig, peak_v, over, last_out);
}
static R cascade(float kp_pos, const RobotParams& rp = default_robot()) {
SpeedRig rig(rp);
PidConfig inner_c = {1.0f, 5.0f, 0.0f, -0.4f, 0.4f, 0.0f, true, AW_CLAMP, 8.0f};
Pid inner(inner_c);
double over = 0, peak_v = 0, last_out = 0;
for (int i = 0; i < 400; ++i) {
float v_sp = pid_clamp(kp_pos * (1.0f - rig.distance()), -0.4f, 0.4f);
float u = inner.update(v_sp, rig.speed(), 0.02f);
rig.step(u, u);
double x = rig.w.x - 0.3;
if ((x - 1.0) * 1000 > over) over = (x - 1.0) * 1000;
if (rig.true_speed() > peak_v) peak_v = rig.true_speed();
if (std::fabs(x - 1.0) > 0.005) last_out = (i + 1) * 0.02;
}
return score(rig, peak_v, over, last_out);
}
int main() {
std::printf("a 1 m move: overshoot of the true distance (mm), time to stay within 5 mm (s; 8.00 = never), peak wheel speed (m/s)\n");
std::printf(" loop overshoot mm settled at (s) peak speed\n");
for (float kp : {2.0f, 4.0f, 8.0f}) { R r = single(kp); std::printf(" single position PID, Kp %-4.1f %12.1f %14.2f %10.2f\n", kp, r.over_mm, r.settle_s, r.peak_v); }
for (float kp : {1.0f, 2.0f, 4.0f}) { R r = cascade(kp); std::printf(" cascade, outer Kp %-4.1f %12.1f %14.2f %10.2f\n", kp, r.over_mm, r.settle_s, r.peak_v); }
RobotParams heavy = default_robot(); heavy.tau = 0.2; heavy.gain_l = heavy.gain_r = 0.8; // heavier, motors 20 % weaker: ASSUMED
RobotParams light = default_robot(); light.tau = 0.05; light.gain_l = light.gain_r = 1.25; // lighter, motors 25 % stronger: ASSUMED
std::puts(""); std::printf("the same two settings (single Kp 4.0; cascade outer Kp 2.0) on other robots: overshoot mm / settled at s"); std::puts("");
std::printf(" robot single loop cascade"); std::puts("");
const char* names[] = {"nominal", "heavy, weak motors", "light, strong motors"};
RobotParams robots[] = {default_robot(), heavy, light};
for (int k = 0; k < 3; ++k) {
R a = single(4.0f, robots[k]), b = cascade(2.0f, robots[k]);
std::printf(" %-22s %7.1f / %5.2f %7.1f / %5.2f", names[k], a.over_mm, a.settle_s, b.over_mm, b.settle_s); std::puts("");
}
return 0;
}
a 1 m move: overshoot of the true distance (mm), time to stay within 5 mm (s; 8.00 = never), peak wheel speed (m/s)
loop overshoot mm settled at (s) peak speed
single position PID, Kp 2.0 0.0 4.18 0.40
single position PID, Kp 4.0 0.0 3.04 0.40
single position PID, Kp 8.0 2.3 2.64 0.40
cascade, outer Kp 1.0 0.0 5.16 0.40
cascade, outer Kp 2.0 2.6 3.22 0.40
cascade, outer Kp 4.0 9.4 3.50 0.40
the same two settings (single Kp 4.0; cascade outer Kp 2.0) on other robots: overshoot mm / settled at s
robot single loop cascade
nominal 0.0 / 3.04 2.6 / 3.22
heavy, weak motors 3.3 / 3.52 2.3 / 3.72
light, strong motors 0.0 / 2.58 1.2 / 3.32
On this plant the cascade did not help. The single loop with Kp 4 reaches 1 m with no overshoot in 3.04 s; the cascade’s best settings overshoot 2.6 mm and settle at 3.22 s, and with the outer Kp at 4 it overshoots 9.4 mm. On the other robots the two are within a few millimetres of each other, and the single loop settles up to 0.7 s sooner. What the table does support is the safe-speed argument: both loops are clamped at 0.4 m/s and both reached it. What it does not test is the argument that the inner loop absorbs a change in the motor (a flat battery, a heavier load) while the outer loop is untouched; the simulator runs with fixed parameters, so a mid-move disturbance was not tried. I would not choose a cascade because a book does; I would choose it when the speed loop is needed anyway, as it is for the wheel speeds of Programming for Robotics with Arduino C++ 5 and the heading hold of section 6.
6. Heading hold
Programming for Robotics with Arduino C++ 5 left a P-only heading hold with 41 mm of drift and −2.6°: a proportional controller against a steady disturbance (the weak right motor) always leaves a steady error. The integral term removes it. The experiment drives straight for 4 s (1.6 m) at 0.4 m/s with the right motor 5 % weak, on the odometry heading, and scores the true end state:
// e_heading.cpp -- holding a heading while driving straight at 0.4 m/s for 4 s (1.6 m), with a right motor 5 % weak (ASSUMED), on the odometry heading (host build).
// The heading comes from the encoders: (right ticks - left ticks) x per_tick / track, exact radius and track. The controller turns the robot back toward heading 0:
// the output is a turn rate (limited to +-1.5 rad/s) that is split across the wheels. Scored on the TRUE heading and sideways position at the end, and the largest sideways excursion.
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "rig.h"
#include "pid.h"
static void run(const char* name, float kp, float ki, float kd) {
RobotParams rp = default_robot(); rp.gain_r = 0.95;
SpeedRig rig(rp);
PidConfig c = {kp, ki, kd, -1.5f, 1.5f, 0.05f, true, AW_CLAMP, 8.0f};
Pid pid(c);
const float track = (float)rp.track;
double worst = 0;
for (int i = 0; i < 200; ++i) {
int32_t l, r; rig.w.read_ticks(l, r);
float th = (float)(r - l) * rig.pt / track;
float w = pid.update(0.0f, th, 0.02f);
const float v = 0.4f;
rig.step(v - 0.5f * w * track, v + 0.5f * w * track);
double lat = (rig.w.y - 1.0) * 1000;
if (std::fabs(lat) > worst) worst = std::fabs(lat);
}
std::printf(" %-26s %17.2f %17.1f %17.1f\n", name, rig.w.th * 180 / SIM_PI, (rig.w.y - 1.0) * 1000, worst);
}
int main() {
std::printf("straight 1.6 m with the right motor 5 %% weak; true values at the end\n");
std::printf(" heading controller heading (deg) sideways (mm) worst sideways (mm)\n");
run("none (open loop)", 0.0f, 0.0f, 0.0f);
run("P only, Kp 3", 3.0f, 0.0f, 0.0f);
run("PI, Kp 3, Ki 1", 3.0f, 1.0f, 0.0f);
run("PI, Kp 3, Ki 3", 3.0f, 3.0f, 0.0f);
run("PI, Kp 3, Ki 8", 3.0f, 8.0f, 0.0f);
run("PID, Kp 3, Ki 3, Kd 0.2", 3.0f, 3.0f, 0.2f);
return 0;
}
straight 1.6 m with the right motor 5 % weak; true values at the end
heading controller heading (deg) sideways (mm) worst sideways (mm)
none (open loop) -29.80 -386.8 386.8
P only, Kp 3 -2.70 -66.5 66.5
PI, Kp 3, Ki 1 -0.76 -39.6 39.6
PI, Kp 3, Ki 3 -0.03 -17.8 17.8
PI, Kp 3, Ki 8 0.10 -6.4 8.2
PID, Kp 3, Ki 3, Kd 0.2 -0.03 -18.0 18.0
Open loop the robot ends 387 mm to the side at −29.8°. P only leaves −2.70° and 66.5 mm (similar to the P-only hold of Programming for Robotics with Arduino C++ 5, which left −2.6° and 41 mm on a 1 m move). Adding Ki = 1 gives −0.76°, Ki = 3 gives −0.03° and 17.8 mm, Ki = 8 gives 0.10° and 8.2 mm worst excursion. The integral removes the heading error but not the sideways drift already built up while it was catching up, which is why the position error falls more slowly than the heading error. The derivative (Kd = 0.2) changes nothing visible here, as in section 3.
7. A PID with integers
On a chip with no floating-point unit a float PI is expensive, and PidFixed in the header is the integer alternative: error and output in the same small units (mm/s), the gains as scaled integers (Kp×256, Ki×dt×65536), and an integral accumulator that keeps 16 fractional bits. The accumulator clamp is the anti-windup. The variant PidFixedNaive does what looks natural, shifting the product down each step, and it has the same bug as the integer exponential filter of Programming for Robotics with Arduino C++ 4: a small error adds nothing, and the integral stalls. The experiment runs the three on the speed loop for 20 s:
// e_fixed.cpp -- the same speed PI in float, in integers with guard bits, and in integers without (host build). Speed in mm/s, step 0 -> 300 mm/s, Kp 1.5, output 0..500 mm/s.
// Scored by the TRUE speed: mean error over the last 2 s of a 20 s run, and (against the float controller) the largest difference between commands over the whole run.
#include <cstdio>
#include <cmath>
#include <vector>
#include <initializer_list>
#include "rig.h"
#include "pid.h"
struct R { double err_mm_s; std::vector<float> cmd; };
enum Kind { FLOAT, FIXED, NAIVE };
static R run(Kind kind, float ki) {
SpeedRig rig(default_robot());
PidConfig c = {1.5f, ki, 0.0f, 0.0f, 0.5f, 0.0f, true, AW_CLAMP, 8.0f};
Pid pf(c);
PidFixed px((int16_t)std::lround(1.5 * 256), (int32_t)std::lround(ki * 0.02 * 65536), 0, 0, 500);
PidFixedNaive pn((int16_t)std::lround(1.5 * 256), (int16_t)std::lround(ki * 0.02 * 256), 0, 500);
R r; r.err_mm_s = 0; int n = 0;
for (int i = 0; i < 1000; ++i) {
float m = rig.speed();
float u;
if (kind == FLOAT) u = pf.update(0.3f, m, 0.02f);
else {
int16_t meas = (int16_t)std::lround(m * 1000.0f);
int16_t out = kind == FIXED ? px.update(300, meas) : pn.update(300, meas);
u = out / 1000.0f;
}
r.cmd.push_back(u);
rig.step(u, u);
if (i >= 900) { r.err_mm_s += (0.3 - rig.true_speed()) * 1000.0; ++n; }
}
r.err_mm_s /= n;
return r;
}
int main() {
std::printf("speed PI, 20 s; steady error = mean of (300 - true speed) in mm/s over the last 2 s; diff = largest difference of the command from the float controller's (mm/s)\n");
std::printf(" Ki (1/s) float: error guard bits: error diff no guard bits: error diff\n");
for (float ki : {5.0f, 1.0f, 0.3f}) {
R f = run(FLOAT, ki), x = run(FIXED, ki), nv = run(NAIVE, ki);
double dx = 0, dn = 0;
for (size_t i = 0; i < f.cmd.size(); ++i) { dx = std::fmax(dx, std::fabs(f.cmd[i] - x.cmd[i]) * 1000); dn = std::fmax(dn, std::fabs(f.cmd[i] - nv.cmd[i]) * 1000); }
std::printf(" %8.1f %12.2f %17.2f %4.1f %20.2f %4.1f\n", ki, f.err_mm_s, x.err_mm_s, dx, nv.err_mm_s, dn);
}
return 0;
}
speed PI, 20 s; steady error = mean of (300 - true speed) in mm/s over the last 2 s; diff = largest difference of the command from the float controller's (mm/s)
Ki (1/s) float: error guard bits: error diff no guard bits: error diff
5.0 -0.02 -0.44 30.0 5.29 30.0
1.0 0.13 -0.42 17.5 44.57 60.5
0.3 11.91 12.00 18.2 116.49 117.2
With Ki = 5 the float and guard-bit controllers end within 0.5 mm/s of the setpoint; the controller without guard bits ends 5.29 mm/s off. With Ki = 1 the float controller ends 0.13 mm/s off, the guard-bit one −0.42, and the controller without guard bits 44.57 mm/s off: the product of Ki×dt (a count of 5 in Q8) and a small error shifts down to zero, and the integral stops. With Ki = 0.3 it is 116.49 mm/s off, against 11.91 for the float (which is only slow to converge; its time constant is long). The two integer controllers differ from the float one by up to 30 mm/s in the command, but that is a transient: the measurement is rounded to whole millimetres per second and the rounding changes the path a little; the end values agree. Challenge 3 finds how many fractional bits the integral gain needs: with 4 bits Ki = 1 rounds to a count of zero and the integral does nothing at all (a steady error of 120.55 mm/s, exactly the P-only value), and 12 bits get the gain to within 2 %.
What does the integer controller save? The two versions were compiled alone into a sketch that reads A0 and prints the command (the first row is the sketch without a controller), and the machine code of the update function was read with avr-objdump:
arduino-cli compile --fqbn arduino:avr:uno --warnings all -DVARIANT_x s_pid
(whole sketch; "base" only reads A0 and prints it; the update function is noinline and its machine code was read with avr-objdump)
variant flash bytes RAM bytes adds flash adds RAM instructions in update library calls in update
base (no controller) 1890 188 0 0
PI in float (Pid) 4130 265 2240 77 350 27 (7 mul, 6 add, 5 sub, 7 compare, 2 div)
PI in integers (PidFixed) 2496 207 606 19 167 3 (all integer multiplies)
(the instruction counts are of all the code in the function, not of one pass through it; no time was measured)
The float PI costs 2240 bytes of flash and 77 of RAM and its update function is 350 instructions with 27 calls into the float library; the integer one costs 606 and 19, with 167 instructions and 3 calls (all integer multiplications). That is the bill in space and in work; the bill in time is not in the table because no time was measured. Each of those 27 calls runs a subroutine of many instructions, but how many microseconds a pass takes, and whether it matters at a 20 ms period, is a measurement that needs the board. Counting calls tells you where to look first, not how long it takes.
8. The whole controller, and the budget
robot_ch6.ino puts it together: an outer proportional loop on the distance gives a speed setpoint, a heading PI gives a turn rate that is split across the wheels, and each wheel has its own speed PI. The gains are the ones the simulator chose (the speed PI of section 4, the heading PI of section 6, an outer Kp of 2).
// robot_ch6.ino -- Programming for Robotics with Arduino C++, chapter 6: a 1 m move with a position loop, a speed PI on each wheel and a heading PI.
// Compile-checked for the Uno (arduino:avr:uno). NOT run on a board: no board, motor or encoder was attached; every gain below comes from the SIMULATOR (e_tune, e_heading).
#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 "pid.h"
const float V_MAX_MPS = 0.5f;
const uint8_t DEAD_DUTY = 40; // ASSUMED: measure yours (Programming for Robotics with Arduino C++ 5, challenge 3)
const float WHEEL_R = 0.033f, TRACK = 0.150f; // replace by the calibrated values
const float PER_TICK = 6.2831853f * WHEEL_R / 360.0f; // 360 counts per turn (2x decoding of a 180-slot disc)
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 read_ticks(int32_t& l, int32_t& r) { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { l = g_ticks_l; r = g_ticks_r; } }
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));
}
// one speed loop per wheel: speed from the ticks over the last five control steps (100 ms), then a PI with the integral clamped
struct WheelLoop {
Pid pid;
int32_t hist[6];
WheelLoop() : pid({1.0f, 5.0f, 0.0f, -0.4f, 0.4f, 0.0f, true, AW_CLAMP, 8.0f}) { for (uint8_t i = 0; i < 6; ++i) hist[i] = 0; }
float update(float sp, int32_t ticks) {
for (uint8_t i = 0; i < 5; ++i) hist[i] = hist[i + 1];
hist[5] = ticks;
float speed = (float)(hist[5] - hist[0]) * PER_TICK / 0.1f;
return pid.update(sp, speed, 0.02f);
}
};
static WheelLoop left_loop, right_loop;
static Pid heading_pid({3.0f, 3.0f, 0.0f, -1.5f, 1.5f, 0.05f, true, AW_CLAMP, 8.0f}); // Kp 3, Ki 3 as in e_heading
static Scheduler<3> sch;
static bool moving = true;
static float g_dist = 0.0f, g_head = 0.0f;
static void control_task(void*, uint32_t) {
int32_t l, r; read_ticks(l, r);
g_dist = 0.5f * (float)(l + r) * PER_TICK;
g_head = (float)(r - l) * PER_TICK / TRACK;
if (!moving) { drive(0.0f, 0.0f); return; }
float v_sp = pid_clamp(2.0f * (1.0f - g_dist), -0.4f, 0.4f); // outer loop: a proportional position loop (outer Kp 2, as in e_cascade)
float w = heading_pid.update(0.0f, g_head, 0.02f); // heading hold: a turn rate, split across the wheels
float vl = left_loop.update(v_sp - 0.5f * w * TRACK, l);
float vr = right_loop.update(v_sp + 0.5f * w * TRACK, r);
drive(vl, vr);
if (g_dist > 0.995f && g_dist < 1.005f && fabsf(v_sp) < 0.02f) moving = false;
}
static void report_task(void*, uint32_t) {
Serial.print(F("dist ")); Serial.print(g_dist, 3); Serial.print(F(" m heading ")); Serial.print(g_head, 3); Serial.println(F(" rad"));
}
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);
sch.add(control_task, 0, 20);
sch.add(report_task, 0, 500);
}
void loop() { sch.run(millis()); }
It compiles for the Uno with no warnings under --warnings all to 7638 bytes of flash (23 %) and 541 bytes of RAM (26 %): smaller than Programming for Robotics with Arduino C++ 5’s sketch in flash (it has no Mover and no sinf) and 132 bytes larger in RAM (three Pid objects and two histories). It was not run. The same controller, with the same gains and steps, was run on the simulator:
// e_compose.cpp -- the whole controller of robot_ch6.ino on the simulator: position P (Kp 2) -> speed setpoints, a speed PI on each wheel, a heading PI (Kp 3, Ki 3) splitting a turn rate across the wheels.
// Same gains, same 20 ms step, same 100 ms speed estimate as the sketch. A 1 m move, run for 8 s; the TRUE end state is printed. (The sketch itself was compiled for the Uno, not run.)
#include <cstdio>
#include <cmath>
#include "rig.h"
#include "pid.h"
static void run(const char* name, const RobotParams& rp) {
SpeedRig rig(rp);
PidConfig sc = {1.0f, 5.0f, 0.0f, -0.4f, 0.4f, 0.0f, true, AW_CLAMP, 8.0f};
Pid left(sc), right(sc);
PidConfig hc = {3.0f, 3.0f, 0.0f, -1.5f, 1.5f, 0.05f, true, AW_CLAMP, 8.0f};
Pid heading(hc);
int32_t hl[6] = {0}, hr[6] = {0};
const float track = 0.150f; // what the code believes; the simulator's robot has the same
double done_at = -1;
bool moving = true;
for (int i = 0; i < 400; ++i) {
int32_t l, r; rig.w.read_ticks(l, r);
float dist = 0.5f * (float)(l + r) * rig.pt, head = (float)(r - l) * rig.pt / track;
for (int k = 0; k < 5; ++k) { hl[k] = hl[k + 1]; hr[k] = hr[k + 1]; }
hl[5] = l; hr[5] = r;
float sl = (float)(hl[5] - hl[0]) * rig.pt / 0.1f, sr = (float)(hr[5] - hr[0]) * rig.pt / 0.1f;
if (!moving) { rig.step(0, 0); continue; }
float v_sp = pid_clamp(2.0f * (1.0f - dist), -0.4f, 0.4f);
float w = heading.update(0.0f, head, 0.02f);
float vl = left.update(v_sp - 0.5f * w * track, sl, 0.02f);
float vr = right.update(v_sp + 0.5f * w * track, sr, 0.02f);
rig.step(vl, vr);
if (dist > 0.995f && dist < 1.005f && std::fabs(v_sp) < 0.02f) { moving = false; done_at = (i + 1) * 0.02; }
}
std::printf(" %-26s %12.4f %12.1f %12.2f %10.2f\n", name, rig.w.x - 0.3, (rig.w.y - 1.0) * 1000, rig.w.th * 180 / SIM_PI, done_at);
}
int main() {
RobotParams weak = default_robot(); weak.gain_r = 0.95;
RobotParams heavy = default_robot(); heavy.tau = 0.2; heavy.gain_l = heavy.gain_r = 0.8;
std::printf("a 1 m move with the controller of robot_ch6.ino; true end state\n");
std::printf(" robot distance (m) sideways (mm) heading (deg) done at (s)\n");
run("nominal", default_robot());
run("right motor 5 % weak", weak);
run("heavy, motors 20 % weaker", heavy);
return 0;
}
a 1 m move with the controller of robot_ch6.ino; true end state
robot distance (m) sideways (mm) heading (deg) done at (s)
nominal 0.9992 0.0 0.00 3.26
right motor 5 % weak 0.9989 -23.2 3.28 3.34
heavy, motors 20 % weaker 1.0035 0.0 0.00 3.76
On the nominal robot the 1 m move ends 0.9992 m out, straight, in 3.26 s. With the right motor 5 % weak it ends 0.9989 m out but 23.2 mm to the side with a heading of 3.28°, which is not what the heading hold of section 6 promised. Printing the trace explains it: during the cruise the heading drifts to −2.9° and the integral builds up to correct it; the move then slows toward the end, the integral that was right at 0.4 m/s is too much at 0.05 m/s, the heading swings through zero to +3.7°, and the move ends (the stop condition looks at the distance and the speed setpoint, not the heading) before it settles. The integral time constant, Kp/Ki = 1 s, is long for a move of 3 s. Either a longer straight, a heading integral that is reset or frozen when the speed setpoint falls, or a stop condition that also waits for the heading, would help; I did not try them. This is the kind of thing a simulator is for: it found a failure of a plan that looked finished.
9. What the numbers can and cannot be trusted for
What they show. The shapes: an unprotected integral winds up (3.18 in the integral, 1.98 s to recover) and clamping or back-calculation fixes it; a derivative of the error kicks and an unfiltered one multiplies the noise by four and bought nothing on a first-order plant; the best-scoring tuning broke on a lighter robot; the cascade was no better than a single loop; the integral removes a steady heading error but needs time; an integer integral without guard bits stalls. The flash, RAM and instruction counts are the compiler’s for the real chip.
What they do not show. The plants (lag, gains, delay) and the “other robots” are assumptions: real motors have a dead zone, a stiction threshold, a battery that sags and a gearbox with backlash, none of which the loop here has met. The cascade was tested on fixed parameters, so its disturbance-rejection argument is untested. No time per pass was measured, so the cost of float is known in space and in library calls and not in microseconds. Every gain in robot_ch6.ino came from the simulator, and a real robot needs them re-tuned by the procedure of section 4: start gentle, raise Kp until it just starts to ring, back off, add Ki, and test on a perturbed setup before trusting it.
Challenge 1: The price of windup
Sweep how long the setpoint stays out of reach (0.25, 0.5, 1 and 2 s) and measure how long the true speed takes to return to within 10 % of 0.2 m/s, for no anti-windup, clamping, and back-calculation with gains of 1, 4, 8 and 20 per second. Explain why the unprotected recovery time grows with the time out of reach, and what happens to back-calculation when kb is too small.
Sweep the time constant of the derivative’s filter from 0 to 0.5 s on the speed PID of section 3 (derivative on the measurement) and print the command jitter, the overshoot and the 90 % rise time. Choose a value and say what you give up for it, and why the rise-time column is not a clean trend.
Write an integer PI whose integral gain has F fractional bits. For Ki of 1.0 and 0.3 per second and F of 4, 6, 8, 10, 12 and 16, print the gain it actually implements (as a percentage of the wanted one) and the steady speed error after 30 s. Find the smallest F for each Ki, and say what goes wrong at the bottom of the table.
Windup. Unprotected integral 3.18 after 1.5 s out of reach; 1.98 s to recover, still 0.500 m/s a second later. Clamp 0.10 s (undershoot 0.044), back-calculation 0.12 s (0.003). Every limited output needs one.
Derivative. On the error it kicks the command to the limit (0.500); on the measurement 0.378. Unfiltered it gives 17.01 mm/s of jitter against 3.89 for the PI; a 0.05 s filter 6.37. On a first-order speed loop it bought nothing (overshoot 0.6 % without, 1.4 % with).
Tuning. Best IAE on the model: Kp 2, Ki 20 (0.020, 7.5 %); on a lighter robot 45.6 % overshoot, IAE 0.091. Gentler Kp 1, Ki 5: 0.040 and under 2 % on all three. Tune for margin, then test on perturbed plants. Kp past about 4 hits the 50 ms measurement delay.
Cascade. Single loop Kp 4: 0.0 mm overshoot, 3.04 s. Cascade outer Kp 2: 2.6 mm, 3.22 s. No benefit found; the disturbance argument was not tested.
Heading hold. 1.6 m with a 5 % weak motor: open loop −29.8°, 387 mm; P −2.70°, 66.5 mm; PI Ki 3 −0.03°, 17.8 mm. The integral needs time: in the 1 m move of robot_ch6.ino it overshoots to +3.28° at the stop.
Integer PI. Guard bits (Q16 accumulator): error −0.42 mm/s at Ki 1; without them 44.57. At 4 fractional bits Ki 1 rounds to a count of 0 and the integral is dead (120.55 mm/s). 12 bits: within 2 % of the gain.
Cost. Float PI +2240 bytes flash, +77 RAM, 350 instructions, 27 float-library calls; integer PI +606, +19, 167 instructions, 3 integer multiplies. Time per pass: not measured.
Not run: anything on a board; every plant parameter and every gain comes from the simulator.
Next: Programming for Robotics with Arduino C++ 7, State Machines and Behaviours
Programming for Robotics with Arduino C++ 7 (planned; not yet written) gives the robot something to decide: enum class states and switch, table-driven machines with function pointers, timers and time-outs, and line-follower, obstacle-avoider and wall-follower behaviours built on the moves and controllers of this chapter, tested on the host before they are tried on the board, with the transition table held in flash or static memory instead of a heap.