Sensor Code and Filtering

Programming for Robotics with Arduino C++

Course 2 · Chapter 4 · Sensor Code and Filtering

Programming for Robotics with Arduino C++ 3 ended with two loose ends. Challenge 1 bolted an averaging wrapper on at the seam and removed the ratchet bias, with a warning that the average costs delay; and robot_ch3.ino reported zero for the wheel encoders because they need interrupts. This chapter builds both properly: the small filters a robot needs, written without lists or the heap, with the ways each one fails, and the encoder code that runs inside an interrupt, with the one bug that interrupts invite.

Programming for Robotics with Arduino C++ 2 gave the rule that governs everything here: the Uno has 2048 bytes of RAM and 32,256 of flash, so every buffer has a size the compiler knows, and each piece is measured in bytes and cycles, not guessed at.

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. The signals are models with assumed noise, spike and chatter figures, and the IR sensor curve is an assumption, not any data sheet’s. Compiled for the Uno, not run (arduino-cli, core arduino:avr 1.8.8, --warnings all): the encoder sketch, the one-filter-at-a-time sketch and robot_ch4.ino. Flash and RAM figures are the compiler’s; instruction counts come from disassembling the compiled code with avr-objdump. Cycle counts add up the data-sheet cycles of each instruction; they were not measured on a chip. No board, encoder or sensor was attached. Nothing here was measured on hardware.

1. No lists: ring buffers of fixed size

Python’s collections.deque(maxlen=5) is a list that forgets its oldest entry, and it grows and shrinks as it likes. A filter on a microcontroller needs the same behaviour in memory that is reserved once. The standard answer is a ring buffer: an array of N values, a write position that wraps from the end back to the start, and a count of how many values are valid. Pushing overwrites the oldest value once the array is full. The array’s size is a template parameter, so its RAM cost is known at compile time: Ring<int16_t, N> costs 2N + 2 bytes (the values, a head and a count).

In PythonOn the Uno in C++
readings = deque(maxlen=5)Ring<int16_t, 5> readings; 12 bytes, reserved at compile time, never grows
statistics.median(readings)a copy of at most N values, sorted by insertion sort: no allocation, and N is tiny
sum(readings) / len(readings)a running int32_t sum, or a loop over the buffer; the float version has a trap (section 4)
a variable another thread changes: the interpreter protects a single assignment for youa volatile variable an interrupt changes, read with interrupts off (section 9)
an integer never overflows or loses precisionshifts throw away bits (section 5); a float has 24 bits of precision (section 4)

Here is everything this chapter needs from the filters, in one header. Each class takes the numbers it needs and nothing else; none calls an Arduino function, so the same file runs in the PC experiments and compiles into the sketch.

// filters.h -- fixed-size buffers and the small filters a robot needs (Programming for Robotics with Arduino C++ 4). // Plain C++11: no Arduino calls, no heap, no lists. Every buffer's size is a template parameter, so its RAM cost is known at compile time. #pragma once #include <stdint.h> // ---- a ring buffer: the newest N values, oldest overwritten ---- template <class T, uint8_t N> class Ring { static_assert(N > 0, "a ring buffer needs a size of at least 1"); public: Ring() : head_(0), count_(0) {} void push(T v) { buf_[head_] = v; head_ = (uint8_t)((head_ + 1) % N); if (count_ < N) ++count_; } uint8_t size() const { return count_; } bool full() const { return count_ == N; } T at(uint8_t i) const { return buf_[(uint8_t)((head_ + N - count_ + i) % N)]; } // i = 0 is the oldest value held T oldest() const { return at(0); } T newest() const { return at((uint8_t)(count_ - 1)); } private: T buf_[N]; uint8_t head_, count_; }; // ---- debounce: the output changes only after the input has disagreed with it for n samples IN A ROW ---- class Debounce { public: explicit Debounce(uint8_t n, bool initial = false) : n_(n), count_(0), state_(initial) {} bool update(bool raw) { if (raw == state_) count_ = 0; else if (++count_ >= n_) { state_ = raw; count_ = 0; } return state_; } bool state() const { return state_; } private: uint8_t n_, count_; bool state_; }; // ---- median of the last N values (N odd): rejects spikes completely, with no averaging of them ---- template <class T, uint8_t N> class Median { static_assert(N % 2 == 1, "a median window must be odd"); public: T update(T x) { ring_.push(x); T tmp[N]; uint8_t n = ring_.size(); for (uint8_t i = 0; i < n; ++i) { // insertion sort of a COPY, at most N values T v = ring_.at(i); uint8_t j = i; while (j > 0 && tmp[j - 1] > v) { tmp[j] = tmp[j - 1]; --j; } tmp[j] = v; } return tmp[n / 2]; } private: Ring<T, N> ring_; }; // ---- moving average of the last N values ---- template <uint8_t N> class MovingAvgInt { // integer running sum: exact, forever public: MovingAvgInt() : sum_(0) {} int16_t update(int16_t x) { if (ring_.full()) sum_ -= ring_.oldest(); ring_.push(x); sum_ += x; return (int16_t)(sum_ / ring_.size()); } private: Ring<int16_t, N> ring_; int32_t sum_; }; template <uint8_t N> class MovingAvgFloatSum { // the same idea in floats: add the new, subtract the old, divide. It looks the same and is not. public: MovingAvgFloatSum() : sum_(0.0f) {} float update(float x) { if (ring_.full()) sum_ -= ring_.oldest(); ring_.push(x); sum_ += x; return sum_ / ring_.size(); } private: Ring<float, N> ring_; float sum_; }; template <uint8_t N> class MovingAvgFloatSafe { // the float version that cannot drift: add up the whole window again every time (N additions) public: float update(float x) { ring_.push(x); float sum = 0.0f; for (uint8_t i = 0; i < ring_.size(); ++i) sum += ring_.at(i); return sum / ring_.size(); } private: Ring<float, N> ring_; }; // ---- exponential filter: y += a (x - y) ---- class EmaFloat { public: explicit EmaFloat(float a) : a_(a), y_(0.0f), init_(false) {} float update(float x) { if (!init_) { y_ = x; init_ = true; } else y_ += a_ * (x - y_); return y_; } private: float a_, y_; bool init_; }; // a = 1 / 2^K in integers. THIS ONE LOOKS RIGHT AND STALLS: when |x - y| < 2^K the shifted difference is zero (or -1), so y stops short of x. template <uint8_t K> class EmaIntNaive { public: EmaIntNaive() : y_(0), init_(false) {} int16_t update(int16_t x) { if (!init_) { y_ = x; init_ = true; } else y_ += (int16_t)((x - y_) >> K); return y_; } // >> of a negative number is implementation-defined in C++11 private: int16_t y_; bool init_; }; // The fix: keep K extra BITS of y. acc holds y x 2^K, so the rounding that the shift throws away is kept in the low bits and fed back. template <uint8_t K> class EmaIntGuard { public: EmaIntGuard() : acc_(0), init_(false) {} int16_t update(int16_t x) { if (!init_) { acc_ = (int32_t)x * (1L << K); init_ = true; } else acc_ += (int32_t)x - (acc_ / (1L << K)); // a division, not a shift: well defined for negative numbers too return (int16_t)((acc_ + (1L << (K - 1))) / (1L << K)); // round to nearest } private: int32_t acc_; bool init_; };

2. Debounce: a switch that lies for a few milliseconds

A bumper switch is metal touching metal, and the contact flickers for a few milliseconds each time it closes or opens. A program that reads the pin every millisecond sees a press as several. The cure is to accept a change only after the pin has disagreed with the current state n samples in a row, which is the Debounce class above. The experiment gives every press and release 0 to 8 ms of random chatter (an assumed model of the switch) and reads once a millisecond:

// e_debounce.cpp -- a bumper switch that chatters when pressed and released: how many presses does the program see? (host build, a seeded model of the switch) // MODEL: every real change of the switch is followed by 0 to 8 ms of random chatter (the contact flickers each millisecond), then it settles. The program reads the pin once per millisecond. #include <cstdio> #include <initializer_list> #include "sim.h" // the seeded Rng #include "filters.h" struct Result { int presses_seen; double latency_sum_ms; int latency_n; int missed; }; static Result run(uint8_t n, double press_ms, uint32_t seed) { Rng rng(seed); Debounce deb(n); Result r = {0, 0.0, 0, 0}; const int PRESSES = 50; const uint32_t period = 400; // one press every 400 ms bool prev_out = false; uint32_t press_start = 0; bool waiting = false; bool seen_this = false; uint32_t total = (uint32_t)PRESSES * period; // exactly 50 press cycles for (uint32_t t = 0; t < total; ++t) { uint32_t phase = t % period; bool truth = phase >= 100 && phase < 100 + (uint32_t)press_ms; // pressed from 100 ms for press_ms // chatter: for the first `bounce` ms after each real edge, the contact flickers static uint32_t last_edge, bounce; static bool last_truth; if (t == 0) { last_edge = 0; bounce = 0; last_truth = false; } if (truth != last_truth) { last_edge = t; bounce = (uint32_t)(rng.uniform() * 9.0); last_truth = truth; } bool pin = truth; if (t - last_edge < bounce) pin = rng.uniform() < 0.5; if (phase == 100) { press_start = t; waiting = true; seen_this = false; } bool out = deb.update(pin); if (out && !prev_out) { // a rising edge of the DEBOUNCED signal: the program sees a press ++r.presses_seen; if (waiting && !seen_this) { r.latency_sum_ms += (double)(t - press_start); ++r.latency_n; seen_this = true; } } prev_out = out; } r.missed = PRESSES - r.latency_n; // presses that were never seen at all return r; } int main() { std::printf("50 presses of a switch with 0..8 ms of chatter after every change; the pin is read once per ms\n"); std::printf(" press length samples in a row press events seen (true: 50) mean delay ms presses never seen\n"); for (double len : {30.0, 4.0}) for (uint8_t n : {1, 3, 5, 10, 20}) { Result r = run(n, len, 1); std::printf(" %9.0f ms %16u %17d %10s %13.1f %18d\n", len, (unsigned)n, r.presses_seen, "", r.latency_n ? r.latency_sum_ms / r.latency_n : 0.0, r.missed); } return 0; }
50 presses of a switch with 0..8 ms of chatter after every change; the pin is read once per ms press length samples in a row press events seen (true: 50) mean delay ms presses never seen 30 ms 1 129 0.6 0 30 ms 3 52 4.8 0 30 ms 5 50 7.0 0 30 ms 10 50 12.0 0 30 ms 20 50 22.0 0 4 ms 1 103 0.7 0 4 ms 3 32 3.6 19 4 ms 5 12 4.6 38 4 ms 10 0 0.0 50 4 ms 20 0 0.0 50

Read the table from both ends. With no debounce (1 sample), a 30 ms press produced 129 press events for 50 true presses. Three samples in a row still gave 52, because eight milliseconds of chatter can include three equal readings in a row by chance; five samples gave exactly 50, at a mean delay of 7.0 ms, and 20 gave 50 at 22.0 ms. So the debounce time must be longer than the longest chatter, and every extra sample is delay added to every real press.

The lower half is the trap. A 4 ms tap is shorter than the chatter, so with 5 samples in a row only 12 of the 50 taps produced an event and 38 were never seen, and with 10 samples all 50 were missed. Debounce is a low-pass filter on a logic signal: it removes anything shorter than its window, whether that is chatter or a real, brief press. Choose the window from the shortest press that matters, not from the worst chatter alone; a bumper that must catch a brush against an obstacle needs a short window and a switch that chatters less.

3. Median or average? It depends on what the errors look like

An ultrasonic sensor makes two kinds of mistake: noise (a few millimetres either way), and outliers: no echo, or an echo from something off to the side, 3 m instead of 1 m. An average treats an outlier as data and smears it over the next N readings. A median sorts the last N values and takes the middle one, so one wrong value among N is simply discarded. The experiment feeds nine filters the same 200 seeded runs of a range falling from 2000 mm to 300 mm (5 mm noise, 5 % no-echo readings held, 3 % wrong echoes), and also a clean step from 1000 mm to 500 mm to measure delay:

// e_filters.cpp -- seven ways to filter an ultrasonic range, on a noisy signal with dropouts and spikes, and on a clean step (host build, seeded; the signal is a MODEL) // Signal: the true range falls from 2000 mm to 300 mm at 200 mm/s, one reading per 20 ms. Each reading: 5 mm of Gaussian noise; 5 % no echo (-1); // 3 % wrong echoes (a random value 0..4000 mm). Dropouts do not reach the filter: it holds its last output. #include <cstdio> #include <cmath> #include "filters.h" #include "sim.h" struct Acc { double sq = 0, worst = 0; long n = 0; }; template <class F> static void run_noisy(F& f, Acc& a, uint32_t seed) { Rng rng(seed); int16_t out = 2000; const int N = 425; // 8.5 s of 20 ms readings for (int i = 0; i < N; ++i) { double truth = 2000.0 - 200.0 * (i * 0.02); double u = rng.uniform(); int16_t x; if (u < 0.05) x = -1; // no echo else if (u < 0.08) x = (int16_t)(rng.uniform() * 4000.0); // a wrong echo else x = (int16_t)std::lround(truth + 5.0 * rng.normal()); if (x >= 0) out = f.update(x); // dropouts are skipped: the output holds if (i >= 20) { double e = out - truth; a.sq += e * e; if (std::fabs(e) > a.worst) a.worst = std::fabs(e); ++a.n; } } } template <class F> static int step_samples(F& f) { // clean step 1000 -> 500 mm: how many readings until the output is within 25 mm of 500? for (int i = 0; i < 100; ++i) f.update(1000); for (int i = 1; i <= 200; ++i) { int16_t y = f.update(500); if (y <= 525) return i; } return -1; } struct Raw { int16_t update(int16_t x) { return x; } }; struct Cascade { Median<int16_t, 5> m; EmaIntGuard<2> e; int16_t update(int16_t x) { return e.update(m.update(x)); } }; template <class F> static void row(const char* name) { Acc a; for (uint32_t seed = 1; seed <= 200; ++seed) { F f; run_noisy(f, a, seed); } F g; int s = step_samples(g); std::printf(" %-28s %9.1f %9.1f %14d %13d\n", name, std::sqrt(a.sq / a.n), a.worst, s, s * 20); } int main() { std::printf("200 seeded runs of the falling range (5 mm noise, 5 %% no echo held, 3 %% wrong echoes), and one clean step 1000 -> 500 mm:\n"); std::printf(" filter rms mm worst mm readings to 500+25 ms at 20 ms\n"); row<Raw>("none (hold on no echo)"); row<Median<int16_t, 3> >("median of 3"); row<Median<int16_t, 5> >("median of 5"); row<Median<int16_t, 9> >("median of 9"); row<MovingAvgInt<5> >("moving average of 5"); row<MovingAvgInt<9> >("moving average of 9"); row<EmaIntGuard<2> >("exponential, a = 1/4"); row<EmaIntGuard<3> >("exponential, a = 1/8"); row<Cascade>("median of 5, then a = 1/4"); return 0; }
200 seeded runs of the falling range (5 mm noise, 5 % no echo held, 3 % wrong echoes), and one clean step 1000 -> 500 mm: filter rms mm worst mm readings to 500+25 ms at 20 ms none (hold on no echo) 271.5 3545.0 1 20 median of 3 49.7 3277.0 2 40 median of 5 12.4 2155.0 3 60 median of 9 17.8 48.0 5 100 moving average of 5 126.4 1800.0 5 100 moving average of 9 101.0 1011.0 9 180 exponential, a = 1/4 110.7 1486.0 11 220 exponential, a = 1/8 91.0 903.0 23 460 median of 5, then a = 1/4 22.4 561.0 13 260

With no filter the rms error is 271.5 mm, almost all of it from wrong echoes (worst 3545 mm). Averaging helps little: a moving average of 5 is still 126.4 mm rms and its worst error is 1800 mm, because one wrong echo of 3000 mm shifts the average by 600 mm for five readings. The median of 5 gets to 12.4 mm. The median of 9 has a better worst case (48 mm against 2155) but a worse rms (17.8 against 12.4): a bigger window lags the falling ramp more, and 200 mm/s is 4 mm per reading, so a median of N lags by about (N − 1)/2 readings.

The cost is in the last two columns: the median of 5 needs 3 readings (60 ms) to follow a step, the exponential filter with a = 1/8 needs 23 (460 ms), and the cascade (median of 5 to throw out spikes, then an exponential filter to smooth the noise) gave 22.4 mm rms for 13 readings of delay. Smoothing and delay are the same thing: a controller that acts on a 460 ms old range will overshoot a wall that is approaching, and this is why chapter 3’s controller could use an average of 9 and a faster one could not.

A median is not magic either. It fails when more than half of its window is wrong; challenge 1 tabulates when that happens and compares it with the binomial chance.

4. The moving average that drifts

The fast way to a moving average is a running sum: add the new value, subtract the one that falls out, divide. In integers this is exact forever, and MovingAvgInt uses a 32-bit sum. In floats it looks identical and is not, because a float keeps about seven decimal digits, and every add and subtract rounds. The rounding errors do not cancel; they accumulate, in a sum that is never recomputed. The experiment runs a moving average of 8 on 10 million samples (at 50 Hz that is 2.3 days) for three input sizes, against a recompute-every-time float version and the exact answer:

// e_madrift.cpp -- a moving average of 8 values, kept as a running sum in float, against the same average recomputed each time, against the exact answer (host build) #include <cstdio> #include <cmath> #include <initializer_list> #include "filters.h" // The input is a value near `offset` that wobbles by +-3 in a fixed pattern. The exact answer is computed in double from the last 8 inputs. static double input(long i, double offset) { return offset + 3.0 * std::sin(0.01 * i) + 0.1 * (i % 7); } static void trial(double offset, long checkpoints[], int ncp) { MovingAvgFloatSum<8> running; MovingAvgFloatSafe<8> safe; double window[8] = {0}; int cp = 0; for (long i = 1; i <= checkpoints[ncp - 1]; ++i) { double x = input(i, offset); float fx = (float)x; // what the board would hold float r = running.update(fx), s = safe.update(fx); window[i % 8] = fx; if (i == checkpoints[cp]) { double exact = 0; int n = i < 8 ? (int)i : 8; for (int k = 0; k < n; ++k) exact += window[((i - k) % 8 + 8) % 8]; exact /= n; std::printf(" %9ld samples running sum %12.4f (error %+9.4f) recomputed %12.4f (error %+9.4f)\n", i, r, r - exact, s, s - exact); ++cp; } } } int main() { long cps[] = {1000, 100000, 1000000, 10000000}; std::printf("input near 1000 (like a range in mm):\n"); trial(1000.0, cps, 4); std::printf("input near 100000 (a larger offset, e.g. a scaled quantity):\n"); trial(100000.0, cps, 4); std::printf("input near 1000000:\n"); trial(1000000.0, cps, 4); // the integer version for comparison: exact by construction MovingAvgInt<8> iv; long long window[8] = {0}; int16_t last = 0; long long worst = 0; for (long i = 1; i <= 10000000; ++i) { int16_t x = (int16_t)(1000 + (long)(3.0 * std::sin(0.01 * i)) + (i % 7)); last = iv.update(x); window[i % 8] = x; if (i % 100000 == 0) { long long sum = 0; for (int k = 0; k < 8; ++k) sum += window[k]; long long exact_floor = sum / 8; long long d = last > exact_floor ? last - exact_floor : exact_floor - last; if (d > worst) worst = d; } } std::printf("integer running sum (int32), 10,000,000 samples, checked every 100,000: the largest difference from the exact average is %lld\n", worst); return 0; }
input near 1000 (like a range in mm): 1000 samples running sum 998.7951 (error +0.0002) recomputed 998.7949 (error -0.0001) 100000 samples running sum 1002.7531 (error +0.0087) recomputed 1002.7444 (error +0.0000) 1000000 samples running sum 999.4631 (error +0.0042) recomputed 999.4589 (error -0.0000) 10000000 samples running sum 1000.6138 (error +0.1017) recomputed 1000.5121 (error +0.0000) input near 100000 (a larger offset, e.g. a scaled quantity): 1000 samples running sum 99998.9062 (error +0.1113) recomputed 99998.7969 (error +0.0020) 100000 samples running sum 100002.3438 (error -0.4023) recomputed 100002.7500 (error +0.0039) 1000000 samples running sum 99993.8203 (error -5.6377) recomputed 99999.4609 (error +0.0029) 10000000 samples running sum 99946.7656 (error -53.7461) recomputed 100000.5000 (error -0.0117) input near 1000000: 1000 samples running sum 999999.3750 (error +0.5859) recomputed 999998.8750 (error +0.0859) 100000 samples running sum 1000034.7500 (error +32.0000) recomputed 1000002.7500 (error +0.0000) 1000000 samples running sum 1000319.5625 (error +320.1016) recomputed 999999.3750 (error -0.0859) 10000000 samples running sum 1003200.1250 (error +3199.6172) recomputed 1000000.5000 (error -0.0078) integer running sum (int32), 10,000,000 samples, checked every 100,000: the largest difference from the exact average is 0

For an input near 1000 the drift is small: 0.1017 after 10 million samples. For an input near 100000 the running sum is off by 53.7 and near 1,000,000 by 3199.6, while the recomputed version stays within 0.09 everywhere and the integer sum is exact (largest difference 0 over 10 million). The lesson is not “never use a float running sum”; it is that the error grows with the size of the values and the length of the run, and a robot that runs for days with an offset reading can hit both. Two safe options are the integer sum, or the float version that adds up the whole window each time (N additions, instead of two).

5. The exponential filter, and the integer one that stalls

The cheapest filter of all keeps no buffer: y += a * (x - y), with a between 0 and 1. It needs one number of RAM. The integer version chooses a = 1/2K so the multiply becomes a shift, and here is the trap: the shift throws bits away, and when the difference between input and output is smaller than 2K the shifted difference is zero, so the output stops moving, short of the input. The experiment holds a constant input for 2000 samples and reports where each version ends:

// e_ema.cpp -- the exponential filter in float, in integers with a plain shift, and in integers with guard bits: where do they end up? (host build) #include <cstdio> #include <cmath> #include "filters.h" #include "sim.h" template <class F> static int settle(F& f, int16_t from, int16_t to, int steps) { // feed `from` for a while, then `to` for `steps` samples; return the last output for (int i = 0; i < 400; ++i) f.update(from); int16_t y = from; for (int i = 0; i < steps; ++i) y = f.update(to); return y; } int main() { std::printf("final output after 2000 samples of a constant input (a step from 0, and a step down from 1000):\n"); std::printf(" filter step 0 -> 1000 step 1000 -> 0 step 0 -> 37 step 0 -> 5\n"); { EmaIntNaive<2> a, b, c, d; std::printf(" integer, plain shift, K=2 (1/4) %14d %15d %12d %11d\n", settle(a, 0, 1000, 2000), settle(b, 1000, 0, 2000), settle(c, 0, 37, 2000), settle(d, 0, 5, 2000)); } { EmaIntNaive<3> a, b, c, d; std::printf(" integer, plain shift, K=3 (1/8) %14d %15d %12d %11d\n", settle(a, 0, 1000, 2000), settle(b, 1000, 0, 2000), settle(c, 0, 37, 2000), settle(d, 0, 5, 2000)); } { EmaIntNaive<5> a, b, c, d; std::printf(" integer, plain shift, K=5 (1/32)%14d %15d %12d %11d\n", settle(a, 0, 1000, 2000), settle(b, 1000, 0, 2000), settle(c, 0, 37, 2000), settle(d, 0, 5, 2000)); } { EmaIntGuard<3> a, b, c, d; std::printf(" integer, guard bits, K=3 (1/8) %14d %15d %12d %11d\n", settle(a, 0, 1000, 2000), settle(b, 1000, 0, 2000), settle(c, 0, 37, 2000), settle(d, 0, 5, 2000)); } { EmaIntGuard<5> a, b, c, d; std::printf(" integer, guard bits, K=5 (1/32)%14d %15d %12d %11d\n", settle(a, 0, 1000, 2000), settle(b, 1000, 0, 2000), settle(c, 0, 37, 2000), settle(d, 0, 5, 2000)); } std::printf("\nagainst the float filter (a = 1/8) on a noisy ramp, 20000 samples of 5 mm noise round a slope (whole millimetres in, whole millimetres out):\n"); Rng rng(3); EmaFloat ref(0.125f); EmaIntNaive<3> naive; EmaIntGuard<3> guard; double sn = 0, sg = 0, mn = 0, mg = 0; int n = 0; for (int i = 0; i < 20000; ++i) { double truth = 3000.0 - 0.1 * i; // falls 0.1 mm per sample, so the filter always lags a little int16_t x = (int16_t)std::lround(truth + 5.0 * rng.normal()); float r = ref.update((float)x); int16_t a = naive.update(x), b = guard.update(x); if (i > 100) { double dn = a - r, dg = b - r; sn += dn * dn; sg += dg * dg; mn += dn; mg += dg; ++n; } } std::printf(" plain shift : mean difference from the float filter %+6.2f mm, rms %.2f mm\n", mn / n, std::sqrt(sn / n)); std::printf(" guard bits : mean difference from the float filter %+6.2f mm, rms %.2f mm\n", mg / n, std::sqrt(sg / n)); return 0; }
final output after 2000 samples of a constant input (a step from 0, and a step down from 1000): filter step 0 -> 1000 step 1000 -> 0 step 0 -> 37 step 0 -> 5 integer, plain shift, K=2 (1/4) 997 0 34 2 integer, plain shift, K=3 (1/8) 993 0 30 0 integer, plain shift, K=5 (1/32) 969 0 6 0 integer, guard bits, K=3 (1/8) 1000 1 37 5 integer, guard bits, K=5 (1/32) 1000 1 37 5 against the float filter (a = 1/8) on a noisy ramp, 20000 samples of 5 mm noise round a slope (whole millimetres in, whole millimetres out): plain shift : mean difference from the float filter -3.46 mm, rms 3.51 mm guard bits : mean difference from the float filter +0.50 mm, rms 0.58 mm

With the plain shift and K = 3, a step from 0 to 1000 ends at 993, which is 2K − 1 = 7 short; a step to 37 ends at 30; and a step from 0 to 5 never moves off 0, for K = 3 or 5. On the noisy ramp the plain shift reads an average of 3.46 mm low (about (2K − 1)/2), against +0.50 mm for the version with guard bits. The fix is to keep K extra bits of the output: the accumulator holds the output times 2K, so the rounding the shift would discard stays in the low bits and is fed back. The guard-bit version reaches 1000, 37 and 5. It is not perfect: falling to 0 ends at 1, a residue of the truncating division, and challenge 2 explores how many guard bits that costs to remove.

6. Calibration: from counts to distance and position

Every sensor reports a number, and a calibration turns it into the quantity the robot needs. Two examples show the two kinds of work involved. Both sensor models below are assumptions made for these experiments, not any manufacturer’s curve.

An infrared distance sensor reports a curve that falls as an object recedes, roughly counts = 80 + 52000/(d + 40) from 100 to 800 mm, and folds back below 100 mm (the reading falls as the object gets too close). One function inverts the curve by formula (a float division, 900 bytes of flash in section 10); the other uses a table of N distances at evenly spaced counts and interpolates (integers only, but the table takes RAM). The line-sensor array has five sensors with different gain and offset, so its raw reading of the same line depends on which sensor sees it; the calibration sweeps over the line and floor, remembers each sensor’s minimum and maximum, and scales every reading to 0 to 1000 before the weighted position is taken.

// calib.h -- turning raw sensor numbers into units (Programming for Robotics with Arduino C++ 4). Plain C++11, no Arduino calls. // The IR curve is an ASSUMPTION used for the experiments, not any datasheet's: counts(d) = 80 + 52000 / (d + 40) for d = 100..800 mm, // and below 100 mm the reading FOLDS BACK (counts fall as the object gets closer), here counts = 451 * d / 100. #pragma once #include <stdint.h> inline float ir_counts_model(float d_mm) { if (d_mm < 100.0f) return 451.0f * d_mm / 100.0f; return 80.0f + 52000.0f / (d_mm + 40.0f); } // Method 1: invert the formula. One float division. Only valid on the far side of the peak (counts 142..451, i.e. 100..800 mm). inline float ir_dist_formula(int16_t counts) { if (counts <= 80) return 9999.0f; // beyond the end of the curve: treat as "far" return 52000.0f / (float)(counts - 80) - 40.0f; } // Method 2: a table of distances at N evenly spaced counts from C_LO to C_HI, linear interpolation between neighbours. Integers only. // table[i] is the distance (mm) for counts C_LO + i * STEP, nearest integer; counts outside the range clamp to the end entries. template <uint8_t N> class IrTable { static_assert(N >= 2, "a table needs at least two entries"); public: IrTable(const int16_t* table, int16_t c_lo, int16_t c_hi) : t_(table), lo_(c_lo), span_((int16_t)(c_hi - c_lo)) {} int16_t dist(int16_t counts) const { int32_t pos = (int32_t)(counts - lo_) * (N - 1); // position in table units, times span if (pos <= 0) return t_[0]; if (pos >= (int32_t)span_ * (N - 1)) return t_[N - 1]; int32_t i = pos / span_; // lower entry int32_t frac = pos - i * span_; // 0..span-1 int32_t a = t_[i], b = t_[i + 1]; return (int16_t)(a + ((b - a) * frac + (b - a >= 0 ? span_ / 2 : -span_ / 2)) / span_); } private: const int16_t* t_; int16_t lo_, span_; }; // A line sensor array: five reflectance sensors, each with its own gain and offset. Min/max calibration: sweep the array over the line and the // floor, remember each sensor's smallest and largest reading, then scale every reading to 0..1000. template <uint8_t N> class LineCal { public: LineCal() { for (uint8_t i = 0; i < N; ++i) { min_[i] = 32767; max_[i] = -32768; } } void learn(const int16_t* raw) { for (uint8_t i = 0; i < N; ++i) { if (raw[i] < min_[i]) min_[i] = raw[i]; if (raw[i] > max_[i]) max_[i] = raw[i]; } } int16_t scaled(uint8_t i, int16_t raw) const { int32_t range = (int32_t)max_[i] - min_[i]; if (range < 1) return 0; int32_t v = ((int32_t)(raw - min_[i]) * 1000L) / range; if (v < 0) v = 0; if (v > 1000) v = 1000; return (int16_t)v; } private: int16_t min_[N], max_[N]; }; // Weighted position of a line under the array: sum(pos_i * v_i) / sum(v_i), in the units of pos (here mm). Returns false if nothing sees the line. template <uint8_t N> inline bool line_position(const int16_t* v, const int16_t* pos_mm, float& out) { int32_t num = 0, den = 0; for (uint8_t i = 0; i < N; ++i) { num += (int32_t)pos_mm[i] * v[i]; den += v[i]; } if (den < 100) return false; out = (float)num / (float)den; return true; }
// e_calib.cpp -- calibrating two sensors (host build; both sensor models are ASSUMPTIONS, not datasheet curves) // Part 1: an IR distance sensor. Its curve is counts = 80 + 52000/(d+40) from 100 to 800 mm. Two inverse methods: the formula and a lookup table. // Part 2: a five-sensor line array with different gain and offset on every sensor: weighted position with and without min/max calibration. #include <cstdio> #include <cmath> #include <cstdlib> #include <initializer_list> #include "calib.h" #include "sim.h" static int16_t counts_at(float d) { return (int16_t)std::lround(ir_counts_model(d)); } int main() { // ---- part 1a: how much distance does 2 counts of noise cost? ---- std::printf("IR sensor (assumed curve): distance error caused by +2 counts of ADC noise, formula inversion\n"); std::printf(" true mm counts distance for counts+2 error mm error %%\n"); for (int d : {100, 200, 400, 800}) { int16_t c = counts_at((float)d); float est = ir_dist_formula((int16_t)(c + 2)); std::printf(" %7d %6d %21.1f %8.1f %7.1f\n", d, c, est, est - d, 100.0 * (est - d) / d); } std::printf(" (and the same sensor at 50 mm reads %d counts: the SAME as it reads at about %d mm)\n", counts_at(50.0f), (int)std::lround(ir_dist_formula(counts_at(50.0f)))); // ---- part 1b: lookup table size vs interpolation error (noise-free, whole range) ---- std::printf("\nlookup table of N distances at evenly spaced counts (142..451), linear interpolation: worst error over every count in range\n"); std::printf(" entries N worst error mm at counts ints in table (bytes)\n"); const int16_t C_LO = counts_at(800.0f), C_HI = counts_at(100.0f); const int Ns[] = {4, 8, 16, 32}; for (int n : Ns) { static int16_t tab[64]; for (int i = 0; i < n; ++i) { float c = C_LO + (float)(C_HI - C_LO) * i / (n - 1); tab[i] = (int16_t)std::lround(ir_dist_formula((int16_t)std::lround(c))); } double worst = 0; int wc = 0; for (int c = C_LO; c <= C_HI; ++c) { int16_t est; switch (n) { case 4: { IrTable<4> t(tab, C_LO, C_HI); est = t.dist((int16_t)c); } break; case 8: { IrTable<8> t(tab, C_LO, C_HI); est = t.dist((int16_t)c); } break; case 16: { IrTable<16> t(tab, C_LO, C_HI); est = t.dist((int16_t)c); } break; default: { IrTable<32> t(tab, C_LO, C_HI); est = t.dist((int16_t)c); } break; } double e = std::fabs(est - ir_dist_formula((int16_t)c)); if (e > worst) { worst = e; wc = c; } } std::printf(" %9d %14.1f %9d %21d\n", n, worst, wc, n * 2); } // ---- part 2: a line array ---- const int16_t pos[5] = {-40, -20, 0, 20, 40}; float gain[5] = {1.00f, 0.80f, 1.15f, 0.70f, 1.05f}; float off[5] = { 30, 90, 10, 120, 60}; Rng rng(7); LineCal<5> cal; auto read = [&](float x, int16_t* raw) { // x = the line's centre, mm; a triangular response 25 mm wide each side for (int i = 0; i < 5; ++i) { float r = 1.0f - std::fabs(x - pos[i]) / 25.0f; if (r < 0) r = 0; raw[i] = (int16_t)std::lround(off[i] + gain[i] * 800.0f * r + 2.0 * rng.normal()); } }; int16_t raw[5]; for (float x = -70; x <= 70; x += 1.0f) { read(x, raw); cal.learn(raw); } // the calibration sweep: line and floor both seen std::printf("\nline array: position of a line from -30 to +30 mm, reading each sensor with 2 counts of noise; error = estimate - truth (mm)\n"); std::printf(" true mm uncalibrated error calibrated error\n"); double worst_raw = 0, worst_cal = 0, sq_raw = 0, sq_cal = 0; int n = 0; for (int x = -30; x <= 30; x += 5) { read((float)x, raw); int16_t scaled[5]; for (int i = 0; i < 5; ++i) scaled[i] = cal.scaled((uint8_t)i, raw[i]); float pr = 0, pc = 0; line_position<5>(raw, pos, pr); line_position<5>(scaled, pos, pc); std::printf(" %7d %12.1f %5.1f %10.1f %5.1f\n", x, pr, pr - x, pc, pc - x); } for (int x = -30; x <= 30; ++x) { // every millimetre for the statistics read((float)x, raw); int16_t scaled[5]; for (int i = 0; i < 5; ++i) scaled[i] = cal.scaled((uint8_t)i, raw[i]); float pr = 0, pc = 0; line_position<5>(raw, pos, pr); line_position<5>(scaled, pos, pc); double er = pr - x, ec = pc - x; if (std::fabs(er) > worst_raw) worst_raw = std::fabs(er); if (std::fabs(ec) > worst_cal) worst_cal = std::fabs(ec); sq_raw += er * er; sq_cal += ec * ec; ++n; } std::printf(" over every mm from -30 to +30: worst error uncalibrated %.1f mm, calibrated %.1f mm; rms %.2f vs %.2f mm\n", worst_raw, worst_cal, std::sqrt(sq_raw / n), std::sqrt(sq_cal / n)); return 0; }
IR sensor (assumed curve): distance error caused by +2 counts of ADC noise, formula inversion true mm counts distance for counts+2 error mm error % 100 451 99.4 -0.6 -0.6 200 297 197.4 -2.6 -1.3 400 198 393.3 -6.7 -1.7 800 142 772.5 -27.5 -3.4 (and the same sensor at 50 mm reads 226 counts: the SAME as it reads at about 316 mm) lookup table of N distances at evenly spaced counts (142..451), linear interpolation: worst error over every count in range entries N worst error mm at counts ints in table (bytes) 4 126.2 182 8 8 47.0 161 16 16 14.1 150 32 32 4.3 148 64 line array: position of a line from -30 to +30 mm, reading each sensor with 2 counts of noise; error = estimate - truth (mm) true mm uncalibrated error calibrated error -30 -21.4 8.6 -29.2 0.8 -25 -18.8 6.2 -26.2 -1.2 -20 -13.5 6.5 -19.5 0.5 -15 -7.0 8.0 -12.8 2.2 -10 -4.7 5.3 -9.7 0.3 -5 -2.3 2.7 -6.1 -1.1 0 1.0 1.0 0.1 0.1 5 4.9 -0.1 6.5 1.5 10 7.0 -3.0 9.6 -0.4 15 9.6 -5.4 13.2 -1.8 20 16.3 -3.7 19.8 -0.2 25 22.1 -2.9 26.1 1.1 30 25.2 -4.8 29.7 -0.3 over every mm from -30 to +30: worst error uncalibrated 8.7 mm, calibrated 2.2 mm; rms 4.91 vs 0.90 mm

Three things stand out. First, a fixed error in counts is not a fixed error in millimetres: two counts of ADC noise cost 0.6 mm at 100 mm but 27.5 mm (3.4 %) at 800 mm, because the curve is flat there; a sensor is accurate near and vague far. Second, the fold-back means a reading does not always identify a distance: at 50 mm the sensor reads 226 counts, the same as it reads at about 316 mm, so a robot that can get closer than 100 mm must not trust the sensor alone. Third, the table’s worst error shrinks as entries are added (126.2, 47.0, 14.1 and 4.3 mm for 4, 8, 16 and 32 entries), but at 16 entries it costs 32 bytes of RAM (section 10), and evenly spaced counts are not the best spacing for a curve this bent.

The line array shows what calibration is for. Without it the position estimate is off by up to 8.7 mm (rms 4.91 mm) over ±30 mm, purely because the sensors differ. With the minimum-and-maximum calibration the worst error is 2.2 mm (rms 0.90 mm), and what remains is mostly the noise. The calibration costs two numbers per sensor of RAM and a sweep before the run; a sensor that gets dirty or a floor that changes colour invalidates it, so the sweep belongs at the start of every run, not in the source code.

7. Quadrature encoders: three ways to count

A wheel encoder has two channels, A and B, that go high and low 90° apart. Moving forward, the pair of levels walks through the Gray sequence 00, 01, 11, 10, 00; moving backward it walks the other way. Each step is a tick, and the order tells the direction. The decoders below never read a pin: they are handed levels, so the same code runs on the PC and inside the interrupt.

// encoder.h -- decoding a quadrature encoder (channels A and B, 90 degrees apart). Plain C++11: the decoders never read a pin; they are handed the levels. // Forward motion walks the two-bit state AB through the Gray sequence 00 -> 01 -> 11 -> 10 -> 00; backward walks it the other way. #pragma once #include <stdint.h> // Full 4x decoding: every edge of A or B counts, so 4 counts per cycle. Needs an interrupt (or a fast poll) on BOTH channels. // A glitch that goes out and back (00 -> 01 -> 00 -> 01) counts +1 -1 +1 = +1: it cannot add error. A jump of TWO bits at once cannot be a real step: it is counted as an error. class Quad4x { public: Quad4x() : prev_(0), count_(0), errors_(0) {} void begin(uint8_t ab) { prev_ = ab & 3; } int8_t update(uint8_t ab) { // ab = (A << 1) | B; returns the step: -1, 0 or +1 ab &= 3; static const int8_t STEP[16] = { 0, +1, -1, 2, // from 00 -1, 0, 2, +1, // from 01 +1, 2, 0, -1, // from 10 2, -1, +1, 0 }; // from 11 (2 marks an impossible two-bit jump) int8_t s = STEP[(prev_ << 2) | ab]; prev_ = ab; if (s == 2) { ++errors_; return 0; } count_ += s; return s; } int32_t count() const { return count_; } uint32_t errors() const { return errors_; } private: uint8_t prev_; int32_t count_; uint32_t errors_; }; // 2x decoding: an interrupt on the change of A ONLY; B is just read at that moment. After an A edge, A == B means forward and A != B means backward. // Half the resolution of 4x, but it needs one interrupt pin per wheel, which is what the Uno has (pins 2 and 3). inline int8_t quad2x_step(bool a, bool b) { return (a == b) ? +1 : -1; } // The simplest decoder, and the one most often written first: on a RISING edge of A, look at B. One count per cycle (1x), and chatter on A can add counts. class QuadNaive { public: QuadNaive() : prev_a_(false), count_(0) {} void update(bool a, bool b) { if (a && !prev_a_) count_ += b ? +1 : -1; // forward: B is already high when A rises (01 -> 11) prev_a_ = a; } int32_t count() const { return count_; } private: bool prev_a_; int32_t count_; };

Quad4x counts every edge of both channels (4 counts per cycle) and flags an impossible two-bit jump as an error. quad2x_step reacts only to a change of A and reads B at that moment (2 counts per cycle, and half the interrupts). QuadNaive counts the rising edges of A only (1 per cycle), the decoder most people write first. The test turns a simulated wheel forward at 0.5 m/s for 2 s and backward at 0.25 m/s for 1 s (1302 true ticks net), produces the A and B levels from the tick count, and corrupts them in two ways: chatter (an edge that goes out and back before settling) and skipped states (a state the sampler never saw, which is what happens when an interrupt is late):

// e_quad.cpp -- three quadrature decoders fed the A/B signals of a simulated wheel, with chatter on the edges and with missed samples (host build, seeded) // The wheel is the simulator's: 2 s forward at 0.5 m/s then 1 s backward at 0.25 m/s, 360 ticks per turn. A and B are made from the tick count (Gray code). #include <cstdio> #include <cmath> #include <vector> #include <initializer_list> #include "sim.h" #include "encoder.h" static void ab_of(int32_t tick, bool& a, bool& b) { int idx = (int)(((tick % 4) + 4) % 4); // 0:00 1:01 2:11 3:10 a = (idx == 2 || idx == 3); b = (idx == 1 || idx == 2); } struct Out { int32_t ticks, c4, c2, cn; uint32_t err4; int skipped, changes; }; static Out run(double chatter, double miss, uint32_t seed) { RobotParams rp; rp.tau = 0.0; rp.pwm_quantise = false; SensorParams sp; Arena arena; SimHW w(rp, sp, arena, seed); Rng rng(seed + 100); Quad4x q4; QuadNaive qn; int32_t c2 = 0; bool pa = false, pb = false; // the previous sample of A and B q4.begin(0); int32_t last = 0; int skipped = 0, changes = 0; for (int ms = 0; ms < 3000; ++ms) { w.drive(ms < 2000 ? 0.5f : -0.25f, ms < 2000 ? 0.5f : -0.25f); w.step(0.001); int32_t l, r; w.read_ticks(l, r); while (last != l) { // each tick of the wheel changes the state by one step int32_t prev_tick = last; last += (l > last) ? 1 : -1; bool skip = rng.uniform() < miss; ++changes; if (skip) ++skipped; bool na, nb, oa, ob; ab_of(last, na, nb); ab_of(prev_tick, oa, ob); std::vector<std::pair<bool, bool> > samples; if (!skip) { if (rng.uniform() < chatter) { samples.push_back(std::make_pair(na, nb)); samples.push_back(std::make_pair(oa, ob)); } samples.push_back(std::make_pair(na, nb)); } for (size_t k = 0; k < samples.size(); ++k) { bool a = samples[k].first, b = samples[k].second; q4.update((uint8_t)((a << 1) | b)); if (a != pa) c2 += quad2x_step(a, b); // the 2x decoder runs only when A changes qn.update(a, b); pa = a; pb = b; } } } (void)pb; int32_t l, r; w.read_ticks(l, r); Out o; o.ticks = l; o.c4 = q4.count(); o.c2 = c2; o.cn = qn.count(); o.err4 = q4.errors(); o.skipped = skipped; o.changes = changes; return o; } int main() { std::printf("a wheel turned forward 2 s then backward 1 s; true tick count and what each decoder counted (expected 4x = ticks, 2x = ticks/2, naive 1x = ticks/4):\n"); std::printf(" chatter on an edge states skipped (of changes) true ticks 4x count 2x count naive count 4x error flags\n"); for (double ch : {0.0, 0.02, 0.10, 0.30}) { Out o = run(ch, 0.0, 1); std::printf(" %17.0f %% %6d of %-5d%3s %10d %8d %8d %11d %14u\n", ch * 100, o.skipped, o.changes, "", (int)o.ticks, (int)o.c4, (int)o.c2, (int)o.cn, (unsigned)o.err4); } for (double miss : {0.001, 0.01, 0.05}) { Out o = run(0.0, miss, 1); std::printf(" %17.0f %% %6d of %-5d%3s %10d %8d %8d %11d %14u\n", 0.0, o.skipped, o.changes, "", (int)o.ticks, (int)o.c4, (int)o.c2, (int)o.cn, (unsigned)o.err4); } return 0; }
a wheel turned forward 2 s then backward 1 s; true tick count and what each decoder counted (expected 4x = ticks, 2x = ticks/2, naive 1x = ticks/4): chatter on an edge states skipped (of changes) true ticks 4x count 2x count naive count 4x error flags 0 % 0 of 2170 1302 1302 651 325 0 2 % 0 of 2170 1302 1302 651 323 0 10 % 0 of 2170 1302 1302 651 323 0 30 % 0 of 2170 1302 1302 651 333 0 0 % 4 of 2170 1302 1298 649 323 4 0 % 18 of 2170 1302 1270 641 317 18 0 % 105 of 2170 1302 1160 583 301 97

Chatter is harmless to the 4x and 2x decoders (1302 and 651 in every row) because a glitch that goes out and back counts +1 −1 +1, which is +1. The naive decoder is not so lucky: it should count 325.5 and counts 325, 323, 323 and 333, because every extra rising edge of A is another count.

Missing states is the harder case. Missing 4 of 2170 states cost the 4x decoder 4 counts and raised 4 error flags; the 2x decoder, which cannot see errors at all, was off by 2; and the naive one by about 2. I first expected two lost counts per skipped state, since a skipped state is a jump of two steps, which the 4x decoder flags and counts as zero. That is right, but the deficit is not 2 per skip, because a skipped state going backward adds 2 instead of subtracting them. With a throw-away variant of the program that also counted the direction of each skip (it printed 3 of the 4, 17 of 18 and 88 of 105 skips as forward), the deficits of 4, 32 and 142 are exactly 2 × (forward skips − backward skips): 2 × (3 − 1), 2 × (17 − 1) and 2 × (88 − 17). The error flags are fewer than the skips at 5 % (97 against 105), because two skipped states in a row are a jump of three steps, which looks like a legal step in the other direction:

#include <cstdio> #include "encoder.h" static void ab_of(int t, bool& a, bool& b) { int i = ((t % 4) + 4) % 4; a = (i == 2 || i == 3); b = (i == 1 || i == 2); } int main() { // forward 0..20 skipping tick 5, and tick 12 Quad4x q; q.begin(0); int skipped[] = {5, 12}; for (int t = 1; t <= 20; ++t) { bool sk = false; for (int s : skipped) if (s == t) sk = true; if (sk) continue; bool a, b; ab_of(t, a, b); q.update((uint8_t)((a << 1) | b)); } std::printf("forward 20 ticks, 2 isolated states never seen: count %d (expected 20), errors %u\n", (int)q.count(), (unsigned)q.errors()); // skipping two consecutive states Quad4x p; p.begin(0); for (int t = 1; t <= 20; ++t) { if (t == 5 || t == 6) continue; bool a, b; ab_of(t, a, b); p.update((uint8_t)((a << 1) | b)); } std::printf("two CONSECUTIVE states never seen: count %d, errors %u\n", (int)p.count(), (unsigned)p.errors()); return 0; }
forward 20 ticks, 2 isolated states never seen: count 16 (expected 20), errors 2 two CONSECUTIVE states never seen: count 16, errors 0

Twenty forward ticks with two isolated skips counted 16 with 2 error flags, and with two consecutive skips counted 16 with 0 flags. So an error flag is evidence of a lost state, and its absence is not evidence that none was lost. What you can do about it is make skips rare (a fast interrupt) and compare the encoder count with something else, as chapter 5 does with odometry.

8. Interrupts on the Uno

The Uno can interrupt on exactly two pins, 2 and 3 (INT0 and INT1). Two wheels with 4x decoding would need four interrupt sources; with 2x decoding, channel A of each wheel goes on an interrupt pin and channel B on any ordinary pin read inside the routine. pins.h now has PIN_ENC_L_B = 15 and PIN_ENC_R_B = 16 (analog pins A1 and A2 used as digital inputs) and PIN_IR = 17 (A3), each checked by a static_assert. (Full 4x decoding of two wheels would need pin-change interrupts, which share one vector between several pins; it is not built here.)

The sketch below writes the interrupt registers directly instead of calling attachInterrupt, so the routine stays short. It also has two reading functions, deliberately noinline, so that the compiler gives each its own code that can be read in the disassembly: one reads a 32-bit counter plainly, the other inside an atomic block (section 9).

// s_isr.ino -- two wheel encoders on the Uno's two interrupt pins, 2x decoding, and two ways to read the 32-bit counters. // Channel A of each wheel is on an interrupt pin (INT0 = pin 2, INT1 = pin 3); channel B is read inside the interrupt (A1 = PC1, A2 = PC2). // Compiled for the Uno with arduino-cli; NOT run on a board (none attached). The instruction counts come from disassembling the compiled code. #include <avr/io.h> #include <avr/interrupt.h> #include <util/atomic.h> #include "pins.h" volatile int32_t g_ticks_l = 0, g_ticks_r = 0; // After an edge of A: A == B means forward, A != B means backward (the 2x rule from encoder.h). ISR(INT0_vect) { bool a = (PIND & _BV(PD2)) != 0; bool b = (PINC & _BV(PC1)) != 0; g_ticks_l += (a == b) ? 1 : -1; } ISR(INT1_vect) { bool a = (PIND & _BV(PD3)) != 0; bool b = (PINC & _BV(PC2)) != 0; g_ticks_r += (a == b) ? 1 : -1; } // UNSAFE: four separate byte loads. An interrupt between two of them gives a torn value. __attribute__((noinline)) int32_t read_left_unsafe() { return g_ticks_l; } // SAFE: interrupts are off while the four bytes are copied, and put back as they were found. __attribute__((noinline)) int32_t read_left_atomic() { int32_t v; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { v = g_ticks_l; } return v; } void setup() { 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); // INT0 and INT1: an interrupt on ANY change of the pin EIFR = _BV(INTF0) | _BV(INTF1); // clear anything pending EIMSK = _BV(INT0) | _BV(INT1); // switch both on Serial.begin(115200); } void loop() { Serial.println(read_left_unsafe()); Serial.println(read_left_atomic()); Serial.println((long)g_ticks_r); delay(500); }
arduino-cli compile --fqbn arduino:avr:uno --warnings all s_isr Sketch uses 2418 bytes (7%) of program storage space. Maximum is 32256 bytes. Global variables use 196 bytes (9%) of dynamic memory, leaving 1852 bytes for local variables. Maximum is 2048 bytes. avr-objdump -d, _Z16read_left_unsafev: 3c6 lds r22, 0x0116 ; 0x800116 <__data_end> 3ca lds r23, 0x0117 ; 0x800117 <__data_end+0x1> 3ce lds r24, 0x0118 ; 0x800118 <__data_end+0x2> 3d2 lds r25, 0x0119 ; 0x800119 <__data_end+0x3> 3d6 ret avr-objdump -d, _Z16read_left_atomicv: 3ae in r18, 0x3f ; 63 3b0 cli 3b2 lds r22, 0x0116 ; 0x800116 <__data_end> 3b6 lds r23, 0x0117 ; 0x800117 <__data_end+0x1> 3ba lds r24, 0x0118 ; 0x800118 <__data_end+0x2> 3be lds r25, 0x0119 ; 0x800119 <__data_end+0x3> 3c2 out 0x3f, r18 ; 63 3c4 ret ISR for INT0 (__vector_1), counted from the listing: 54 instructions, 87 cycles on the forward path, 84 on the backward path plus about 7 cycles before its first instruction (4 for the interrupt, 3 for the jmp in the vector table; data-sheet figures, not measured) = about 94 cycles = 5.9 us at 16 MHz 11 x push 11 x pop 6 x ldi 4 x sts 4 x lds 3 x in 3 x adc 2 x eor 1 x rjmp 1 x reti 1 x out 1 x movw 1 x lsr 1 x cpse 1 x bst 1 x bld 1 x andi 1 x add

The routine for INT0 compiles to 54 instructions. Adding the cycles of each (data-sheet figures: push, pop, lds and sts are two cycles, reti four) gives 87 cycles on the forward path and 84 on the backward path, and with about 7 cycles of interrupt entry, roughly 94 cycles, 5.9 µs at 16 MHz. Half of that is overhead: 11 pushes and 11 pops save and restore registers the routine uses to do a four-byte add, 44 cycles, before and after a two-line routine. That is the price of a 32-bit counter on an 8-bit chip; a 16-bit counter would need only half the loads and stores. One wheel at the simulator’s forward speed makes 868 ticks per second, so this 2x routine runs 434 times a second (868 would be 4x), a processor load of 434 × 94 / 16,000,000 = 0.25 % per wheel. These are cycle counts from a listing, not measurements of the chip: the cost of the interrupt entry is the data sheet’s, and nothing was timed on a board.

9. The torn read

The Uno’s processor is 8-bit. Reading a 32-bit volatile counter takes four separate lds instructions, as the listing above shows for read_left_unsafe, and an interrupt can arrive between any two of them. If the interrupt adds 1 to the counter in that gap, the program has the low byte from before and the upper bytes from after. Most of the time that does not matter: the bytes agree. It matters when the add carries out of the bytes already read, as in 0x000000FF becoming 0x00000100. The byte-load model enumerates the cases and then repeats 20 million random reads:

// e_torn.cpp -- a torn read: an 8-bit processor reads a 32-bit counter one byte at a time, and an interrupt adds 1 between two of the byte loads. // This is a MODEL of the byte loads (lowest byte first, as avr-gcc loads them); it is not run on a board. Host build. #include <cstdio> #include <cstdint> #include <initializer_list> #include "sim.h" // Read the counter as four byte loads, with `isr_after` loads done when the interrupt (counter += 1) happens (0..3), or never if isr_after is 4 (after the last load). static uint32_t torn_read(uint32_t counter, int isr_after) { uint32_t out = 0; for (int b = 0; b < 4; ++b) { if (b == isr_after) counter += 1; // the interrupt runs between byte loads out |= ((counter >> (8 * b)) & 0xFFu) << (8 * b); } return out; } int main() { std::printf("a 32-bit counter read as four byte loads; an interrupt adds 1 after the first, second or third load:\n"); std::printf(" counter before interrupt after load value read true values (before/after) error vs nearest\n"); for (uint32_t v : {0x00000010u, 0x000000FFu, 0x0000FFFFu, 0x00FFFFFFu}) { for (int g = 1; g <= 3; ++g) { uint32_t r = torn_read(v, g); long e1 = (long)r - (long)v, e2 = (long)r - (long)(v + 1); long err = (e1 < 0 ? -e1 : e1) < (e2 < 0 ? -e2 : e2) ? e1 : e2; std::printf(" 0x%08X %17d 0x%08X %10u / %-10u %16ld\n", (unsigned)v, g, (unsigned)r, (unsigned)v, (unsigned)(v + 1), err); } } // How often? An interrupt that lands during one of the four load instructions takes effect after that instruction, so over a read it falls in // gap 1, 2, 3 or after the last load with equal chance (the model: 4 loads of 2 cycles each, the edge arrives at a random cycle). // Count over 20 million random (counter value, edge position) pairs how many reads are torn (differ from both true values). Rng rng(11); const long TRIALS = 20000000L; long torn = 0, hit = 0; for (long i = 0; i < TRIALS; ++i) { uint32_t v = rng.next(); // all 32 bits (uniform() has only 24, which would leave the low byte always 0) int g = (int)(rng.uniform() * 4.0) + 1; // 1,2,3: the interrupt lands in a gap; 4 means after the last load if (g < 4) ++hit; uint32_t r = torn_read(v, g); if (r != v && r != v + 1) ++torn; } std::printf("\n%ld random reads with an interrupt inside the read: %ld landed between loads, %ld of them torn (%.4f %% of the reads, %.3f %% of the in-gap cases; 1/256 is %.3f %%)\n", TRIALS, hit, torn, 100.0 * torn / TRIALS, 100.0 * torn / hit, 100.0 / 256); // Arithmetic estimate for the encoder: a read takes about 4 x 2 = 8 cycles at 16 MHz (0.5 us). double edges_per_s = 434.0; // ISR calls per second for one wheel at 2x (the sketch decodes channel A edges only): half of the 868 ticks per second the sim wheel makes double read_s = 8.0 / 16e6; double p_hit = edges_per_s * read_s; // chance an edge falls inside one read (< 1) std::printf("arithmetic: one read lasts %.2f us; at %.0f ISR calls/s the chance an interrupt falls inside a given read is %.2e;\n", read_s * 1e6, edges_per_s, p_hit); std::printf(" the simulated rate above says about %.2e of such reads are torn, so a torn read per %.1f million reads\n", (double)torn / (double)hit * 0.75, 1.0 / (p_hit * (double)torn / (double)hit * 0.75) / 1e6); std::printf(" at 50 reads per second that is one torn read every %.1f hours of driving (the worst case, a wrapping byte, is not rare enough to ignore)\n", 1.0 / (p_hit * (double)torn / (double)hit * 0.75) / 50.0 / 3600.0); return 0; }
a 32-bit counter read as four byte loads; an interrupt adds 1 after the first, second or third load: counter before interrupt after load value read true values (before/after) error vs nearest 0x00000010 1 0x00000010 16 / 17 0 0x00000010 2 0x00000010 16 / 17 0 0x00000010 3 0x00000010 16 / 17 0 0x000000FF 1 0x000001FF 255 / 256 255 0x000000FF 2 0x000000FF 255 / 256 0 0x000000FF 3 0x000000FF 255 / 256 0 0x0000FFFF 1 0x000100FF 65535 / 65536 255 0x0000FFFF 2 0x0001FFFF 65535 / 65536 65535 0x0000FFFF 3 0x0000FFFF 65535 / 65536 0 0x00FFFFFF 1 0x010000FF 16777215 / 16777216 255 0x00FFFFFF 2 0x0100FFFF 16777215 / 16777216 65535 0x00FFFFFF 3 0x01FFFFFF 16777215 / 16777216 16777215 20000000 random reads with an interrupt inside the read: 14999877 landed between loads, 19315 of them torn (0.0966 % of the reads, 0.129 % of the in-gap cases; 1/256 is 0.391 %) arithmetic: one read lasts 0.50 us; at 434 ISR calls/s the chance an interrupt falls inside a given read is 2.17e-04; the simulated rate above says about 9.66e-04 of such reads are torn, so a torn read per 4.8 million reads at 50 reads per second that is one torn read every 26.5 hours of driving (the worst case, a wrapping byte, is not rare enough to ignore)

The enumeration shows the wrong values: the counter 255 (0x000000FF) read as 511 when the interrupt lands after the first byte; 65535 (0x0000FFFF) read as 131071 (0x0001FFFF) when it lands after the second byte; and the worst case, 0x00FFFFFF read as 0x01FFFFFF, 16,777,215 too high. The random run found 19,315 torn reads in 20 million (0.097 %), close to the 1/1024 expected from an interrupt landing in the first gap one time in four and a low byte of 0xFF one time in 256. The arithmetic at the end is a model, not a measurement: with 434 interrupts per second (one wheel at 2x) and a read lasting about 8 cycles (0.5 µs), an interrupt lands inside a given read with chance 2.2 × 10-4, so a torn read of this one counter happens about once per 4.8 million reads, one in 26 hours at 50 reads per second. That is rare enough to pass every test on a bench and wrong often enough to wreck a run of a robot that drives for hours; the wheel is then “somewhere else” for one control cycle, and the odometry carries the error forever.

The fix is to turn interrupts off while the four bytes are copied and put the interrupt flag back as it was found (ATOMIC_BLOCK(ATOMIC_RESTORESTATE)). The disassembly above shows what it costs: the atomic read is 8 instructions and 15 cycles against 5 and 12, and interrupts are off for about 10 of them (0.6 µs), a tenth of one interrupt routine, so a pending edge is delayed by far less than the routine takes. robot_ch4.ino copies both counters inside one atomic block, so the left and right values are from the same moment.

10. What it costs, and the sketch

Each filter was compiled alone into a sketch that reads A3 and prints the result (cast to long, so that printing a float does not add its own code to the filter’s bill). The first row is the sketch without a filter; the last two columns are what each filter adds:

arduino-cli compile --fqbn arduino:avr:uno --warnings all -DVARIANT_x s_filters (flash and RAM of the whole sketch; "base" only reads A3 and prints it, so the last two columns are what each filter adds) variant flash bytes RAM bytes adds flash adds RAM base (no filter) 1890 188 0 0 debounce, 5 samples 1970 191 80 3 median of 3 2180 196 290 8 median of 5 2180 200 290 12 moving average of 8, integers 2142 210 252 22 moving average of 8, float 3000 222 1110 34 exponential, integers, K = 2 2122 193 232 5 exponential, float, a = 1/4 2876 197 986 9 IR distance, formula (float) 2790 188 900 0 IR distance, 16-entry table 2368 226 478 38

Floating point is the expensive habit: the float moving average adds 1110 bytes of flash and 34 of RAM against 252 and 22 for the integer one, because the Uno has no floating-point hardware and every float operation calls a library routine; an exponential filter in floats costs 986 bytes, in integers 232. For the IR sensor the 16-entry table (478 bytes of flash) is cheaper in flash than the formula (900) but costs 38 bytes of RAM, 32 of them the table itself: on the Uno, a const array without PROGMEM is copied into RAM at start-up. A PROGMEM table would give the RAM back; it was not tried here. The median of 3 and of 5 compile to the same size here, and differ only in the 4 bytes of buffer.

Finally robot_ch4.ino is chapter 3’s robot with the stubbed encoders replaced by the interrupt routines and the atomic read, and a Median<int16_t, 5> between the ultrasonic sensor and the controller. The filter sits in set_range, the seam, so drive.h does not change (still byte-identical to the simulator’s). A no-echo reading is passed on as a no-echo: it is a fault signal, not a distance to average.

// robot_ch4.ino -- Programming for Robotics with Arduino C++, chapter 4: chapter 3's robot with real encoders (interrupts, 2x decoding, atomic reads) // and a median filter between the ultrasonic sensor and the controller. Compile-checked for the Uno (arduino:avr:uno). NOT run on a board. #include <avr/io.h> #include <avr/interrupt.h> #include <util/atomic.h> #include "scheduler.h" #include "conv.h" #include "echo.h" #include "pins.h" #include "filters.h" #include "drive.h" const float V_MAX_MPS = 0.5f; // wheel speed at a duty of 255: an assumption, as in chapter 2 // ---- encoders: an interrupt on every change of channel A, channel B read inside it (2x decoding) ---- volatile int32_t g_ticks_l = 0, g_ticks_r = 0; ISR(INT0_vect) { bool a = (PIND & _BV(PD2)) != 0, b = (PINC & _BV(PC1)) != 0; g_ticks_l += (a == b) ? 1 : -1; } ISR(INT1_vect) { bool a = (PIND & _BV(PD3)) != 0, b = (PINC & _BV(PC2)) != 0; g_ticks_r += (a == b) ? 1 : -1; } static void encoders_begin() { 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); // any change on INT0 and on INT1 EIFR = _BV(INTF0) | _BV(INTF1); EIMSK = _BV(INT0) | _BV(INT1); } class PinHW { // the four functions drive.h needs, on real pins public: PinHW() : range_m_(-1.0f) {} float range_m() { return range_m_; } // negative until the first echo, and after a timeout void set_range(float m) { // the filter sits HERE, at the seam: the controller never sees a raw reading if (m < 0.0f) { range_m_ = m; return; } // a dropout is passed on as a dropout, not averaged in int16_t mm = (int16_t)(m * 1000.0f + 0.5f); range_m_ = (float)median_.update(mm) * 0.001f; } void read_ticks(int32_t& l, int32_t& r) { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { l = g_ticks_l; r = g_ticks_r; } // both counters copied with interrupts off } bool bumped() { return digitalRead(PIN_BUMP) == LOW; } 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(vl >= 0.0f ? vl : -vl, V_MAX_MPS)); analogWrite(PIN_MR_PWM, speed_to_pwm(vr >= 0.0f ? vr : -vr, V_MAX_MPS)); } private: float range_m_; Median<int16_t, 5> median_; }; static PinHW hw; static DriveConfig make_config() { DriveConfig c; c.stop_m = 0.25f; c.k_range = 1.5f; c.vmax = V_MAX_MPS; c.k_heading = 2.0f; c.wheel_r = 0.033f; c.track = 0.15f; c.ticks_per_rev = 360; c.max_dropouts = 5; // 360 COUNTS per turn: a 180-slot disc at 2x return c; } static DriveRobot<PinHW> robot(hw, make_config()); static Echo echo; static Scheduler<5> sch; static bool trig_level = false; static void echo_start_task(void*, uint32_t) { echo.start(); } static void report_task(void*, uint32_t now) { int32_t l, r; hw.read_ticks(l, r); Serial.print(now); Serial.print(F(" ms range ")); Serial.print(robot.range(), 3); Serial.print(F(" m ticks ")); Serial.print(l); Serial.print(' '); Serial.print(r); Serial.print(F(" fault ")); Serial.println((int)robot.fault()); } 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_TRIG, OUTPUT); pinMode(PIN_ECHO, INPUT); pinMode(PIN_BUMP, INPUT_PULLUP); encoders_begin(); sch.add(DriveRobot<PinHW>::sense_task, &robot, 20); sch.add(DriveRobot<PinHW>::think_task, &robot, 20); sch.add(DriveRobot<PinHW>::act_task, &robot, 20); sch.add(echo_start_task, 0, 60); sch.add(report_task, 0, 500); } void loop() { bool before = trig_level; Echo::Status st = echo.update(micros(), digitalRead(PIN_ECHO), trig_level); if (trig_level != before) digitalWrite(PIN_TRIG, trig_level); if (st == Echo::READY) hw.set_range(echo_us_to_m(echo.width_us())); else if (st == Echo::TIMEOUT) hw.set_range(-1.0f); sch.run(millis()); }

It compiles for the Uno, with no warnings under --warnings all, to 8626 bytes of flash (26 %) and 433 bytes of RAM (21 %), against 7726 and 413 for chapter 3’s sketch: 900 bytes more flash and 20 bytes more RAM, of which 12 are the median’s buffer and 8 the two counters. It was not run. In particular the ticks_per_rev = 360 assumes a 180-slot disc at 2x decoding, and the right wheel, which turns the opposite way on a real robot, would need its sign flipped: a wiring and configuration question for the chapter that drives with these counts.

11. What the numbers can and cannot be trusted for

What they show. The shapes: a median rejects spikes while an average smears them; delay grows with the window; a plain integer exponential filter stalls by 2K − 1; a float running sum drifts with value size and run length; 4x and 2x decoders ignore chatter and the naive one does not; a 32-bit read on an 8-bit chip can tear, and an atomic read prevents it, at a measured cost in instructions. The instruction, flash and RAM counts come from the real compiler for the real chip.

What they do not show. Every noise level, spike rate, chatter length and curve here is an assumption, and a real sensor will have different ones, often with an error that is not random (a surface that absorbs sound, a switch that wears). The cycle counts are from the data sheet and a listing, not a logic analyser; the torn-read rate depends on how often the program really reads the counter, which was a guess of 50 Hz. And the decoders were tested on a perfect simulated wheel: real encoders add uneven slots and electrical noise that no experiment here has. Before a robot relies on any of this, put a scope or a logic analyser on the pins and read the tick counter against turns counted by hand.

Challenge 1: How big a median?
A median fails when more than half of its window is wrong. Sweep the share of wrong echoes (0, 3, 10, 20, 30 and 40 %) against windows of 3, 5, 9 and 15, on the falling-range signal of section 3 (100 seeds per cell), and print the rms and worst error. Next to it print the binomial chance that more than half of a window is wrong, and say what window you would choose for 3 % and for 20 % wrong echoes, and why the cleanest signal prefers the smallest window.
View solution
Challenge 2: How many guard bits?
Generalise the integer exponential filter so that the shift K and the number of guard bits G are separate (EmaG<K, G>). For K = 3 and K = 5 try several values of G and print where each ends after a step 0 → 1000, 0 → 37, 0 → 5 and 1000 → 0, and the rms difference from the float filter on a noisy ramp. Find the smallest G that removes the stall in both directions, and explain the result in terms of (2K − 1) / 2G.
View solution
Challenge 3: Which values tear?
Enumerate every value of a 2-byte and a 3-byte counter, with an interrupt adding 1 after each possible byte load, and count the torn reads exactly. Compare the counts with 1/256gap, report the worst error, and use the disassembly of the unsafe and atomic reads to say how many instructions and cycles the fix costs and for how long interrupts are off.
View solution

Quick reference

  • Ring buffer. Ring<T, N>: N values plus 2 bytes; no heap, no lists; the size is a template parameter.
  • Debounce. 50 presses with 0–8 ms of chatter: 129 events raw, 52 at 3 samples in a row, 50 at 5 (delay 7.0 ms). A 4 ms tap: 12 of 50 seen at 5, none at 10. The window is a low-pass filter for real presses too.
  • Median or average. rms 271.5 mm unfiltered, 126.4 averaging 5, 12.4 median of 5; worst 2155 mm for median 5, 48 for median 9. A window of N lags (N − 1)/2 readings; 460 ms for an exponential a = 1/8. A median fails when over half the window is wrong (challenge 1).
  • Float running sum. Error after 10 million samples: 0.10 (input 1000), 53.7 (1e5), 3199.6 (1e6); recomputing the window stays within 0.09; an int32_t sum is exact.
  • Integer exponential filter. Plain shift K=3 stops 7 short (993), never leaves 0 for a step to 5; guard bits fix it (1000, 37, 5), falling ends at 1; G = K + 1 clears both directions for K = 3 and 5 (challenge 2).
  • Calibration. Two counts of noise cost 0.6 mm at 100 mm and 27.5 mm at 800 mm (assumed curve); a reading folds back below 100 mm (50 mm reads like about 316 mm). A 16-entry table: worst error 14.1 mm. Line array: worst 8.7 mm uncalibrated, 2.2 mm calibrated.
  • Decoders. 4x = 1302, 2x = 651, naive = 325 on 1302 true ticks; chatter harmless to 4x/2x. Skipped states: deficit = 2 × (forward − backward skips); two consecutive skips raise no flag.
  • Interrupt. INT0 routine: 54 instructions, about 94 cycles (5.9 µs) from a listing, 11 push and 11 pop of them; 0.25 % load per wheel at 434 calls/s.
  • Torn read. A 32-bit read is 4 loads (5 instructions, 12 cycles); atomic: 8 instructions, 15 cycles, interrupts off for about 10. 19,315 of 20 million modelled reads torn (0.097 %); exhaustive 2-byte counter: 256 of 65,536 (1/256).
  • Budget. robot_ch4.ino: 8626 bytes flash (26 %), 433 bytes RAM (21 %). Integer filters add 80–290 bytes of flash; floats 986–1110; a 16-entry table costs 32 bytes of RAM unless it is PROGMEM.
  • Not run: anything on a board; every noise, spike and chatter figure and the IR curve are assumptions.

Next: Programming for Robotics with Arduino C++ 5, Driving: Motors and Odometry

Programming for Robotics with Arduino C++ 5 (planned; not yet written) turns the counters of this chapter into motion: motor driver code with ramping and limits, encoder counts converted to wheel speed, the odometry pose update, and straight and turn-by-angle moves, with the cost of float that this chapter measured and the encoder counts that its interrupt now supplies.