Course 2 · Chapter 5 · Driving: Motors and Odometry
Programming for Robotics with Arduino C++ 4 ended with a counter that is correct: an interrupt routine that counts each wheel’s ticks, read atomically. This chapter uses those counts to make the robot move: a command that does not slam the motors, a wheel speed worked out from the ticks, a pose (x, y and heading) integrated from them, and two moves, straight and turn-by-angle, that end where they were told to. The theme is the one the course started with, the budget: what float costs on a chip with no floating-point hardware, and what the integer alternative costs in code and care.
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. The simulator’s wheels have a 0.1 s lag, an 8-bit duty and exact ticks; the dead zone, the weak motor, and the wheel-radius and track errors used for calibration are assumptions I chose, not measurements of any motor.
Compiled for the Uno, not run (arduino-cli, core arduino:avr 1.8.8, --warnings all, no warnings from this chapter’s code): the one-update-at-a-time sketch and robot_ch5.ino. Flash and RAM figures are the compiler’s. No time per update was measured: nothing here was timed on a board.
No board, motor or encoder was attached.
1. Ramps, limits and the dead zone
A controller that asks for 0.5 m/s at the instant it starts is asking a motor and a set of wheels for an acceleration they may not be able to give: the wheels slip, the supply sags, and the odometry (which assumes the wheels grip) goes wrong from the first centimetre. A ramp limits how fast a command may change. A limit clamps it. And a dead zone is the opposite problem at the other end: below some duty the motor does not turn at all, so a small command does nothing, and the robot sits still and then lurches. Here is the code of the chapter in one header, with its first pieces: Ramp, and speed_to_pwm_dz, which maps a speed to duty counts from just above the dead zone up to 255.
// motion.h -- driving a two-wheel robot (Programming for Robotics with Arduino C++ 5). Plain C++11: no Arduino calls, no heap.
// Ramp, motor command with a dead zone, two ways to turn encoder counts into a speed, and the odometry pose update in three integrators.
#pragma once
#include <stdint.h>
#include <math.h>
#include "conv.h"
inline float clampf(float v, float lo, float hi) { return v < lo ? lo : (v > hi ? hi : v); }
// ---- ramp: the command may change by at most `accel` units per second ----
class Ramp {
public:
explicit Ramp(float accel) : a_(accel), v_(0.0f) {}
float step(float target, float dt) { float m = a_ * dt; v_ += clampf(target - v_, -m, m); return v_; }
float value() const { return v_; }
void reset(float v = 0.0f) { v_ = v; }
private:
float a_, v_;
};
// ---- a motor command that knows about the dead zone: duty `dead` is the highest that does not move the wheel, so speed v > 0 maps to dead+1 .. 255 ----
inline uint8_t speed_to_pwm_dz(float v, float vmax, uint8_t dead) {
if (v <= 0.0f) return 0;
if (v >= vmax) return 255;
return (uint8_t)((float)dead + 1.0f + (254.0f - (float)dead) * v / vmax + 0.5f);
}
// ---- wheel speed, method 1: ticks counted over a fixed window. Resolution = one tick per window; fine when fast, coarse when slow. ----
class SpeedWindow {
public:
SpeedWindow(float per_tick_m) : pt_(per_tick_m), last_ticks_(0), last_us_(0), v_(0.0f), first_(true) {}
float update(int32_t ticks, uint32_t now_us) {
if (first_) { last_ticks_ = ticks; last_us_ = now_us; first_ = false; return 0.0f; }
uint32_t dt = now_us - last_us_;
if (dt == 0) return v_;
v_ = (float)(ticks - last_ticks_) * pt_ / ((float)dt * 1.0e-6f);
last_ticks_ = ticks; last_us_ = now_us;
return v_;
}
private:
float pt_; int32_t last_ticks_; uint32_t last_us_; float v_; bool first_;
};
// ---- wheel speed, method 2: the time between the last two ticks. Finer when slow; needs a timestamp for every tick (taken in the interrupt). ----
class SpeedPeriod {
public:
SpeedPeriod(float per_tick_m, uint32_t timeout_us) : pt_(per_tick_m), timeout_(timeout_us), t_prev_(0), t_last_(0), dir_(0), n_(0) {}
void on_tick(int8_t dir, uint32_t t_us) { t_prev_ = t_last_; t_last_ = t_us; dir_ = dir; if (n_ < 2) ++n_; }
float speed(uint32_t now_us) const {
if (n_ < 2 || now_us - t_last_ > timeout_) return 0.0f; // no recent tick: stopped (or slower than the timeout allows)
return (float)dir_ * pt_ / ((float)(t_last_ - t_prev_) * 1.0e-6f);
}
private:
float pt_; uint32_t timeout_, t_prev_, t_last_; int8_t dir_; uint8_t n_;
};
// ---- the pose update from one step of the wheels: distance d travelled by the centre and heading change dth (both in the same step) ----
struct Pose { float x, y, th; };
inline void pose_euler(Pose& p, float d, float dth) { p.x += d * cosf(p.th); p.y += d * sinf(p.th); p.th += dth; } // the heading from the START of the step
inline void pose_midpoint(Pose& p, float d, float dth) { float m = p.th + 0.5f * dth; p.x += d * cosf(m); p.y += d * sinf(m); p.th += dth; } // the heading half way
inline void pose_arc(Pose& p, float d, float dth) { // the exact circular arc
if (fabsf(dth) < 1.0e-6f) { pose_midpoint(p, d, dth); return; }
float r = d / dth;
p.x += r * (sinf(p.th + dth) - sinf(p.th));
p.y -= r * (cosf(p.th + dth) - cosf(p.th));
p.th += dth;
}
// ---- straight and turn-by-angle moves, on odometry. HW needs read_ticks() and drive() only. ----
struct MoveConfig {
float wheel_r, track; // metres: the ROBOT'S belief, which calibration corrects
int ticks_per_rev;
float vmax, accel; // cruise speed (m/s) and the ramp on the forward speed (m/s^2)
float k_dist; // forward speed per metre still to go (1/s)
float k_head; // heading hold during a straight move: turn rate per radian of error (1/s); 0 switches it off
float wmax, alpha, k_turn, wmin; // turning: top rate (rad/s), ramp (rad/s^2), rate per radian still to go (1/s), the smallest rate that is not stuck (rad/s)
float tol_m, tol_rad; // a move is done when this close
};
template <class HW>
class Mover {
public:
enum Mode : uint8_t { IDLE, STRAIGHT, TURN };
Mover(HW& hw, const MoveConfig& c) : hw_(hw), c_(c), vr_(c.accel), wr_(c.alpha), mode_(IDLE), first_(true), tl_(0), tr_(0),
p_{0.0f, 0.0f, 0.0f}, trav_(0.0f), target_(0.0f), start_(0.0f), th_ref_(0.0f) {}
void straight(float dist_m) { mode_ = STRAIGHT; start_ = trav_; target_ = dist_m; th_ref_ = p_.th; }
void turn(float rad) { mode_ = TURN; target_ = p_.th + rad; }
bool done() const { return mode_ == IDLE; }
void update(float dt) {
int32_t l, r; hw_.read_ticks(l, r);
if (first_) { tl_ = l; tr_ = r; first_ = false; }
const float pt = 6.2831853f * c_.wheel_r / (float)c_.ticks_per_rev;
float dl = (float)(l - tl_) * pt, dr = (float)(r - tr_) * pt;
tl_ = l; tr_ = r;
float d = 0.5f * (dl + dr), dth = (dr - dl) / c_.track;
pose_midpoint(p_, d, dth);
trav_ += d;
float v = 0.0f, w = 0.0f;
if (mode_ == STRAIGHT) {
float rem = target_ - (trav_ - start_);
if (fabsf(rem) < c_.tol_m && fabsf(vr_.value()) < 0.02f) { mode_ = IDLE; vr_.reset(); wr_.reset(); }
else {
v = vr_.step(clampf(c_.k_dist * rem, -c_.vmax, c_.vmax), dt);
w = -c_.k_head * (p_.th - th_ref_) * (fabsf(v) / c_.vmax);
}
} else if (mode_ == TURN) {
float rem = target_ - p_.th;
if (fabsf(rem) < c_.tol_rad && fabsf(wr_.value()) < 0.05f) { mode_ = IDLE; vr_.reset(); wr_.reset(); }
else {
float want = clampf(c_.k_turn * rem, -c_.wmax, c_.wmax);
if (fabsf(rem) >= c_.tol_rad && fabsf(want) < c_.wmin) want = rem > 0 ? c_.wmin : -c_.wmin;
if (fabsf(rem) < c_.tol_rad) want = 0.0f;
w = wr_.step(want, dt);
}
}
hw_.drive(v - 0.5f * w * c_.track, v + 0.5f * w * c_.track);
}
const Pose& pose() const { return p_; }
float travelled() const { return trav_; }
private:
HW& hw_;
MoveConfig c_;
Ramp vr_, wr_;
Mode mode_;
bool first_;
int32_t tl_, tr_;
Pose p_;
float trav_, target_, start_, th_ref_;
};
The experiment first drives the simulated wheel through chapter 2’s plain speed_to_pwm and through the dead-zone version, with an assumed dead duty of 40 (the motor turns only above it, and speed rises linearly to 0.5 m/s at 255). Then it compares a step command with the same command through a ramp:
// e_motor.cpp -- two things between the controller and the wheels: the dead zone and the ramp (host build; both motors are MODELS).
// Part 1: the motors do not turn at duty <= 40 (an ASSUMED dead zone); above it speed rises linearly to 0.5 m/s at 255. Commands through chapter 2's speed_to_pwm and through speed_to_pwm_dz.
// Part 2: a command that steps 0 -> 0.5 m/s against the same command through a Ramp; the wheel follows with a 0.1 s lag.
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "sim.h"
#include "motion.h"
int main() {
std::printf("steady wheel speed after 2 s for a commanded speed, dead zone at duty 40 (m/s); vmax 0.5\n");
std::printf(" commanded plain: duty actual error %% with dead zone: duty actual error %%\n");
for (double v : {0.005, 0.02, 0.05, 0.1, 0.2, 0.4}) {
double got[2]; int duty[2];
for (int k = 0; k < 2; ++k) {
RobotParams rp; rp.dead_duty = 40; rp.tau = 0.05;
SensorParams sp; Arena arena;
SimHW w(rp, sp, arena, 1);
// the simulator quantises through speed_to_pwm itself, so for the compensated command we hand it the speed that makes speed_to_pwm produce the wanted duty
uint8_t d = k == 0 ? speed_to_pwm((float)v, 0.5f) : speed_to_pwm_dz((float)v, 0.5f, 40);
duty[k] = d;
w.drive((float)(d / 255.0 * 0.5), (float)(d / 255.0 * 0.5));
for (int i = 0; i < 2000; ++i) w.step(0.001);
got[k] = w.wheel_l();
}
std::printf(" %9.3f %11d %6.3f %7.0f %20d %6.3f %7.1f\n", v, duty[0], got[0], 100 * (got[0] - v) / v, duty[1], got[1], 100 * (got[1] - v) / v);
}
std::printf("\na step of 0.5 m/s against a ramp (wheel lag 0.1 s):\n");
std::printf(" command peak wheel acceleration (m/s^2) time to 95 %% of speed (s) distance in that time (m)\n");
for (double accel : {0.0, 2.0, 1.0, 0.5}) {
RobotParams rp; rp.tau = 0.10; rp.pwm_quantise = false;
SensorParams sp; Arena arena;
SimHW w(rp, sp, arena, 1);
Ramp ramp((float)accel);
double prev = 0, peak = 0, t95 = -1, d95 = 0, x0 = w.x;
for (int i = 1; i <= 4000; ++i) {
float cmd = accel == 0.0 ? 0.5f : ramp.step(0.5f, 0.001f);
w.drive(cmd, cmd);
w.step(0.001);
double a = (w.wheel_l() - prev) / 0.001; prev = w.wheel_l();
if (a > peak) peak = a;
if (t95 < 0 && w.wheel_l() >= 0.475) { t95 = i * 0.001; d95 = w.x - x0; }
}
if (accel == 0.0) std::printf(" step ");
else std::printf(" ramp %.1f m/s^2 ", accel);
std::printf("%29.2f %25.3f %26.3f\n", peak, t95, d95);
}
return 0;
}
steady wheel speed after 2 s for a commanded speed, dead zone at duty 40 (m/s); vmax 0.5
commanded plain: duty actual error % with dead zone: duty actual error %
0.005 3 0.000 -100 43 0.007 39.5
0.020 10 0.000 -100 50 0.023 16.3
0.050 26 0.000 -100 62 0.051 2.3
0.100 51 0.026 -74 84 0.102 2.3
0.200 102 0.144 -28 127 0.202 1.2
0.400 204 0.381 -5 212 0.400 -0.0
a step of 0.5 m/s against a ramp (wheel lag 0.1 s):
command peak wheel acceleration (m/s^2) time to 95 % of speed (s) distance in that time (m)
step 5.00 0.299 0.102
ramp 2.0 m/s^2 1.84 0.448 0.115
ramp 1.0 m/s^2 0.99 0.637 0.147
ramp 0.5 m/s^2 0.50 1.068 0.237
With the plain mapping nothing below 0.1 m/s works: 0.005, 0.02 and 0.05 m/s all produce a duty of 26 or less, inside the dead zone, so the wheel does not turn (error −100 %), and 0.1 m/s gives 0.026 m/s, 74 % short. The dead-zone mapping puts them within 2.3 % from 0.05 m/s up. At the bottom it is not perfect: 0.005 m/s reads 39.5 % high, because one duty step is (0.5 − 0) / (255 − 40) = 2.3 mm/s, so the slowest steady speed is about 2.3 mm/s and a command below that is rounded up to it. The 40 is an assumption; a real motor’s dead zone depends on the supply voltage, the load and the gearbox, and has to be found by driving it (challenge 3).
The ramp table shows what a ramp costs and buys. A step to 0.5 m/s makes the wheel’s own lag the only limit: the peak acceleration is 5.00 m/s² and 95 % of the speed is reached in 0.299 s. A ramp of 1.0 m/s² keeps the peak at 0.99 m/s² and takes 0.637 s; of 0.5 m/s² takes 1.068 s. Whether 5 m/s² makes the wheels slip depends on the floor and the wheels, which the simulator does not model; the ramp is how you stay below the limit once you have found it.
2. From counts to wheel speed
The counter says how far the wheel has gone; a speed controller needs how fast it is going. There are two ways to get a speed from ticks. Counting over a window takes the difference of the count over a fixed time: SpeedWindow. Its resolution is one tick per window, so with 0.576 mm per tick and a window of 20 ms the smallest step in speed it can see is 28.8 mm/s. Timing the ticks takes the time between the last two: SpeedPeriod. Its resolution is the clock’s, but it needs a timestamp for every tick, taken in the interrupt routine, and it must decide what to say when no tick has come lately. The experiment holds the wheel at a constant true speed:
// e_speed.cpp -- turning encoder counts into a wheel speed, two ways, on a wheel turning at a constant true speed (host build).
// 360 ticks per turn, wheel radius 0.033 m: one tick is 0.576 mm. The simulated clock steps by 20 us (micros() on the Uno counts in 4 us steps, so this is a little COARSER than the board).
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "sim.h"
#include "motion.h"
struct Err { double sq = 0; int n = 0, zeros = 0; void add(double e, bool zero) { sq += e * e; ++n; if (zero) ++zeros; } double rms() const { return std::sqrt(sq / n); } };
int main() {
std::printf("true speed held constant for 3 s; rms error of the speed estimate in mm/s (and how often the 20 ms window said 0)\n");
std::printf(" true m/s ms between ticks window 20 ms zeros of 20 ms window 100 ms period of two ticks\n");
for (double v : {0.01, 0.02, 0.05, 0.1, 0.2, 0.5}) {
RobotParams rp; rp.tau = 0.0; rp.pwm_quantise = false;
SensorParams sp; Arena arena;
SimHW w(rp, sp, arena, 1);
const float pt = (float)(2.0 * SIM_PI * rp.wheel_r / rp.ticks_per_rev);
SpeedWindow w20(pt), w100(pt);
SpeedPeriod per(pt, 200000);
Err e20, e100, ep;
int32_t last_l = 0;
const uint32_t dt_us = 20;
w.drive((float)v, (float)v);
for (uint32_t us = dt_us; us <= 3000000; us += dt_us) {
w.step(dt_us * 1e-6);
int32_t l, r; w.read_ticks(l, r);
if (l != last_l) { per.on_tick(l > last_l ? 1 : -1, us); last_l = l; }
if (us % 20000 == 0) {
float s20 = w20.update(l, us);
if (us > 1000000) e20.add((s20 - v) * 1000.0, s20 == 0.0f);
float sp_ = per.speed(us);
if (us > 1000000) ep.add((sp_ - v) * 1000.0, false);
}
if (us % 100000 == 0) { float s100 = w100.update(l, us); if (us > 1000000) e100.add((s100 - v) * 1000.0, false); }
}
std::printf(" %8.2f %16.1f %12.2f %14d %13.2f %19.2f\n", v, pt / v * 1000.0, e20.rms(), e20.zeros, e100.rms(), ep.rms());
}
return 0;
}
true speed held constant for 3 s; rms error of the speed estimate in mm/s (and how often the 20 ms window said 0)
true m/s ms between ticks window 20 ms zeros of 20 ms window 100 ms period of two ticks
0.01 57.6 13.74 65 2.50 0.00
0.02 28.8 13.20 30 2.88 0.00
0.05 11.5 12.63 0 2.64 0.02
0.10 5.8 14.37 0 2.75 0.05
0.20 2.9 6.84 0 2.64 0.01
0.50 1.2 13.82 0 2.30 4.36
At 0.01 m/s a tick comes every 57.6 ms, so a 20 ms window sees no tick at all 65 times in 100 and one tick the rest, and the estimate flips between 0 and 28.8 mm/s: an rms error of 13.74 mm/s on a speed of 10. The period method is exact there (error 0.00). At 0.5 m/s the picture reverses a little: ticks are 1.2 ms apart, the 20 µs clock of this simulation is 1.7 % of that, and the period method’s error is 4.36 mm/s (0.9 %), against 13.82 for the window. (The simulation’s clock step is coarser than the Uno’s 4 µs micros(), so this overstates the period method’s error on the board.) The price of a longer window is delay: a window of 100 ms reads 2.5 mm/s rms error at 0.01 m/s, but its value is on average 50 ms old, which matters to a speed controller. Challenge 1 maps all of this.
3. Odometry: from ticks to a pose
Each control step the code turns the tick differences of the two wheels into the distance d moved by the centre and the heading change Δθ, and adds them to the pose. The question is which heading to move along while the heading is itself changing. Three answers, in increasing cost: Euler uses the heading at the start of the step; midpoint uses the heading half way through (as drive.h does); the exact arc uses the closed form for a circular arc. A fourth, in section 5, uses integers. The test drives two laps of a tight arc (radius 0.225 m, 1.67 rad/s) at several update intervals and compares the final pose with the simulator’s truth:
// e_odom.cpp -- the same encoder counts through four odometry updates, on a tight arc (host build; the simulator's wheels are ideal and the robot's wheel radius and track are exact,
// so what is left is the error of the update rule itself and of the tick quantisation).
// Path: left wheel 0.25 m/s, right wheel 0.5 m/s: an arc of radius 0.225 m at 1.667 rad/s, two full laps (7.54 s; the run is 7.6 s). The truth is the simulator's pose.
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "sim.h"
#include "motion.h"
#include "fixed.h"
struct R { double pos_mm, head_deg; };
template <int METHOD>
static R run(int interval_ms) {
RobotParams rp; rp.tau = 0.0; rp.pwm_quantise = false;
SensorParams sp; Arena arena;
SimHW w(rp, sp, arena, 1);
const float pt = (float)(2.0 * SIM_PI * rp.wheel_r / rp.ticks_per_rev);
Pose p = {0.0f, 0.0f, 0.0f};
OdomFixed fx((int32_t)std::lround(pt * 1e6 / 2.0 * 256.0), (int32_t)std::lround(pt / rp.track * 65536.0 / (2.0 * SIM_PI) * 65536.0));
int32_t pl = 0, pr = 0;
fx.update(0, 0); // the baseline: the counts at the start
w.drive(0.25f, 0.5f);
const int total_ms = 7600; // a multiple of every update interval, so the last update lands exactly on the end
for (int ms = 1; ms <= total_ms; ++ms) {
for (int k = 0; k < 10; ++k) w.step(0.0001);
if (ms % interval_ms == 0) {
int32_t l, r; w.read_ticks(l, r);
if (METHOD == 3) fx.update(l, r);
else {
float dl = (float)(l - pl) * pt, dr = (float)(r - pr) * pt;
float d = 0.5f * (dl + dr), dth = (dr - dl) / (float)rp.track;
if (METHOD == 0) pose_euler(p, d, dth); else if (METHOD == 1) pose_midpoint(p, d, dth); else pose_arc(p, d, dth);
}
pl = l; pr = r;
}
}
double ox, oy, oth;
if (METHOD == 3) { ox = fx.p.x_um * 1e-6; oy = fx.p.y_um * 1e-6; oth = fx.p.th * 2.0 * SIM_PI / 65536.0; }
else { ox = p.x; oy = p.y; oth = p.th; }
double ex = ox - (w.x - 0.3), ey = oy - (w.y - 1.0);
double eth = std::remainder(oth - w.th, 2.0 * SIM_PI);
R r; r.pos_mm = std::sqrt(ex * ex + ey * ey) * 1000.0; r.head_deg = eth * 180.0 / SIM_PI;
return r;
}
int main() {
std::printf("two laps of a radius-0.225 m arc: position error (mm) / heading error (degrees) of the odometry at the end, by update interval\n");
std::printf(" interval Euler (start heading) midpoint (half heading) exact arc fixed point (integers)\n");
for (int ms : {10, 20, 50, 100, 200}) {
R a = run<0>(ms), b = run<1>(ms), c = run<2>(ms), d = run<3>(ms);
std::printf(" %5d ms %9.1f / %6.2f %10.2f / %6.2f %8.2f / %6.2f %10.2f / %6.2f\n", ms, a.pos_mm, a.head_deg, b.pos_mm, b.head_deg, c.pos_mm, c.head_deg, d.pos_mm, d.head_deg);
}
return 0;
}
two laps of a radius-0.225 m arc: position error (mm) / heading error (degrees) of the odometry at the end, by update interval
interval Euler (start heading) midpoint (half heading) exact arc fixed point (integers)
10 ms 0.5 / 0.03 0.45 / 0.03 0.45 / 0.03 0.94 / 0.03
20 ms 0.6 / 0.03 0.45 / 0.03 0.45 / 0.03 0.68 / 0.03
50 ms 1.0 / 0.03 0.46 / 0.03 0.47 / 0.03 0.54 / 0.03
100 ms 2.2 / 0.03 0.36 / 0.03 0.37 / 0.03 0.42 / 0.03
200 ms 3.9 / 0.03 0.16 / 0.03 0.16 / 0.03 185.22 / 0.03
The first thing to see is the floor: every method has 0.45 mm of position error at 10 ms and 0.03° of heading error at every interval, and these are the encoder’s quantisation (a tick is 0.576 mm) rather than anything in the update rule. Euler is a little worse (0.5 mm at 10 ms) and degrades as the interval grows: 1.0 mm at 50 ms, 3.9 mm at 200 ms, while midpoint and exact arc stay under 0.5 mm. Midpoint and exact arc agree to within 0.02 mm at every interval, so the exact arc, which costs 318 more bytes of flash (section 5), buys nothing here. Choose midpoint. The conclusion has a limit: the heading came from exact tick counts, so the only error was in where along the arc the step was taken; a real robot’s error is dominated by slip and by the calibration of section 6.
4. Why float heading drifts
The pose update adds a small number to a large one: th += dth. A float has 24 bits of precision, so the spacing between neighbouring floats grows with the number: about 0.0039 near 32768, and near 6 about 5 × 10-7. Every addition is rounded to a multiple of that spacing, and when the step is the same every time the rounding is the same every time, so it does not average out. This experiment adds 0.02 rad (1 rad/s at 50 Hz) to a heading that is kept three ways and compares each with the truth, computed in double:
// e_float.cpp -- adding small heading changes to a float heading, for a long time (host build; float is 32-bit here as on the Uno).
// A robot turning at 1 rad/s with an update every 20 ms adds dth = 0.02 rad each step. The true heading after N steps is N * 0.02 (computed in double).
// Four ways to keep the heading: a float that grows forever, a float wrapped into (-pi, pi], a uint16 binary angle, and a double for reference.
#include <cstdio>
#include <cmath>
#include <cstdint>
#include <initializer_list>
int main() {
const double TWO_PI = 6.283185307179586;
const float dth = 0.02f;
float grow = 0.0f, wrap = 0.0f;
uint16_t bam = 0; const uint16_t dbam = (uint16_t)std::lround(0.02 / TWO_PI * 65536.0); // 209 units per step: 0.02 rad rounded to the unit
std::printf("heading after N updates of 0.02 rad (1 rad/s at 50 Hz); error = estimate - truth, in degrees, compared modulo one turn\n");
std::printf(" updates time float, never wrapped float, wrapped to +-pi uint16 binary angle\n");
long n = 0;
for (long target : {1000L, 10000L, 100000L, 1000000L, 10000000L}) {
for (; n < target; ++n) {
grow += dth;
wrap += dth; if (wrap > 3.14159265f) wrap -= 6.2831853f;
bam = (uint16_t)(bam + dbam);
}
double truth = std::fmod(0.02 * (double)target, TWO_PI);
auto err = [&](double est) { double e = std::remainder(est - truth, TWO_PI); return e * 180.0 / 3.14159265358979; };
double t_s = target / 50.0;
std::printf(" %8ld %5.1f h %20.4f %22.4f %19.4f\n", target, t_s / 3600.0, err(std::fmod((double)grow, TWO_PI)), err((double)wrap), err(bam * TWO_PI / 65536.0));
}
std::printf("the 'never wrapped' heading itself ends at %.1f rad (truth %.1f rad)\n", (double)grow, 0.02 * 1.0e7);
std::printf("one unit of the binary angle is %.4f degrees; 209 units per step is %.6f rad against 0.02 (a %.3f %% error in the rate)\n", 360.0 / 65536.0, 209 * TWO_PI / 65536.0, (209 * TWO_PI / 65536.0 / 0.02 - 1) * 100);
return 0;
}
heading after N updates of 0.02 rad (1 rad/s at 50 Hz); error = estimate - truth, in degrees, compared modulo one turn
updates time float, never wrapped float, wrapped to +-pi uint16 binary angle
1000 0.0 h 0.0153 -0.0009 2.1557
10000 0.1 h 0.3383 -0.0091 21.5570
100000 0.6 h 76.2079 -0.0907 -144.4301
1000000 5.6 h 35.7660 -0.9073 -4.3012
10000000 55.6 h 72.7898 -9.0731 -43.0120
the 'never wrapped' heading itself ends at 191361.9 rad (truth 200000.0 rad)
one unit of the binary angle is 0.0055 degrees; 209 units per step is 0.020038 rad against 0.02 (a 0.188 % error in the rate)
A heading that is never wrapped is off by 76° after 100,000 updates (33 minutes of turning at 1 rad/s) and ends at 191,362 rad when the truth is 200,000: 4.3 % short, and the error is not random, it is rate error from rounding. Wrapping the angle into (−π, π] keeps the numbers small and cuts the error by a factor of about 800, to −0.09° after the same 100,000 updates, but it still drifts (−9.07° after 10 million). The third column, a uint16_t binary angle, looks worse (2.16° after 1000 updates, 21.6° after 10,000), and the reason is a lesson of its own: it adds 209 units per step, which is 0.02 rad rounded to the unit, a 0.19 % error in the rate, and that error accumulates exactly like the float’s. Section 5 and challenge 2 show the cure: do not add steps, compute the heading from the exact integer tick count.
5. Odometry in integers
The Uno has no floating-point unit, so every float add, multiply and divide is a call to a library routine, and sinf and cosf are the heaviest of them. fixed.h does the update with integers only. The heading is a uint16_t in binary angle units (65,536 to the turn): it wraps by itself, with no wrap code, and its resolution is 0.0055°. The position is in micrometres in an int32_t. The sine comes from a 65-entry quarter-wave table in Q15 (15 fractional bits) with linear interpolation. The design point worth remembering is the one from section 4: the heading is computed from the total difference of the tick counts, so rounding in the conversion cannot accumulate; the distance keeps its rounding remainder and carries it into the next step.
// fixed.h -- the odometry update with integers only (Programming for Robotics with Arduino C++ 5): no float, no sinf, no cosf.
// Heading is a uint16_t in binary angle units (65536 per turn): it wraps by itself, so there is no wrap-around code and no float to lose precision.
// Position is in micrometres (int32_t: good to +-2147 m). sin/cos come from a 65-entry quarter-wave table in Q15 with linear interpolation.
#pragma once
#include <stdint.h>
// sin(pi/2 * i/64) * 32767, i = 0..64
static const int16_t SIN_Q15[65] = {
0, 804, 1608, 2410, 3212, 4011, 4808, 5602, 6393, 7179, 7962, 8739, 9512, 10278, 11039, 11793,
12539, 13279, 14010, 14732, 15446, 16151, 16846, 17530, 18204, 18868, 19519, 20159, 20787, 21403, 22005, 22594,
23170, 23731, 24279, 24811, 25329, 25832, 26319, 26790, 27245, 27683, 28105, 28510, 28898, 29268, 29621, 29956,
30273, 30571, 30852, 31113, 31356, 31580, 31785, 31971, 32137, 32285, 32412, 32521, 32609, 32678, 32728, 32757,
32767 };
inline int16_t sin_q15(uint16_t a) { // a: 0..65535 = 0..2 pi; result -32767..32767
uint8_t quad = (uint8_t)(a >> 14);
uint16_t r = a & 0x3FFF;
if (quad & 1) r = (uint16_t)(0x4000 - r); // mirror in the odd quadrants
uint8_t i = (uint8_t)(r >> 8), frac = (uint8_t)r;
int32_t lo = SIN_Q15[i], hi = SIN_Q15[i + 1 > 64 ? 64 : i + 1];
int16_t v = (int16_t)(lo + (((hi - lo) * frac) >> 8));
return (quad & 2) ? (int16_t)-v : v;
}
inline int16_t cos_q15(uint16_t a) { return sin_q15((uint16_t)(a + 0x4000)); }
struct PoseFixed { int32_t x_um, y_um; uint16_t th; };
// One step. dist_um = distance of the centre in micrometres, dth = heading change in binary angle units (signed). Midpoint rule, as in pose_midpoint.
inline void pose_fixed(PoseFixed& p, int32_t dist_um, int16_t dth) {
uint16_t mid = (uint16_t)(p.th + (uint16_t)(dth / 2));
p.x_um += (dist_um * cos_q15(mid)) >> 15; // 32-bit product: fine while |dist_um| <= 65,535 (65 mm per step)
p.y_um += (dist_um * sin_q15(mid)) >> 15;
p.th = (uint16_t)(p.th + (uint16_t)dth);
}
// Odometry from cumulative encoder counts, integers only. The heading is computed from the TOTAL difference of the counts (not added up step by step),
// so rounding in the conversion cannot accumulate; the distance keeps its rounding remainder and carries it into the next step.
// k_dist_q8 = (micrometres per tick / 2) * 256 (the centre moves by half the sum of the two wheels)
// k_ang_q16 = (binary angle units per tick of difference) * 65536 = (per_tick / track) * 65536 / (2 pi) * 65536
class OdomFixed {
public:
OdomFixed(int32_t k_dist_q8, int32_t k_ang_q16) : kd_(k_dist_q8), ka_(k_ang_q16), tl0_(0), tr0_(0), tl_(0), tr_(0), rem_(0), first_(true) { p.x_um = 0; p.y_um = 0; p.th = 0; }
void update(int32_t tl, int32_t tr) {
if (first_) { tl0_ = tl_ = tl; tr0_ = tr_ = tr; first_ = false; return; }
int32_t dl = tl - tl_, dr = tr - tr_;
tl_ = tl; tr_ = tr;
int32_t q8 = (dl + dr) * kd_ + rem_;
int32_t d_um = q8 >> 8;
rem_ = q8 - (d_um << 8);
uint32_t diff = (uint32_t)(tr - tr0_) - (uint32_t)(tl - tl0_); // total difference since the start, wraps harmlessly
uint16_t th_new = (uint16_t)(th0_ + (uint16_t)((diff * (uint32_t)ka_) >> 16)); // the 32-bit product wraps, and 2^32 is a whole number of turns of the shifted result
pose_fixed(p, d_um, (int16_t)(uint16_t)(th_new - p.th));
}
PoseFixed p;
uint16_t th0_ = 0; // initial heading, binary angle units
private:
int32_t kd_, ka_, tl0_, tr0_, tl_, tr_, rem_;
bool first_;
};
The column on the right of the odometry experiment is this code. Its heading error is the same 0.03° as the float versions and its position error 0.42 to 0.94 mm, the same as the float ones, with one exception that shows a limit of the design: at an interval of 200 ms the distance per step is 75 mm, over the 65 mm that a 32-bit product with a Q15 sine can take, and the error jumps to 185 mm. The code says so in its comment; the experiment shows what ignoring the comment costs. The cost side is measured by compiling one update at a time into a sketch that reads two counters and prints the pose (the flash and RAM of the whole sketch; the first row is the sketch with no odometry):
arduino-cli compile --fqbn arduino:avr:uno --warnings all -DVARIANT_x s_odom
(whole sketch; "base" only reads two counters and prints them; the last two columns are what each odometry update adds)
variant flash bytes RAM bytes adds flash adds RAM
base (no odometry) 2134 196 0 0
float, midpoint rule (sinf, cosf) 4032 216 1898 20
float, exact arc (sinf, cosf) 4350 216 2216 20
integers, binary angle, 65-entry table 3206 367 1072 171
Midpoint odometry in float adds 1898 bytes of flash, the exact arc 2216 (the 318 extra are the division and the extra trigonometry), and the integer version 1072: a saving of 826 bytes, bought with 171 bytes of RAM, 130 of them the sine table. A static const array without PROGMEM is copied into RAM on the Uno, so the table is paid for twice (flash for its initial values and RAM for the copy); a PROGMEM table would give the RAM back and was not tried here. The integer version is not obviously a win on a 32 KB chip: 826 bytes is 2.6 % of the flash, and the code is harder to read. Its stronger case is time, which was not measured: the float version calls several library routines per update, and on a board with a faster control loop or less flash the integer version may be the only one that fits. Measure before choosing.
6. Moves: straight, and turn by an angle
Mover (in the header above) turns the pose into two moves. straight(d) drives until the odometry says d metres, with the forward speed proportional to the distance still to go (and ramped), and holds the heading by turning against the heading error (a P-only controller on the odometry heading). turn(a) turns until the heading is a radians away, with a turn rate proportional to the angle still to go, a floor on the rate (the slowest turn that is not stuck in the dead zone), and a ramp. A move is done when it is within a tolerance and the speed has died away.
The first run of the turn never finished, and why is worth seeing:
// e_turn.cpp -- a turn-by-90-degrees move that never finishes (host build, ideal robot: exact wheel radius and track, equal motors, 0.1 s motor lag).
// The move is done when the heading is within a tolerance of the target and the turn rate has died away. One encoder tick of difference between the wheels is
// 0.576 mm / 150 mm = 0.0038 rad (0.22 degrees); the slowest turn the controller allows is 0.4 rad/s.
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "sim.h"
#include "motion.h"
int main() {
std::printf("turn +90 degrees, run for up to 10 s; what the TRUE heading does after the controller decides\n");
std::printf(" tolerance rad tolerance deg done at (s) true heading at 10 s (deg) true heading swing over the last 2 s (deg)\n");
for (double tol : {0.003, 0.006, 0.010, 0.020}) {
RobotParams rp; rp.tau = 0.1;
SensorParams sp; Arena big; big.w = 100; big.h = 100;
SimHW w(rp, sp, big, 1); w.x = 50; w.y = 50;
MoveConfig c;
c.wheel_r = 0.033f; c.track = 0.15f; c.ticks_per_rev = 360; c.vmax = 0.4f; c.accel = 1.0f; c.k_dist = 3.0f; c.k_head = 0.0f;
c.wmax = 3.0f; c.alpha = 8.0f; c.k_turn = 3.0f; c.wmin = 0.4f; c.tol_m = 0.002f; c.tol_rad = (float)tol;
Mover<SimHW> m(w, c);
m.turn((float)(SIM_PI / 2));
double done_at = -1, lo = 1e9, hi = -1e9;
for (int t = 0; t < 500; ++t) {
m.update(0.02f);
for (int k = 0; k < 20; ++k) w.step(0.001);
if (done_at < 0 && m.done()) done_at = (t + 1) * 0.02;
if (t >= 400) { double d = w.th * 180 / SIM_PI; if (d < lo) lo = d; if (d > hi) hi = d; }
}
char buf[16];
if (done_at < 0) std::snprintf(buf, sizeof buf, "never"); else std::snprintf(buf, sizeof buf, "%.2f", done_at);
std::printf(" %13.3f %13.2f %11s %26.2f %42.2f\n", tol, tol * 180 / SIM_PI, buf, w.th * 180 / SIM_PI, hi - lo);
}
return 0;
}
turn +90 degrees, run for up to 10 s; what the TRUE heading does after the controller decides
tolerance rad tolerance deg done at (s) true heading at 10 s (deg) true heading swing over the last 2 s (deg)
0.003 0.17 never 89.02 1.78
0.006 0.34 never 89.02 1.78
0.010 0.57 1.46 88.47 0.00
0.020 1.15 1.20 92.06 0.00
With tolerances of 0.003 and 0.006 rad the 90° turn never completes: the true heading swings 1.78° peak to peak for as long as the program runs. The tolerance (0.17° and 0.34°) is smaller than one step of the heading the encoders can see (one tick on each wheel is 0.44°), and the controller will not turn slower than 0.4 rad/s, so every time it moves it jumps over the target, reverses, and jumps back. At 0.010 rad (0.57°) it finishes in 1.46 s. The rule is a general one: a tolerance finer than the sensor’s resolution is a request the controller can never satisfy; set it at about two steps of resolution. The finished turn is still 1.5° short (88.47°); I did not separate how much of that is the tolerance, the quantisation and the last coasting of the wheels.
Now the calibration. A robot’s code believes a wheel radius and a track width; the real ones differ, and an error in the radius is an error in every distance, and an error in the track is an error in every turn. Two driving tests measure them: drive a long straight and compare the distance the odometry counted with the distance covered; then spin on the spot for several turns and compare. In the experiment the true robot has a wheel radius 1.5 % larger than the code’s, a track 1.3 % wider, and a right motor 5 % weak (all assumed):
// e_move.cpp -- straight and turn-by-angle moves on odometry, with a robot whose real wheels are not quite what the code believes (host build; all the errors below are ASSUMED).
// The true robot: right motor 5 % weak, wheel radius 0.0335 m (the code believes 0.033), track 0.152 m (the code believes 0.150). Ideal otherwise: no slip, 8-bit duty, 0.1 s motor lag.
#include <cstdio>
#include <cmath>
#include "sim.h"
#include "motion.h"
static RobotParams true_robot() {
RobotParams rp; rp.wheel_r = 0.0335; rp.track = 0.152; rp.gain_r = 0.95; rp.tau = 0.1;
return rp;
}
static MoveConfig config(double wheel_r, double track, float k_head) {
MoveConfig c;
c.wheel_r = (float)wheel_r; c.track = (float)track; c.ticks_per_rev = 360;
c.vmax = 0.4f; c.accel = 1.0f; c.k_dist = 3.0f; c.k_head = k_head;
c.wmax = 3.0f; c.alpha = 8.0f; c.k_turn = 3.0f; c.wmin = 0.4f;
c.tol_m = 0.002f; c.tol_rad = 0.010f; // 0.57 degrees: coarser than one tick of heading (0.22 degrees), see e_turn
return c;
}
struct Result { double dist, lateral, head_deg; };
// run one move on a fresh robot; returns what the TRUTH did
template <bool TURN>
static Result run(double amount, double wheel_r, double track, float k_head) {
RobotParams rp = true_robot();
SensorParams sp; Arena big; big.w = 100; big.h = 100;
SimHW w(rp, sp, big, 1);
w.x = 50.0; w.y = 50.0;
MoveConfig c = config(wheel_r, track, k_head);
Mover<SimHW> m(w, c);
if (TURN) m.turn((float)amount); else m.straight((float)amount);
for (int tick = 0; tick < 3000 && !m.done(); ++tick) { m.update(0.02f); for (int k = 0; k < 20; ++k) w.step(0.001); }
for (int k = 0; k < 600; ++k) { m.update(0.02f); for (int j = 0; j < 20; ++j) w.step(0.001); } // let the wheels coast to rest, still updating
Result r;
double dx = w.x - 50.0, dy = w.y - 50.0;
r.dist = std::sqrt(dx * dx + dy * dy);
r.lateral = dy; // the move was ordered along +x
r.head_deg = w.th * 180.0 / SIM_PI;
return r;
}
int main() {
const double R0 = 0.033, T0 = 0.150;
std::printf("before calibration (the code believes wheel radius 0.033 m, track 0.150 m):\n");
std::printf(" move true distance (m) sideways drift (mm) true heading (deg)\n");
Result a = run<false>(1.0, R0, T0, 0.0f);
std::printf(" straight 1.000 m, no heading hold %17.4f %19.1f %18.2f\n", a.dist, a.lateral * 1000, a.head_deg);
Result b = run<false>(1.0, R0, T0, 3.0f);
std::printf(" straight 1.000 m, heading hold %17.4f %19.1f %18.2f\n", b.dist, b.lateral * 1000, b.head_deg);
Result t = run<true>(SIM_PI / 2, R0, T0, 0.0f);
std::printf(" turn +90 degrees %17s %19s %18.2f\n", "", "", t.head_deg);
// calibration 1: drive 2 m by the code's belief and measure the true distance -> a scale for the wheel radius
Result s = run<false>(2.0, R0, T0, 3.0f);
double scale_r = s.dist / 2.0;
double R1 = R0 * scale_r;
// calibration 2: spin four turns by the code's belief (with the radius corrected) and measure the true rotation -> a scale for the track
Result sp4 = run<true>(8.0 * SIM_PI, R1, T0, 0.0f);
double true_turn = sp4.head_deg * SIM_PI / 180.0;
double T1 = T0 * (8.0 * SIM_PI) / true_turn;
std::printf("\ncalibration: a 2 m drive covered %.4f m, so the wheel radius becomes %.5f m (scale %.4f); then four ordered turns made %.3f turns (%.2f deg), so the track becomes %.5f m\n",
s.dist, R1, scale_r, true_turn / (2 * SIM_PI), sp4.head_deg, T1);
std::printf("(the true values are 0.0335 and 0.152; the 5 %% weaker right motor does not change either, because both come from the ticks)\n");
std::printf("\nafter calibration:\n");
std::printf(" move true distance (m) sideways drift (mm) true heading (deg)\n");
Result a2 = run<false>(1.0, R1, T1, 0.0f);
std::printf(" straight 1.000 m, no heading hold %17.4f %19.1f %18.2f\n", a2.dist, a2.lateral * 1000, a2.head_deg);
Result b2 = run<false>(1.0, R1, T1, 3.0f);
std::printf(" straight 1.000 m, heading hold %17.4f %19.1f %18.2f\n", b2.dist, b2.lateral * 1000, b2.head_deg);
Result t2 = run<true>(SIM_PI / 2, R1, T1, 0.0f);
std::printf(" turn +90 degrees %17s %19s %18.2f\n", "", "", t2.head_deg);
return 0;
}
before calibration (the code believes wheel radius 0.033 m, track 0.150 m):
move true distance (m) sideways drift (mm) true heading (deg)
straight 1.000 m, no heading hold 1.0103 -172.2 -19.63
straight 1.000 m, heading hold 1.0152 -42.1 -2.60
turn +90 degrees 88.93
calibration: a 2 m drive covered 2.0305 m, so the wheel radius becomes 0.03350 m (scale 1.0153); then four ordered turns made 3.943 turns (1419.56 deg), so the track becomes 0.15216 m
(the true values are 0.0335 and 0.152; the 5 % weaker right motor does not change either, because both come from the ticks)
after calibration:
move true distance (m) sideways drift (mm) true heading (deg)
straight 1.000 m, no heading hold 0.9955 -167.2 -19.34
straight 1.000 m, heading hold 1.0002 -41.4 -2.64
turn +90 degrees 88.78
Before calibration an ordered 1 m straight covers 1.0152 m with the heading held: 1.5 % long, which is the radius. The 2 m calibration drive measured 2.0305 m, so the radius is corrected to 0.03350 m (the true value, to the digits shown). The four-turn spin gave 3.943 turns instead of 4, and the track is corrected to 0.15216 m (true 0.152; the 0.1 % residual is the turn tolerance). After calibration the held straight covers 1.0002 m. The 5 % weak right motor does not enter either number: both calibrations come from the ticks, which count what the wheels really did, whatever the duty. What the weak motor does is steer, and without heading hold the robot ends 167 mm to the side at −19.3° (and a chord of 0.9955 m for 1 m of path); with the P-only heading hold the drift falls to 41 mm and −2.6°. A proportional hold leaves a steady error against a steady disturbance; removing that is the job of the PID of Programming for Robotics with Arduino C++ 6.
The turn is the sobering row: +90° ordered gave 88.93° before and 88.78° after calibration. For turns the two errors nearly cancel (a radius 1.5 % too small and a track 1.3 % too narrow: a net 0.18 %, which is 0.16° at 90°), and calibration moved the result by 0.15°, as that predicts, which is far less than the 1.1° the stopping error leaves. The track alone is a larger error: with the radius corrected but not the track, the four ordered turns fell 20° short. Know the size of each error before calibrating the smallest one.
7. The sketch and the budget
robot_ch5.ino puts it together on the Uno: the interrupt routines and atomic reads of Programming for Robotics with Arduino C++ 4, PinHW reduced to read_ticks and drive (all that Mover needs), a motor command through speed_to_pwm_dz with an assumed dead duty of 40, and a control task every 20 ms that drives a square: 0.5 m, a 90° turn, four times. It prints the pose and the left wheel speed twice a second.
// robot_ch5.ino -- Programming for Robotics with Arduino C++, chapter 5: the robot drives a square on odometry (straight 0.5 m, turn 90 degrees, four times).
// Compile-checked for the Uno (arduino:avr:uno). NOT run on a board: no board, motor or encoder was attached.
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/atomic.h>
#include "scheduler.h"
#include "conv.h"
#include "pins.h"
#include "motion.h"
const float V_MAX_MPS = 0.5f; // wheel speed at a duty of 255: an assumption (chapter 2)
const uint8_t DEAD_DUTY = 40; // the highest duty that does not turn the wheel: an ASSUMED value; measure yours (challenge 3)
volatile int32_t g_ticks_l = 0, g_ticks_r = 0; // the interrupt routines of chapter 4, 2x decoding
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; }
class PinHW { // read_ticks() and drive(): all that Mover needs
public:
void read_ticks(int32_t& l, int32_t& r) { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { l = g_ticks_l; r = g_ticks_r; } }
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 PinHW hw;
static MoveConfig make_config() {
MoveConfig c;
c.wheel_r = 0.033f; c.track = 0.150f; c.ticks_per_rev = 360; // 360 COUNTS per turn: a 180-slot disc at 2x; replace by the calibrated values
c.vmax = 0.4f; c.accel = 1.0f; c.k_dist = 3.0f; c.k_head = 3.0f;
c.wmax = 3.0f; c.alpha = 8.0f; c.k_turn = 3.0f; c.wmin = 0.4f;
c.tol_m = 0.002f; c.tol_rad = 0.010f; // coarser than one tick of heading (e_turn)
return c;
}
static Mover<PinHW> mover(hw, make_config());
static SpeedWindow speed_l(2.0f * 3.14159265f * 0.033f / 360.0f);
static Scheduler<3> sch;
static uint8_t leg = 0; // 0..7: straight, turn, straight, turn, ...
static void control_task(void*, uint32_t) {
mover.update(0.02f);
if (mover.done() && leg < 8) {
if (leg % 2 == 0) mover.straight(0.5f); else mover.turn(1.5707963f);
++leg;
}
}
static void report_task(void*, uint32_t) {
int32_t l, r; hw.read_ticks(l, r);
Serial.print(F("leg ")); Serial.print(leg); Serial.print(F(" x ")); Serial.print(mover.pose().x, 3);
Serial.print(F(" y ")); Serial.print(mover.pose().y, 3); Serial.print(F(" th ")); Serial.print(mover.pose().th, 3);
Serial.print(F(" v_left ")); Serial.println(speed_l.update(l, micros()), 3);
}
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 with no warnings under --warnings all to 8868 bytes of flash (27 %) and 409 bytes of RAM (19 %), against 8626 and 433 for Programming for Robotics with Arduino C++ 4’s sketch: it adds the odometry (with sinf and cosf) and the moves, and drops the ultrasonic sensor and its median filter. It was not run. The values that must change before it moves a real robot are the ones the chapter has just shown to matter: the wheel radius and track from a calibration, DEAD_DUTY from the sweep of challenge 3, and ticks_per_rev from the encoder disc.
8. What the numbers can and cannot be trusted for
What they show. The shapes: a window cannot see a slow wheel and a period can; midpoint odometry is as good as the exact arc here; a float heading accumulates a systematic error, and rounding the step to an integer accumulates one too, so the integer heading must come from the counts; a tolerance below the sensor’s resolution makes a move never finish; calibration fixes the scale of distances and turns and nothing else. Flash and RAM figures are the compiler’s for the real chip.
What they do not show. The dead zone, the lag, the weak motor and the radius and track errors are assumptions, and a real robot slips, has backlash, has a floor that changes, and loses encoder counts, none of which is here. No update was timed, so the cost of float in time is unmeasured; only its flash and RAM are. The odometry of a real robot drifts from the first metre for reasons this simulator cannot make: the next step, as in the Python course, is to correct it with another sensor (Programming for Robotics with Arduino C++ 10), and before then to drive a real square, mark where it ends, and calibrate on the floor you will use.
Challenge 1: Which speed estimator?
Compare ticks counted over windows of 20, 50 and 100 ms with the period of the last two ticks, at true speeds from 0.01 to 0.5 m/s on the simulator. Print each estimator’s rms error as a percentage of the speed, and the delay each adds. Say which you would use below 0.05 m/s, at 0.1 m/s and at 0.5 m/s, and what you give up for it.
Find, for steps of 1e-3, 1e-4 and 1e-5 rad, the heading at which a float th += dth freezes, and compare it with dth × 224. Then keep the heading of a wheel pair that gains one tick of difference per update three ways: a float added to and wrapped, a float computed from the count, and a binary angle computed from the count; print the error against a double truth at 105 to 108 updates, and say which you would choose on the Uno.
The simulator holds a hidden dead duty that your program may not read. Find it by driving the motor: hold each duty from 0 up for 1.5 s, count the ticks in the last second, and call a duty “moving” at 3 ticks or more. Then command 0.02, 0.05 and 0.1 m/s through the plain mapping and through speed_to_pwm_dz with the value you found, for two different hidden dead zones (57 and 23).
Dead zone. With a dead duty of 40 (assumed) the plain mapping gives nothing below 0.1 m/s (0.1 m/s gives 0.026); speed_to_pwm_dz is within 2.3 % from 0.05 m/s. One duty step is 2.3 mm/s, the slowest steady speed.
Ramp. Step to 0.5 m/s: peak 5.00 m/s², 95 % in 0.299 s. Ramps of 2.0, 1.0, 0.5 m/s²: peaks 1.84, 0.99, 0.50; times 0.448, 0.637, 1.068 s.
Wheel speed. 0.576 mm per tick. A 20 ms window sees 0 or 28.8 mm/s: at 0.01 m/s it says 0 in 65 of 100 samples (13.74 mm/s rms). The period of two ticks: 0.00 error there, 4.36 mm/s at 0.5 m/s with a 20 µs clock.
Odometry. Floor 0.45 mm and 0.03°, from the ticks. Euler 0.5 to 3.9 mm from 10 to 200 ms; midpoint and exact arc 0.45 to 0.16, equal within 0.02 mm. Use midpoint.
Float heading. Never wrapped: 76° off after 105 updates of 0.02 rad. Wrapped: −0.09°, still drifting (−9.07° at 107). A float freezes near dth × 224 to twice that (32768 rad for 1e-3). Rounding the step to an integer accumulates too; compute the heading from the count.
Integers. Binary angle (uint16, 65,536 per turn) and micrometres; Q15 quarter-wave table of 65 entries. Same accuracy as float, except a 32-bit product limit: 65 mm per step (185 mm error at 200 ms). Flash: midpoint float +1898, arc +2216, integers +1072; RAM +20, +20, +171 (table not in PROGMEM).
Tolerance. Below the sensor’s resolution a move never ends: tolerances 0.003 and 0.006 rad never finish (swing 1.78°); 0.010 rad finishes in 1.46 s.
Calibration. A 2 m drive gave 2.0305 m: radius 0.03350 m (true 0.0335). Four ordered turns gave 3.943: track 0.15216 m (true 0.152). Held straight: 1.0152 m before, 1.0002 m after. The 90° turn: 88.93° before, 88.78° after (stopping error larger than the scale error).
Not run: anything on a board; the dead zone, lag, weak motor and the radius and track errors are assumptions.
Next: Programming for Robotics with Arduino C++ 6, Control Loops in Code
Programming for Robotics with Arduino C++ 6 (planned; not yet written) replaces the proportional controllers of this chapter with a PID class: anti-windup and a filtered derivative, tuned in the simulator first, a cascaded speed and position loop, a proper heading hold (the steady error of section 6 is what an integral term removes), and a fixed-point PID, with the time per pass counted in microseconds.