Programming for Robotics with Arduino C++ 9 gave the robot a route; to follow it the robot must know where it is, and no sensor says so. The wheel encoders drift (Programming for Robotics with Arduino C++ 5), a gyro integrates its own offset into a heading that wanders off, a compass is noisy and is thrown by every motor and steel table, an accelerometer shakes with the motors. Each is right about something the others are wrong about. State estimation is the craft of combining them: believing each sensor where it is good and ignoring it where it is bad.
The chapter builds three tools in order of weight: the complementary filter (one line), a scalar Kalman filter (one number and a gain) and a two-state Kalman filter with its small matrices multiplied out into ordinary arithmetic. Then it fuses a gyro with a compass, and wheel speed with a range sensor, and ends with the question the Uno forces: what does each of them cost on a chip with no floating-point unit, and when is integer arithmetic worth the trouble?
What was run, and what was not
Run on a PC (g++ 16.2, C++11, -Wall -Wextra -pedantic): every experiment with an output under it and the three challenge solutions, on simulated sensors. The gyro offsets and noise, the compass noise and its 20° disturbances, the accelerometer vibration, the range noise and dropouts, and the odometry noise are assumptions I chose, not measurements of any real part.
Compiled for the Uno, not run (arduino-cli, core arduino:avr 1.8.8, --warnings all): the six-variant cost-test sketch and robot_ch10.ino; the instruction and library-call counts come from avr-objdump, the sizes from the compiler and avr-nm.
From memory and not verified: the gyro chip’s I2C address, its register numbers and its scale in robot_ch10.ino are what I remember of an MPU-6050-style data sheet; I did not check them and the code never ran against a chip.
Nothing was attached to a board and no time was measured. “Cost” here means bytes of flash and RAM and the number of instructions and library calls: never seconds.
1. Why one sensor is not enough
The three failures have different shapes, and the filters of this chapter work because the shapes are different. A gyro measures how fast the robot turns, so its angle is the sum of many readings: smooth and quick to respond, but any constant offset in the readings becomes an angle that grows without limit. A compass or an accelerometer measures the angle itself, so it never drifts, but it is noisy and, near motors, disturbed. A good estimate follows the gyro for the fast changes and the absolute sensor for the slow ones. In Python this is a few lines of NumPy; on the Uno it is a few lines of arithmetic whose price you can read off the compiler’s report.
In Python
On the Uno in C++
F @ P @ F.T + Q on NumPy arrays, any size of state
the 2 × 2 products multiplied out by hand into scalar statements: 13 multiplications for a predict and an update
np.linalg.inv(S) for the innovation covariance
a measurement of one number makes S a scalar: one division
64-bit floats at the speed of the hardware
32-bit floats done by library routines: every +, *, / is a function call of a couple of hundred bytes of code
filterpy or a library fixes the maths for you
nothing: you choose Q and R, and they are assumptions about hardware you must measure
no thought for the word size
integers in micro-radians, gains in Q16: you choose the units so nothing overflows and nothing rounds to zero
2. The complementary filter
The complementary filter is the cheapest estimator there is: angle = alpha * (angle + rate * dt) + (1 - alpha) * measured. Each step the angle moves with the gyro (the part in the brackets) and is then pulled a little way toward the absolute measurement. The weight alpha = tau / (tau + dt) is set by one number, the time constanttau: for changes faster than about tau seconds the gyro is believed, for slower ones the measurement. All the estimators of the chapter are in one header, est.h: plain C++11, no heap, no matrix library, no Arduino calls, so the same file runs on the PC and the Uno. Here it is, in four parts (the complementary filter and its fixed-point twin, a scalar Kalman filter, a two-state Kalman filter, and a fixed-point heading filter):
// est.h -- state estimation in small, fixed-size pieces (Programming for Robotics with Arduino C++ 10). Plain C++11: no heap, no matrix library, no Arduino calls.
// The two-state filters are written out as scalar equations: on a chip with no floating-point unit every multiplication is a library call, and you want to see them.
#pragma once
#include <stdint.h>
// ---- 1. complementary filter: trust the gyro for fast changes and the accelerometer (or any absolute angle) for slow ones ----
// angle = alpha * (angle + rate dt) + (1 - alpha) * measured, alpha = tau / (tau + dt). tau is the time (s) below which the gyro is believed.
class Complementary {
public:
Complementary(float tau_s, float dt_s, float start = 0.0f) : angle_(start), alpha_(tau_s / (tau_s + dt_s)) {}
float update(float rate, float measured, float dt_s) { angle_ = alpha_ * (angle_ + rate * dt_s) + (1.0f - alpha_) * measured; return angle_; }
float angle() const { return angle_; }
private:
float angle_, alpha_;
};
// the same filter in integers: angle in micro-radians, rate in micro-radians per second, a 10 ms step, k = (1 - alpha) in Q16
class ComplementaryFixed {
public:
ComplementaryFixed(float tau_s, int32_t start_urad = 0) : angle_(start_urad), k_((int32_t)(65536.0f * 0.01f / (tau_s + 0.01f) + 0.5f)) {}
int32_t update(int32_t rate_urad_s, int32_t measured_urad) {
angle_ += rate_urad_s / 100; // 10 ms
int32_t d = measured_urad - angle_;
if (d > 2000000) d = 2000000; else if (d < -2000000) d = -2000000; // keeps the product below 2^31
angle_ += ((d >> 4) * k_) >> 12;
return angle_;
}
int32_t k() const { return k_; }
private:
int32_t angle_, k_;
};
// ---- 2. a scalar Kalman filter: one number that changes slowly (a distance, a bias), measured with noise ----
class Kalman1 {
public:
Kalman1(float x0, float p0, float q, float r) : x_(x0), p_(p0), q_(q), r_(r), k_(0.0f) {}
void update(float z) {
p_ += q_; // predict: the state is a random walk, its uncertainty grows by q
k_ = p_ / (p_ + r_); // the gain: how much of the surprise to believe
x_ += k_ * (z - x_);
p_ *= (1.0f - k_);
}
float x() const { return x_; }
float p() const { return p_; }
float gain() const { return k_; }
private:
float x_, p_, q_, r_, k_;
};
// ---- 3. a two-state Kalman filter with the matrices written out. State (x0, x1); measurement of x0 (and, optionally, of x1). ----
// model: x0' = x0 + f01 * x1 * dt + u * dt x1' = x1 (f01 = +1: x0 is a position, x1 its speed; f01 = -1: x0 is a heading, x1 the gyro's bias, u the gyro rate)
// F = [1 f01 dt; 0 1], Q = diag(q0 dt, q1 dt) (a simple choice, not the textbook matrix), P is 2 x 2 and symmetric (p00, p01, p11).
class Kalman2 {
public:
Kalman2(float f01, float q0, float q1, float p0 = 1.0f, float p1 = 1.0f) : f01_(f01), q0_(q0), q1_(q1), x0_(0), x1_(0), p00_(p0), p01_(0), p11_(p1), k0_(0), k1_(0) {}
void set(float x0, float x1) { x0_ = x0; x1_ = x1; }
void predict(float u, float dt) {
x0_ += (f01_ * x1_ + u) * dt; // x = F x + B u
float a = p00_ + f01_ * dt * p01_; // P = F P F^T + Q, multiplied out
float b = p01_ + f01_ * dt * p11_;
p00_ = a + f01_ * dt * b + q0_ * dt; // (symmetric: p10 = p01)
p01_ = b;
p11_ += q1_ * dt;
}
void update_x0(float z, float r) { // H = [1 0]
float s = p00_ + r; // innovation variance
k0_ = p00_ / s; k1_ = p01_ / s; // the gain K = P H^T / s
float y = z - x0_;
x0_ += k0_ * y; x1_ += k1_ * y;
float p00 = p00_, p01 = p01_; // P = (I - K H) P
p00_ -= k0_ * p00; p01_ -= k0_ * p01; p11_ -= k1_ * p01;
}
void update_x1(float z, float r) { // H = [0 1]
float s = p11_ + r;
k0_ = p01_ / s; k1_ = p11_ / s;
float y = z - x1_;
x0_ += k0_ * y; x1_ += k1_ * y;
float p01 = p01_, p11 = p11_;
p00_ -= k0_ * p01; p01_ -= k0_ * p11; p11_ -= k1_ * p11;
}
float x0() const { return x0_; }
float x1() const { return x1_; }
float k0() const { return k0_; }
float k1() const { return k1_; }
float p00() const { return p00_; }
private:
float f01_, q0_, q1_, x0_, x1_, p00_, p01_, p11_, k0_, k1_;
};
// ---- 4. the same heading-and-bias filter in integers, with the gains fixed (they settle after a while, so they can be computed beforehand on a PC) ----
// heading in micro-radians, bias in micro-radians per second, gyro rate in micro-radians per second, a 10 ms predict step; K0 and K1 in Q16.
class HeadingFixed {
public:
HeadingFixed(int32_t k0_q16, int32_t k1_q16) : th_(0), b_(0), k0_(k0_q16), k1_(k1_q16) {}
void set(int32_t th_urad, int32_t b_urad_s) { th_ = th_urad; b_ = b_urad_s; }
void predict(int32_t rate_urad_s) { th_ += (rate_urad_s - b_) / 100; }
void update(int32_t z_urad) {
int32_t y = z_urad - th_;
if (y > 2000000) y = 2000000; else if (y < -2000000) y = -2000000;
th_ += ((y >> 4) * k0_) >> 12;
b_ += ((y >> 4) * k1_) >> 12;
}
int32_t heading() const { return th_; }
int32_t bias() const { return b_; }
private:
int32_t th_, b_, k0_, k1_;
};
The first experiment is a simulated tilt: two sine waves and a step of 0.4 rad at 30 s (the robot is tipped up a kerb). The gyro has a constant offset (random per run, up to 0.03 rad/s) and noise; the accelerometer angle has noise and a 6 Hz vibration from the motors. All of that is assumed. The table is the rms error in degrees, over the whole run and over the 5 s after the step (how fast the filter follows a real change):
// e_comp.cpp -- the complementary filter on a simulated tilt angle (host build; every sensor model below is ASSUMED, not measured).
// Truth: the robot's tilt (rad) is two sine waves (periods 8 s and 2.5 s) and a step of +0.4 rad at t = 30 s (it is tipped up a kerb). 100 Hz, 60 s, 40 seeded runs.
// gyro the true rate + a constant offset (random per run, +-0.03 rad/s) + noise of 0.01 rad/s
// accelerometer the true angle + noise of 0.05 rad + a vibration of 0.12 rad at 6 Hz (the motors)
// Compared: the gyro integrated alone, the accelerometer angle alone, and the complementary filter for several time constants tau.
// Scored: the rms error over the run (degrees) and over the 5 s after the step (how quickly the filter follows a real change).
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "sim.h"
#include "est.h"
static double truth(double t) { return 0.35 * std::sin(2 * SIM_PI * t / 8.0) + 0.12 * std::sin(2 * SIM_PI * t / 2.5) + (t >= 30.0 ? 0.4 : 0.0); }
static double truth_rate(double t) { return 0.35 * 2 * SIM_PI / 8.0 * std::cos(2 * SIM_PI * t / 8.0) + 0.12 * 2 * SIM_PI / 2.5 * std::cos(2 * SIM_PI * t / 2.5); }
struct Err { double all, after; };
// kind: -1 gyro only, -2 accelerometer only, otherwise the filter's tau in seconds
static Err run(double tau, int kind, double vib_hz, int seeds) {
double sq_all = 0, sq_after = 0; long n_all = 0, n_after = 0;
for (int seed = 1; seed <= seeds; ++seed) {
Rng rng((uint32_t)seed * 7777u + 5u);
double bias = (rng.uniform() * 2 - 1) * 0.03;
const float dt = 0.01f;
Complementary f(kind > 0 ? (float)tau : 1.0f, dt, (float)truth(0));
double gyro_int = truth(0);
for (int i = 1; i <= 6000; ++i) {
double t = i * dt;
double rate = truth_rate(t) + bias + 0.01 * rng.normal();
double acc = truth(t) + 0.05 * rng.normal() + 0.12 * std::sin(2 * SIM_PI * vib_hz * t);
gyro_int += rate * dt;
double est = kind == -1 ? gyro_int : kind == -2 ? acc : f.update((float)rate, (float)acc, dt);
double e = est - truth(t);
sq_all += e * e; ++n_all;
if (t > 30.0 && t <= 35.0) { sq_after += e * e; ++n_after; }
}
}
Err r = {std::sqrt(sq_all / n_all) * 57.2958, std::sqrt(sq_after / n_after) * 57.2958};
return r;
}
int main() {
std::printf("tilt estimate: rms error in degrees, mean over 40 runs (vibration 6 Hz)\n");
std::printf(" estimator whole run 5 s after the step\n");
{ Err r = run(0, -1, 6.0, 40); std::printf(" gyro integrated alone %10.2f %18.2f\n", r.all, r.after); }
{ Err r = run(0, -2, 6.0, 40); std::printf(" accelerometer angle alone %10.2f %18.2f\n", r.all, r.after); }
for (double tau : {0.05, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0}) { Err r = run(tau, 1, 6.0, 40); std::printf(" complementary, tau %5.2f s %10.2f %18.2f\n", tau, r.all, r.after); }
return 0;
}
tilt estimate: rms error in degrees, mean over 40 runs (vibration 6 Hz)
estimator whole run 5 s after the step
gyro integrated alone 37.52 40.13
accelerometer angle alone 5.65 5.66
complementary, tau 0.05 s 2.35 2.60
complementary, tau 0.20 s 1.22 3.12
complementary, tau 0.50 s 1.59 5.02
complementary, tau 1.00 s 2.30 7.25
complementary, tau 2.00 s 3.51 10.47
complementary, tau 5.00 s 6.53 16.22
complementary, tau 10.00 s 10.76 21.20
Neither sensor is good alone: the gyro’s offset drifts the angle by 37° rms in a minute, the accelerometer is 5.7° off all the time. Between them there is a best tau, here 0.2 s, at 1.22°: a quarter of the accelerometer’s error. But the best tau is a trade: a long one trusts the gyro longer, so its offset has time to drift the angle (3.5° at 2 s) and a real step is followed slowly (10.5° in the 5 s after it); a short one lets the vibration through. The best value depends on what is wrong with the absolute sensor, which is challenge 1.
3. A Kalman filter with one state
The complementary filter has one fixed weight. A Kalman filter computes the weight, the gainK, from two numbers you give it: how noisy a measurement is (R) and how much the state may change between measurements (q). It keeps a third number P, how uncertain it currently is, which grows by q each step and shrinks when a measurement arrives. Start knowing nothing and the first measurement is nearly all believed (K near 1); as confidence grows, K falls. Let me see how the gain behaves on a range sensor with 5 mm of noise, one reading every 60 ms (assumed), for several values of q:
// e_kalman1.cpp -- the scalar Kalman filter: what the gain does (host build; the sensor is assumed: noise 5 mm, one reading every 60 ms).
// Part 1: the gain K step by step for a range that does not change (truth 1.000 m), for several process noises q (m^2 added to the uncertainty each step): q = 0 means "the state never changes".
// The filter starts knowing nothing (variance 1 m^2). Steady state from the formula: P- = (q + sqrt(q^2 + 4 q R)) / 2, K = P- / (P- + R).
// Part 2: the same filters following a range that moves at 0.05 m/s (3 mm per reading). rms error over 20 s, 200 seeded runs.
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "sim.h"
#include "est.h"
int main() {
const double R = 0.005 * 0.005;
const double qs[4] = {0.0, 1e-8, 1e-6, 1e-4};
std::printf("part 1: the gain K after k readings of a fixed range (sigma 5 mm, R = %.1e m^2)\n", R);
std::printf(" k q = 0 q = 1e-8 q = 1e-6 q = 1e-4\n");
Kalman1 f[4] = {Kalman1(1.0f, 1.0f, (float)qs[0], (float)R), Kalman1(1.0f, 1.0f, (float)qs[1], (float)R), Kalman1(1.0f, 1.0f, (float)qs[2], (float)R), Kalman1(1.0f, 1.0f, (float)qs[3], (float)R)};
Rng rng(12345);
int shown[] = {1, 2, 3, 4, 5, 10, 20, 50, 100, 1000};
int si = 0;
for (int k = 1; k <= 1000; ++k) {
double z = 1.0 + 0.005 * rng.normal();
for (int i = 0; i < 4; ++i) f[i].update((float)z);
if (k == shown[si]) { std::printf(" %-4d %.5f %.5f %.5f %.5f\n", k, f[0].gain(), f[1].gain(), f[2].gain(), f[3].gain()); ++si; }
}
std::printf(" formula, steady state:");
for (int i = 0; i < 4; ++i) { double pm = (qs[i] + std::sqrt(qs[i] * qs[i] + 4 * qs[i] * R)) / 2; std::printf(" %.5f", pm / (pm + R)); }
std::printf("\n (q = 0: K = 1/k exactly after k readings, a running average that never stops averaging)\n");
std::printf("\npart 2: following a range that moves at 0.05 m/s, readings every 60 ms for 20 s, 200 runs\n");
std::printf(" q (m^2 per reading) steady gain K rms error (mm) rms error of the raw readings (mm)\n");
for (double q : {0.0, 1e-8, 1e-6, 1e-5, 1e-4}) {
double sq = 0, sqraw = 0; long n = 0;
for (int seed = 1; seed <= 200; ++seed) {
Rng r2((uint32_t)seed * 911u);
Kalman1 k(1.0f, 1.0f, (float)q, (float)R);
for (int i = 1; i <= 333; ++i) {
double truth = 1.0 + 0.05 * i * 0.06;
double z = truth + 0.005 * r2.normal();
k.update((float)z);
if (i > 10) { sq += (k.x() - truth) * (k.x() - truth); sqraw += (z - truth) * (z - truth); ++n; }
}
}
Kalman1 g(1.0f, 1.0f, (float)q, (float)R); for (int i = 0; i < 2000; ++i) g.update(1.0f);
std::printf(" %19.0e %13.5f %14.2f %34.2f\n", q, g.gain(), std::sqrt(sq / n) * 1000, std::sqrt(sqraw / n) * 1000);
}
return 0;
}
part 1: the gain K after k readings of a fixed range (sigma 5 mm, R = 2.5e-05 m^2)
k q = 0 q = 1e-8 q = 1e-6 q = 1e-4
1 0.99997 0.99997 0.99997 0.99997
2 0.50034 0.50044 0.51013 0.83337
3 0.33348 0.33371 0.35489 0.82857
4 0.25008 0.25043 0.28310 0.82843
5 0.20005 0.20053 0.24420 0.82843
10 0.10001 0.10115 0.18855 0.82843
20 0.05000 0.05245 0.18113 0.82843
50 0.02000 0.02606 0.18100 0.82843
100 0.01000 0.02055 0.18100 0.82843
1000 0.00100 0.01980 0.18100 0.82843
formula, steady state: 0.00000 0.01980 0.18100 0.82843
(q = 0: K = 1/k exactly after k readings, a running average that never stops averaging)
part 2: following a range that moves at 0.05 m/s, readings every 60 ms for 20 s, 200 runs
q (m^2 per reading) steady gain K rms error (mm) rms error of the raw readings (mm)
0e+00 0.00050 292.15 4.99
1e-08 0.01980 126.17 4.99
1e-06 0.18100 13.61 4.99
1e-05 0.46332 4.43 4.99
1e-04 0.82843 4.25 4.99
With q = 0 the gain is exactly 1/k after k readings: the filter is a running average that never stops averaging, and when the range moves it follows at a rms error of 292 mm, far worse than the raw readings’ 5 mm. The gain settles at a value set only by q and R (the steady states match the formula to the digits shown), and the choice of q is the whole tuning: 1e-8 is still 126 mm off, 1e-6 is 13.6 mm, and from 1e-5 the filter is better than the raw sensor (4.4 and 4.25 mm against 4.99). A filter told that nothing moves stops listening; a Kalman filter is only as good as the model you tell it.
4. Two states, with the matrices written out
Most of what a robot needs has two numbers tied together: a position and its speed, or a heading and the gyro’s offset. The state is x = (x0, x1); between steps x0 advances by f01 * x1 * dt (plus a known input u, the gyro rate, for the heading) and x1 stays. In matrices:
predict: x = F x + B u F = [ 1 f01*dt ] f01 = +1: x0 is a position, x1 its speed
P = F P F^T + Q [ 0 1 ] f01 = -1: x0 is a heading, x1 the gyro's offset
(the gyro reads rate + offset, so x0 moves by u - x1)
update: s = P00 + R (measuring x0: H = [1 0])
K = P H^T / s = (P00, P01) / s y = z - x0
x = x + K y
P = (I - K H) P
multiplied out for the 2 x 2 symmetric P = [p00 p01; p01 p11]:
a = p00 + f01 dt p01 b = p01 + f01 dt p11
p00 = a + f01 dt b + q0 dt p01 = b p11 = p11 + q1 dt
There is one measurement at a time, so s is a single number and the “inverse” is one division; the only matrix algebra left is the 2 × 2 products, which Kalman2 in est.h has written out so you can count the operations. The process noise here is the simple Q = diag(q0 dt, q1 dt), not the textbook matrix derived from a continuous model: a choice made for clarity, not the only correct one. update_x1 measures the second state instead (the speed from the wheels), with H = [0 1].
Heading from a gyro and a compass
Here x0 is the heading and x1 the gyro’s offset: the gyro is not a measurement but the inputu of the predict step at 100 Hz, and the compass (every 100 ms) is the measurement. The filter has no direct reading of the offset, yet it learns it: the gyro’s heading and the compass keep disagreeing in the same direction, and the filter puts that disagreement down to x1. The experiment compares six estimators over 120 s, with the robot turning back and forth, and the compass disturbed by +20° for 5 s at 60 s and again at 100 s (assumed: a motor or a steel table). The fifth estimator ignores a compass reading more than 0.27 rad (three of its standard deviations) from the estimate: a gate. The sixth is the integer HeadingFixed, with the Kalman gains frozen at their settled values, computed on the PC:
// e_heading.cpp -- heading from a gyro and a compass: six ways (host build; every sensor model is ASSUMED, not measured).
// Truth: the robot sits still for 2 s, then turns back and forth at 0.8 sin(2 pi t / 20) rad/s; 120 s; the gyro runs at 100 Hz, the compass at 10 Hz. 100 seeded runs.
// gyro the true rate + an offset (random per run, +-0.02 rad/s = +-1.1 deg/s) that wanders (random walk, 0.0005 rad/s per sqrt(s)) + noise of 0.005 rad/s
// compass the true heading + noise of 0.09 rad (5 deg), and a magnetic DISTURBANCE: +0.35 rad (20 deg) for 5 s from t = 60 s and again from t = 100 s
// Estimators: (1) the gyro alone, its offset measured while the robot sits still for the first 2 s; (2) the compass alone; (3) the complementary filter, tau 2 s;
// (4) the two-state Kalman filter (heading, gyro offset) with the compass as measurement; (5) the same with a gate that ignores a compass reading more than 0.27 rad (3 sigma) from the estimate;
// (6) the fixed-point filter with the Kalman gains of (4) frozen at their settled values (Q16). Scored: rms error over the run, over the two disturbances, the worst error, and the error of the offset estimate at the end.
#include <cstdio>
#include <cmath>
#include "sim.h"
#include "est.h"
struct Out { double rms, rms_dist, worst, bias_err; };
static double rate_at(double t) { return t < 2.0 ? 0.0 : 0.8 * std::sin(2 * SIM_PI * (t - 2.0) / 20.0); }
// settled gains of the Kalman filter at the moments of a compass update (the predict runs ten times between updates)
static void settled_gains(double q0, double q1, double r, float& k0, float& k1) {
Kalman2 k(-1.0f, (float)q0, (float)q1, 1.0f, 0.01f);
for (int i = 0; i < 400; ++i) { for (int j = 0; j < 10; ++j) k.predict(0.0f, 0.01f); k.update_x0(0.0f, (float)r); }
k0 = k.k0(); k1 = k.k1();
}
static Out run(int kind, int seeds, float k0q = 0, float k1q = 0) {
const double q0 = 0.005 * 0.005 * 0.01, q1 = 0.0005 * 0.0005, r = 0.09 * 0.09;
double sq = 0, sqd = 0, worst = 0, berr = 0; long n = 0, nd = 0;
for (int seed = 1; seed <= seeds; ++seed) {
Rng rng((uint32_t)seed * 4271u + 3u);
double bias = (rng.uniform() * 2 - 1) * 0.02, th = 0.0;
double gyro_th = 0.0, bias_cal = 0.0; int ncal = 0;
Complementary comp(2.0f, 0.01f, 0.0f);
Kalman2 kf(-1.0f, (float)q0, (float)q1, 1.0f, 0.01f), kg(-1.0f, (float)q0, (float)q1, 1.0f, 0.01f);
HeadingFixed fx((int32_t)std::lround(k0q * 65536.0), (int32_t)std::lround(k1q * 65536.0));
double compass = 0.0;
for (int i = 1; i <= 12000; ++i) {
double t = i * 0.01;
double rate = rate_at(t);
th += rate * 0.01;
bias += 0.0005 * std::sqrt(0.01) * rng.normal();
double gyro = rate + bias + 0.005 * rng.normal();
if (t <= 2.0) { bias_cal += gyro; ++ncal; }
gyro_th += (gyro - (ncal ? bias_cal / ncal : 0.0)) * 0.01;
bool dist = (t >= 60 && t < 65) || (t >= 100 && t < 105);
bool have = i % 10 == 0;
if (have) compass = th + 0.09 * rng.normal() + (dist ? 0.35 : 0.0);
double est = 0, bias_est = 0;
comp.update((float)gyro, (float)compass, 0.01f);
kf.predict((float)gyro, 0.01f); kg.predict((float)gyro, 0.01f);
fx.predict((int32_t)std::lround(gyro * 1e6));
if (have) {
kf.update_x0((float)compass, (float)r);
if (std::fabs(compass - kg.x0()) < 0.27) kg.update_x0((float)compass, (float)r);
fx.update((int32_t)std::lround(compass * 1e6));
}
switch (kind) {
case 1: est = gyro_th; break;
case 2: est = compass; break;
case 3: est = comp.angle(); break;
case 4: est = kf.x0(); bias_est = kf.x1(); break;
case 5: est = kg.x0(); bias_est = kg.x1(); break;
default: est = fx.heading() * 1e-6; bias_est = fx.bias() * 1e-6; break;
}
double e = est - th;
sq += e * e; ++n; if (std::fabs(e) > worst) worst = std::fabs(e);
if (dist) { sqd += e * e; ++nd; }
if (i == 12000) berr += std::fabs(bias_est - bias);
}
}
Out o = {std::sqrt(sq / n) * 57.2958, std::sqrt(sqd / nd) * 57.2958, worst * 57.2958, berr / seeds * 57.2958};
return o;
}
int main() {
float k0, k1;
settled_gains(0.005 * 0.005 * 0.01, 0.0005 * 0.0005, 0.09 * 0.09, k0, k1);
std::printf("heading from a gyro (100 Hz) and a compass (10 Hz, two 5 s disturbances of 20 degrees), 120 s, mean over 100 runs\n");
std::printf("settled Kalman gains at a compass update: K0 = %.5f (heading), K1 = %.6f (gyro offset, rad/s per rad); in Q16: %d and %d\n", k0, k1, (int)std::lround(k0 * 65536.0), (int)std::lround(k1 * 65536.0));
std::printf(" estimator rms error (deg) rms in the disturbances (deg) worst error (deg) offset error at the end (deg/s)\n");
const char* names[6] = {"gyro alone, offset calibrated at start", "compass alone", "complementary filter, tau 2 s", "Kalman, heading + gyro offset", "Kalman with a gate at 0.27 rad", "fixed-point, gains frozen (Q16)"};
for (int kind = 1; kind <= 6; ++kind) {
Out o = run(kind, 100, k0, k1);
if (kind == 1 || kind == 2 || kind == 3) std::printf(" %-40s %15.2f %29.2f %17.2f %31s\n", names[kind - 1], o.rms, o.rms_dist, o.worst, "-");
else std::printf(" %-40s %15.2f %29.2f %17.2f %31.3f\n", names[kind - 1], o.rms, o.rms_dist, o.worst, o.bias_err);
}
return 0;
}
heading from a gyro (100 Hz) and a compass (10 Hz, two 5 s disturbances of 20 degrees), 120 s, mean over 100 runs
settled Kalman gains at a compass update: K0 = 0.01866 (heading), K1 = -0.001743 (gyro offset, rad/s per rad); in Q16: 1223 and -114
estimator rms error (deg) rms in the disturbances (deg) worst error (deg) offset error at the end (deg/s)
gyro alone, offset calibrated at start 9.39 11.58 53.07 -
compass alone 7.90 20.54 38.68 -
complementary filter, tau 2 s 5.02 14.30 22.58 -
Kalman, heading + gyro offset 4.41 9.12 16.76 0.329
Kalman with a gate at 0.27 rad 1.84 3.14 13.53 0.096
fixed-point, gains frozen (Q16) 4.46 9.14 16.77 0.325
The ranking is not what the first intuition says. Each sensor alone is poor (9.4° and 7.9° rms; the compass is 20.5° off during the disturbances). The complementary filter helps (5.0°), and the Kalman filter is better again (4.4°) because it also tracks the gyro’s offset: a 0.33°/s error in it at the end of the run. But the two disturbances dominate everything: with the gate, which costs one comparison, the same filter is at 1.84° rms and 3.1° in the disturbances, 0.096°/s from the true offset. The expensive part of a filter was not the matrices; it was deciding when to ignore a sensor. The gate has a cost of its own that this run does not show: if the filter’s estimate were ever far wrong, it could keep rejecting the compass that would correct it (I did not test that case). And the integer filter with frozen gains is 4.46° against the float’s 4.41°: the arithmetic is not what limits the answer.
Position and speed along a wall
The same filter with f01 = +1 estimates a position and its speed. A range sensor gives the position every 60 ms (5 mm noise, 2 % of the readings missing); the wheels give the speed every 20 ms (8 mm/s noise). The robot accelerates, cruises and brakes. Compared: the raw reading and its difference over 60 ms; the filter with the range only; the filter with the range and the odometry speed, fused through update_x1:
// e_posvel.cpp -- position and speed along a wall from a range sensor and wheel odometry (host build; every sensor model is ASSUMED, not measured).
// Truth: the robot starts at 300 mm from the wall's reference, speeds up to 200 mm/s over 2 s, cruises, slows to a stop between 8 s and 10 s, and sits until 12 s.
// range every 60 ms: the true position + noise of 5 mm; 2 % of the readings are missing (the filter then only predicts)
// odometry every 20 ms: the true speed + noise of 8 mm/s
// Estimators: (1) the range reading itself, and its difference over 60 ms as the speed; (2) the 2-state Kalman filter (position, speed) fed with the range only;
// (3) the same filter also fed with the odometry speed (update_x1) every 20 ms. Units: mm and mm/s. 200 seeded runs.
// Scored: rms position error and rms speed error over the run, and over the 2 s of braking.
#include <cstdio>
#include <cmath>
#include "sim.h"
#include "est.h"
static double speed_at(double t) {
if (t < 2.0) return 100.0 * t;
if (t < 8.0) return 200.0;
if (t < 10.0) return 200.0 - 100.0 * (t - 8.0);
return 0.0;
}
struct Out { double pos, spd, pos_b, spd_b; };
static Out run(int kind, int seeds, double q1) {
double sp = 0, ss = 0, spb = 0, ssb = 0; long n = 0, nb = 0;
for (int seed = 1; seed <= seeds; ++seed) {
Rng rng((uint32_t)seed * 911u + 17u);
double x = 300.0, z = 300.0, zprev = 300.0, vz = 0.0;
Kalman2 kf(1.0f, 0.01f, (float)q1, 100.0f, 10000.0f);
kf.set(300.0f, 0.0f);
for (int i = 1; i <= 600; ++i) { // 20 ms steps, 12 s
double t = i * 0.02, v = speed_at(t);
x += v * 0.02;
kf.predict(0.0f, 0.02f);
if (i % 3 == 0) {
if (rng.uniform() >= 0.02) {
z = x + 5.0 * rng.normal();
vz = (z - zprev) / 0.06; zprev = z;
if (kind >= 2) kf.update_x0((float)z, 25.0f);
} else {
zprev = z; // missing reading: hold the last one
vz = 0.0;
}
}
if (kind == 3) kf.update_x1((float)(v + 8.0 * rng.normal()), 64.0f);
double ep, ev;
if (kind == 1) { ep = z - x; ev = vz - v; } else { ep = kf.x0() - x; ev = kf.x1() - v; }
sp += ep * ep; ss += ev * ev; ++n;
if (t > 8.0 && t <= 10.0) { spb += ep * ep; ssb += ev * ev; ++nb; }
}
}
Out o = {std::sqrt(sp / n), std::sqrt(ss / n), std::sqrt(spb / nb), std::sqrt(ssb / nb)};
return o;
}
int main() {
std::printf("position and speed along a wall, 12 s, mean over 200 runs (position in mm, speed in mm/s)\n");
std::printf(" estimator position rms speed rms position rms (braking) speed rms (braking)\n");
const char* names[3] = {"range reading, differenced for speed", "Kalman, range only", "Kalman, range + odometry speed"};
for (int kind = 1; kind <= 3; ++kind) {
Out o = run(kind, 200, 2000.0);
std::printf(" %-40s %12.2f %9.2f %22.2f %19.2f\n", names[kind - 1], o.pos, o.spd, o.pos_b, o.spd_b);
}
return 0;
}
position and speed along a wall, 12 s, mean over 200 runs (position in mm, speed in mm/s)
estimator position rms speed rms position rms (braking) speed rms (braking)
range reading, differenced for speed 6.65 121.06 5.98 119.21
Kalman, range only 3.44 17.03 3.93 23.91
Kalman, range + odometry speed 1.52 4.94 1.66 5.08
Differentiating a noisy reading is the worst way to get a speed: 121 mm/s rms against a top speed of 200 (the raw position is 6.65 mm rms, worse than the sensor’s 5 mm, because a missing reading repeats the last one). The filter with the range alone gets the speed to 17 mm/s and the position to 3.4 mm; the odometry speed, whose own noise (8 mm/s) is larger than the filter’s result, still improves both, to 4.9 mm/s and 1.5 mm, because the two sensors’ errors are independent. Here they are independent by construction: real wheels slip exactly when the range and the odometry disagree, and a real fusion needs a gate on the odometry too.
5. What it costs on the Uno
Everything above ran on a PC with hardware floating point. On the Uno every float operation is a call to a library routine, and every 32-bit integer division or multiplication is as well. The size test s_est.ino has six variants, each with one estimator step in a function of its own, fed from analogRead and printed as an integer so the compiler can neither remove it nor add the float printing code to some variants and not others. Variant 0 is the baseline with no estimator.
// s_est.ino -- cost test for chapter 10: the estimators on the Uno. Compile-checked only; NOT run on a board, no timing measured.
// VARIANT 0: baseline (nothing), 1: complementary float, 2: complementary fixed-point, 3: Kalman1 float, 4: Kalman2 float (predict + update), 5: HeadingFixed (predict + update).
// Each estimator step is a separate noinline function so avr-objdump can count its instructions.
#include "est.h"
#ifndef VARIANT
#define VARIANT 1
#endif
#if VARIANT == 1
static Complementary est(0.5f, 0.01f);
__attribute__((noinline)) float step(float rate, float meas) { return est.update(rate, meas, 0.01f); }
#elif VARIANT == 2
static ComplementaryFixed est(0.5f);
__attribute__((noinline)) int32_t step_fx(int32_t rate, int32_t meas) { return est.update(rate, meas); }
#elif VARIANT == 3
static Kalman1 est(0.0f, 1.0f, 1e-6f, 25.0f);
__attribute__((noinline)) float step(float, float meas) { est.update(meas); return est.x(); }
#elif VARIANT == 4
static Kalman2 est(-1.0f, 2.5e-7f, 2.5e-7f);
__attribute__((noinline)) float step(float rate, float meas) { est.predict(rate, 0.01f); est.update_x0(meas, 0.0081f); return est.x0(); }
#elif VARIANT == 5
static HeadingFixed est(1223, -114);
__attribute__((noinline)) int32_t step_fx(int32_t rate, int32_t meas) { est.predict(rate); est.update(meas); return est.heading(); }
#endif
void setup() { Serial.begin(115200); }
void loop() {
int a = analogRead(A0), b = analogRead(A1); // inputs the compiler cannot know
#if VARIANT == 0
Serial.println((int32_t)(a + b) * 1000L);
#elif VARIANT == 2 || VARIANT == 5
Serial.println(step_fx((int32_t)(a - 512) * 1000L, (int32_t)(b - 512) * 1000L));
#else
Serial.println((int32_t)(step((a - 512) * 0.01f, (b - 512) * 0.001f) * 1000.0f)); // every variant prints an int32, so Serial's float printing is not in the comparison
#endif
delay(10);
}
Compiled for the Uno with --warnings all (no warning from the sketch; the Arduino core’s own new.cpp printed four on the first build, before the core was cached):
Then the step function of each variant, from avr-objdump (script count_est.py): how many instructions it has and which library routines it calls. Calls are counted where they are written, not where they run; there are no loops in these functions, so each call is made once per step:
And the size of the routines those calls reach, from avr-nm:
$ avr-nm -S b_e4/s_est.ino.elf | grep the library routines: symbol sizes in bytes (static code size, not run time)
__addsf3x 204 bytes
__divsf3 8 bytes
__divsf3x 220 bytes
__mulsf3 8 bytes
__mulsf3x 210 bytes
__subsf3 14 bytes
__divmodsi4 46 bytes
__mulsi3 32 bytes
Three readings. The first float operation is the expensive one. The complementary filter’s step is 154 bytes, but the sketch grew by 1034, because the routines for add, subtract and multiply (about 200 bytes each) come with it. Programming for Robotics with Arduino C++ 9’s sketch already carried them, so there the marginal cost of a float filter is closer to the step function itself: 154 bytes for the complementary filter, 778 for Kalman2. The two-state filter is about five times the code of the one-line one (778 bytes, 304 instructions, 29 library calls against 154 bytes, 71 instructions, 6 calls), and the 2 × 2 matrices are the reason. Fixed-point is not free of library calls either.ComplementaryFixed has an instruction count higher than the float one (93 against 71) because of the division by 100 in rate / 100, which is a call to a 32-bit divide, and the multiplication by the gain is a call to a 32-bit multiply. On an AVR the integer routines are far smaller (46 and 32 bytes against about 200 for each float one) and I expect them to be faster; I did not time anything, so that is an expectation and not a result. What I can say from the table is that HeadingFixed, doing the work of the 304-instruction float filter with frozen gains, is 130 instructions, 314 bytes and 3 calls, and a quarter of the flash cost when the float library is not otherwise needed (+500 against +1966).
What fixed-point asks of you in exchange is design work the float version never needed. The units must be chosen so that a value fits: micro-radians keep the heading to 1 µrad in a 32-bit integer, and a gain is stored as an integer in Q16. Here y is clamped to ±2 000 000 and shifted by 4 before the multiplication, because y * gain in a plain int32_t overflows. The gains must be frozen: the full filter’s gains change while it converges, and a fixed gain is only right once they have settled, so the first seconds are worse (challenge 3 shows how many bits the gains need).
6. The robot
robot_ch10.ino is the heading filter on the robot. A gyro on the I2C bus is read every 10 ms and used as the input of the predict step, the wheel-encoder heading (the sum of the wheel differences as in Programming for Robotics with Arduino C++ 5) corrects it every 100 ms, the scheduler of Programming for Robotics with Arduino C++ 1 runs the three tasks, and the position is advanced along the estimated heading. At start-up it averages 200 readings with the robot still to take off most of the gyro’s offset, so the filter only has to learn the remainder. If the gyro stops answering, a few missed readings reuse the last rate and many mean the input is zero and the report says GYRO LOST: a filter that is silently fed a stale input is worse than one that knows it has none.
// robot_ch10.ino -- Programming for Robotics with Arduino C++, chapter 10: the heading from a gyro and the wheel encoders, fused by the two-state Kalman filter.
// Compile-checked for the Uno (arduino:avr:uno). NOT run on a board: nothing was attached. The gyro is assumed to be an MPU-6050-style chip on I2C address 0x68;
// its register numbers (0x6B power management, 0x47 gyro Z high byte) and its scale (131 LSB per degree/second at the +-250 deg/s range) are from MEMORY of the data sheet:
// NOT verified against it and NOT run. Check them before you trust a number from this sketch.
#include <Wire.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/atomic.h>
#include "scheduler.h"
#include "pins.h"
#include "motion.h"
#include "est.h"
const uint8_t GYRO_ADDR = 0x68;
const float GYRO_LSB_PER_RAD_S = 131.0f * 57.29578f; // 131 LSB per degree/second (from memory), per radian/second
const float WHEEL_R = 0.033f, TRACK = 0.150f;
const float PER_TICK = 6.2831853f * WHEEL_R / 360.0f;
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 bool gyro_read(int16_t& raw) { // one gyro Z reading; false if the bus did not answer
Wire.beginTransmission(GYRO_ADDR); Wire.write(0x47);
if (Wire.endTransmission(false) != 0) return false;
if (Wire.requestFrom(GYRO_ADDR, (uint8_t)2) != 2) return false;
raw = (int16_t)((Wire.read() << 8) | Wire.read());
return true;
}
static float gyro_offset = 0.0f; // rad/s, measured at start-up with the robot still
static Kalman2 heading(-1.0f, 2.5e-7f, 2.5e-7f, 1.0f, 0.01f); // x0 = heading (rad), x1 = gyro offset (rad/s); Q: ASSUMED, tune it (challenge 2)
static float enc_heading = 0.0f; // the heading from the wheels alone, as in chapter 5
static Pose pose = {0.0f, 0.0f, 0.0f};
static int32_t last_l = 0, last_r = 0;
static float last_rate = 0.0f;
static bool gyro_ok = false;
static uint8_t misses = 0;
static Scheduler<3> sch;
static void predict_task(void*, uint32_t) { // every 10 ms: predict with the gyro, move the pose
int16_t raw;
if (gyro_read(raw)) { last_rate = (float)raw / GYRO_LSB_PER_RAD_S - gyro_offset; misses = 0; gyro_ok = true; }
else if (misses < 255) { ++misses; if (misses > 5) gyro_ok = false; } // a few misses reuse the last rate; many mean the gyro is gone
heading.predict(gyro_ok ? last_rate : 0.0f, 0.01f);
int32_t l, r; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { l = g_ticks_l; r = g_ticks_r; }
float dl = (float)(l - last_l) * PER_TICK, dr = (float)(r - last_r) * PER_TICK;
last_l = l; last_r = r;
enc_heading += (dr - dl) / TRACK;
float m = heading.x0();
pose.x += 0.5f * (dl + dr) * cosf(m); pose.y += 0.5f * (dl + dr) * sinf(m); pose.th = m;
}
static void update_task(void*, uint32_t) { // every 100 ms: correct with the wheel heading (it slips, so r is large)
heading.update_x0(enc_heading, 0.01f);
}
static void report_task(void*, uint32_t now) {
Serial.print(now); Serial.print(F(" ms heading ")); Serial.print(heading.x0() * 57.29578f, 1);
Serial.print(F(" deg gyro offset ")); Serial.print(heading.x1() * 57.29578f, 2);
Serial.print(F(" deg/s wheels ")); Serial.print(enc_heading * 57.29578f, 1); Serial.println(gyro_ok ? F("") : F(" GYRO LOST"));
}
void setup() {
Serial.begin(115200);
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);
Wire.begin();
Wire.beginTransmission(GYRO_ADDR); Wire.write(0x6B); Wire.write((uint8_t)0); Wire.endTransmission(); // wake the chip (from memory of the data sheet)
float sum = 0.0f; uint8_t n = 0; // 200 readings with the robot still: its offset
for (uint8_t i = 0; i < 200; ++i) { int16_t raw; if (gyro_read(raw)) { sum += (float)raw / GYRO_LSB_PER_RAD_S; ++n; } delay(10); }
if (n > 100) { gyro_offset = sum / n; gyro_ok = true; }
Serial.print(F("gyro offset ")); Serial.print(gyro_offset * 57.29578f, 3); Serial.print(F(" deg/s from ")); Serial.print(n); Serial.println(F(" readings"));
sch.add(predict_task, 0, 10);
sch.add(update_task, 0, 100);
sch.add(report_task, 0, 500);
}
void loop() { sch.run(millis()); }
It compiles for the Uno under --warnings all with no warning from the sketch to:
Sketch uses 9726 bytes (30%) of program storage space. Maximum is 32256 bytes.
Global variables use 574 bytes (28%) of dynamic memory, leaving 1474 bytes for local variables. Maximum is 2048 bytes.
That is 9 726 bytes of flash and 574 bytes of RAM. It was not run: no chip was attached, the I2C address, register numbers and scale are from my memory of a data sheet and unverified, and the filter’s Q (2.5e-7 for both states) is a guess that must be tuned on the real gyro. Wheels that slip make the corrections wrong in exactly the situation they are needed, which is why a real robot would gate them as in section 4.
7. What the numbers can and cannot be trusted for
What they show. The shapes: a complementary filter has a best time constant that depends on the disturbance; a Kalman filter’s gain settles at a value computed from q and R (matching the formula), and a wrong q can be worse than no filter; a filter that estimates the gyro’s offset beats one that does not; a gate on the measurement matters more than the arithmetic; a speed from differencing is hopeless and one from fusion is not; the counts of instructions and library calls of each step, and the flash and RAM of each variant on the Uno.
What they do not show. Every sensor is a simulation with noise I chose: real gyro noise is not Gaussian and white, real offsets depend on temperature, a real compass is not merely off by 20° for 5 s, and real vibration is not one sine wave. The filter’s Q and R were set from the simulation’s own parameters, which a real robot does not know; and the filters are optimal only when the model matches, which here it does by construction. No time was measured: the Uno figures count bytes, instructions and library calls; a claim of speed (integer against float) would need a timer on a board. robot_ch10.ino was compiled, not run.
Challenge 1: The best time constant against the vibration
Repeat the tilt experiment with the accelerometer’s vibration at 0.5, 2, 5 and 20 Hz, and for each find the best time constant of the complementary filter among 0.05, 0.1, 0.2, 0.5, 1, 2 and 5 s. Say what the best tau does as the vibration gets faster, and why.
Sweep the speed process noise q1 (10 to 100 000) and the range noise R the filter is told (4, 25 and 250, when the true value is 25) for the range-only position and speed filter. Report the rms position and speed error and the lag: the time after the robot has stopped for the speed estimate to fall below 10 mm/s. What do q1 and R trade off, and what happens if you tell the filter the wrong R?
The fixed-point heading filter stores its gains as integers with F fractional bits. For F = 4 to 20, report the stored gains, the rms heading error and the error of the offset estimate, and compare with the float filter. How many bits are needed, and which gain is the one that decides it?
Complementary filter.angle = alpha (angle + rate dt) + (1 - alpha) measured, alpha = tau / (tau + dt). Tilt: gyro alone 37.5° rms, accelerometer alone 5.65°, best tau 0.2 s at 1.22°; 0.2 s was best at 6 Hz vibration, 1 s at 0.5 Hz and 0.1 s at 20 Hz.
Scalar Kalman.P += q; K = P / (P + R); x += K (z - x); P *= 1 - K. With q = 0, K = 1/k: a filter told nothing moves is 292 mm off a moving range; q 1e-5 and up beats the raw 4.99 mm (4.4 mm).
Two states.F = [1 f01 dt; 0 1], Q = diag(q0 dt, q1 dt) (a simple choice), one measurement at a time so s is a scalar. Heading + gyro offset: f01 = -1, gyro as input. Position + speed: f01 = +1.
Heading, 120 s, with two 20° compass disturbances. gyro 9.39°, compass 7.90°, complementary 5.02°, Kalman 4.41°, Kalman with a 0.27 rad gate 1.84° (3.14° inside the disturbances), fixed-point with frozen gains 4.46°. A gate is worth more than the arithmetic.
Position and speed. Differencing the range: 121 mm/s rms. Kalman, range only: 3.44 mm and 17.0 mm/s. With the odometry speed: 1.52 mm and 4.94 mm/s.
Cost on the Uno (compiled, not run). Flash over a 1960-byte baseline: complementary float +1034, fixed +376, Kalman1 +1388, Kalman2 +1966, HeadingFixed +500. Steps: 71, 93, 111, 304, 130 instructions; Kalman2 makes 29 float library calls, HeadingFixed 3 integer ones. Integer division by 100 is a library call too.
Fixed-point rules. Use micro-radians, not a per-step rounding of tiny increments; clamp the input before the multiply; freeze gains only after they settle; a gain that rounds to zero stops the filter learning.
Budget.robot_ch10.ino: 9 726 bytes flash (30 %), 574 bytes RAM (28 %), compiled, not run; the gyro’s register map is from memory and unverified; no time measured.
Not run: anything on a board; any real gyro, compass or range sensor; the speed of float against integer; the filters’ Q and R on real hardware.
Next: Programming for Robotics with Arduino C++ 11, Robot Arms in Code
Programming for Robotics with Arduino C++ 11 (planned; not yet written) moves from a robot that drives to one that reaches: forward and inverse kinematics of a two-link arm, trapezoidal speed profiles, the limits of the Servo library, pick-and-place on the simulator, and lookup tables in flash for the trigonometry the chip cannot afford to compute.