Programming for Robotics with Arduino C++ 1 ended with a robot that drove toward a wall in a simulated world: SimHW had two functions, range_m() and drive(speed), and everything else in the program was written against them. This chapter writes the real PinHW that replaces it. That means turning a speed into a PWM duty, a pulse width into a distance, and a stream of bytes from an I2C chip into numbers with units, and doing it on a board where a careless call can cost half the loop time.
The chapter is about the seams: the place where physical quantities become C++ values and back. Each seam is kept in a header of plain C++ with no Arduino calls, so that a PC can test it. Each is then connected to the real pins in one small sketch.
What was run, and what was not
Run on a PC (g++ 16.2, C++11, -Wall -Wextra -pedantic, no warnings): every block below that has an output under it. These use a fake clock, a fake ultrasonic sensor and a fake MPU-6050 written by me from the register map, so they show that my code does what the documents say, not what a real sensor does. Noise levels are assumptions and are labelled. Compiled for the Uno, not run (arduino-cli 1.6.0, core arduino:avr 1.8.8): robot_ch2.ino and the small sketches whose sizes are compared. Flash and RAM figures, and the disassembly shown in section 1, are the real compiler's. I also read the installed Arduino core source to confirm the timer, serial-buffer and baud-rate facts quoted. No board, motor, sensor or IMU was attached. No pin was driven, no PWM frequency measured with an oscilloscope, no sensor read. Facts about the chips (register addresses, scale factors, the 0x68 identity) come from my knowledge of the datasheets and should be checked against the datasheet of the part you buy.
1. A pin is three register bits
Every digital pin of the Uno belongs to a port (B, C or D), and each port has three 8-bit registers: DDRx (direction: 1 = output), PORTx (the output value, or the pull-up for an input) and PINx (the input value, read-only). Pin 13 is bit 5 of port B. pinMode(13, OUTPUT) sets bit 5 of DDRB; digitalWrite(13, HIGH) sets bit 5 of PORTB. That is all a digital output is.
The Arduino functions take a pin number and look the port and bit up in tables while the program runs, and they switch off any PWM on the pin and protect the write from interrupts. That is convenient and has a price. Two sketches that toggle pin 13 forever, one with digitalWrite and one with the port register directly, were compiled for the Uno:
// toggles pin 13 (PB5) by writing the port register directly
void setup() { DDRB |= _BV(PB5); }
void loop() { PORTB |= _BV(PB5); PORTB &= ~_BV(PB5); }
Sketch
Flash
RAM
empty setup() and loop()
444 bytes
9 bytes
toggle with digitalWrite
734 bytes (+290)
9 bytes
toggle with PORTB
450 bytes (+6)
9 bytes
The disassembly of the port version's loop, from the compiler's own output (avr-objdump -d), is two instructions and the loop jump: sbi sets one bit of a register, cbi clears one, and the instruction set manual gives each as 2 clock cycles. The specialised copy of digitalWrite the compiler made for the other sketch is 144 bytes, 66 instructions, and begins like this:
The three lpm instructions read the pin's port, bit and timer from tables in flash; further down it saves the status register and disables interrupts (cli) while it writes. This chapter does not time the two on a board, so no speed ratio is claimed: the evidence is size and the visible instructions. The honest rule is the same as in Programming for Robotics with Arduino C++ 1: use digitalWrite by default, because it is clear and safe, and go to the register only where the instruction count has been shown to matter (a step pulse at tens of kilohertz, say). The register form is unsafe in one way digitalWrite is not: it knows nothing about PWM, so writing a bit that a timer is driving leaves the timer in control.
2. A pin table the compiler checks
Not every pin can do every job: only six can do PWM, only two can interrupt, pins 0 and 1 are the USB serial link, and A4 and A5 are the I2C bus. A wiring mistake of this kind compiles perfectly and fails on the bench. Writing the capabilities as a constexpr table lets the compiler check the plan:
// pins.h -- what each Uno R3 pin can do, and the build robot's pin plan, checked by the compiler. Plain C++11: a constexpr table, no Arduino calls.
#pragma once
#include <stdint.h>
enum Cap : uint8_t { CAP_DIGITAL = 1, CAP_PWM = 2, CAP_ADC = 4, CAP_INT = 8, CAP_I2C = 16, CAP_SPI = 32, CAP_UART = 64 };
enum Role : uint8_t { R_DIGITAL, R_PWM, R_ADC, R_INTERRUPT };
// Pin numbers as the Arduino core uses them: 0..13 digital, 14..19 = A0..A5.
const uint8_t PIN_COUNT = 20;
constexpr uint8_t PIN_CAPS[PIN_COUNT] = {
CAP_DIGITAL | CAP_UART, // 0 RX (USB serial)
CAP_DIGITAL | CAP_UART, // 1 TX (USB serial)
CAP_DIGITAL | CAP_INT, // 2 INT0
CAP_DIGITAL | CAP_PWM | CAP_INT, // 3 INT1, Timer2 B
CAP_DIGITAL, // 4
CAP_DIGITAL | CAP_PWM, // 5 Timer0 B
CAP_DIGITAL | CAP_PWM, // 6 Timer0 A
CAP_DIGITAL, // 7
CAP_DIGITAL, // 8
CAP_DIGITAL | CAP_PWM, // 9 Timer1 A
CAP_DIGITAL | CAP_PWM | CAP_SPI, // 10 Timer1 B, SS
CAP_DIGITAL | CAP_PWM | CAP_SPI, // 11 Timer2 A, MOSI
CAP_DIGITAL | CAP_SPI, // 12 MISO
CAP_DIGITAL | CAP_SPI, // 13 SCK, and the on-board LED
CAP_DIGITAL | CAP_ADC, // 14 A0
CAP_DIGITAL | CAP_ADC, // 15 A1
CAP_DIGITAL | CAP_ADC, // 16 A2
CAP_DIGITAL | CAP_ADC, // 17 A3
CAP_DIGITAL | CAP_ADC | CAP_I2C, // 18 A4, SDA
CAP_DIGITAL | CAP_ADC | CAP_I2C, // 19 A5, SCL
};
constexpr uint8_t role_cap(Role r) { return r == R_PWM ? CAP_PWM : r == R_ADC ? CAP_ADC : r == R_INTERRUPT ? CAP_INT : CAP_DIGITAL; }
// Pins that a plan may not hand out: 0 and 1 are the USB serial link, 18 and 19 belong to the I2C bus the IMU uses.
constexpr bool pin_reserved(uint8_t p) { return p == 0 || p == 1 || p == 18 || p == 19; }
constexpr bool pin_can(uint8_t p, Role r) { return p < PIN_COUNT && (PIN_CAPS[p] & role_cap(r)) != 0; }
constexpr bool pin_ok(uint8_t p, Role r) { return pin_can(p, r) && !pin_reserved(p); }
// The build robot's plan. Each line is checked at compile time: a wrong pin stops the build with the message.
const uint8_t PIN_ML_PWM = 5, PIN_ML_DIR = 4; // left motor: PWM on Timer0 B, direction line
const uint8_t PIN_MR_PWM = 6, PIN_MR_DIR = 7; // right motor: PWM on Timer0 A, direction line
const uint8_t PIN_TRIG = 8, PIN_ECHO = 12; // ultrasonic sensor
const uint8_t PIN_ENC_L = 2, PIN_ENC_R = 3; // wheel encoders: the only two interrupt pins (used from chapter 4)
const uint8_t PIN_BUMP = 11; // bumper switch
const uint8_t PIN_BATT = 14; // A0: battery voltage through a divider
const uint8_t PIN_LED = 13;
static_assert(pin_ok(PIN_ML_PWM, R_PWM) && pin_ok(PIN_MR_PWM, R_PWM), "a motor speed pin must be PWM-capable and not reserved");
static_assert(pin_ok(PIN_ML_DIR, R_DIGITAL) && pin_ok(PIN_MR_DIR, R_DIGITAL), "direction pins must be free digital pins");
static_assert(pin_ok(PIN_TRIG, R_DIGITAL) && pin_ok(PIN_ECHO, R_DIGITAL), "sensor pins must be free digital pins");
static_assert(pin_ok(PIN_ENC_L, R_INTERRUPT) && pin_ok(PIN_ENC_R, R_INTERRUPT), "encoders need interrupt-capable pins (2 and 3 on an Uno)");
static_assert(pin_ok(PIN_BUMP, R_DIGITAL) && pin_ok(PIN_LED, R_DIGITAL), "switch and LED pins must be free digital pins");
static_assert(pin_ok(PIN_BATT, R_ADC), "the battery monitor needs an analog input that I2C does not use");
The same checks, run on a PC against the plan and against six plans with one mistake each:
// e_pins.cpp -- the pin plan through the same checks the compiler uses, then a series of plans with one deliberate mistake each (host build)
#include <cstdio>
#include "pins.h"
struct Use { const char* name; uint8_t pin; Role role; };
static const char* ROLE_NAME[] = {"digital", "PWM", "analog in", "interrupt"};
// Returns the number of problems; prints each one.
static int check(const Use* u, int n) {
int bad = 0;
for (int i = 0; i < n; ++i) {
if (!pin_can(u[i].pin, u[i].role)) { std::printf(" ERROR %-14s pin %2u cannot do %s\n", u[i].name, (unsigned)u[i].pin, ROLE_NAME[u[i].role]); ++bad; }
else if (pin_reserved(u[i].pin)) { std::printf(" ERROR %-14s pin %2u is reserved (USB serial or I2C)\n", u[i].name, (unsigned)u[i].pin); ++bad; }
for (int j = 0; j < i; ++j)
if (u[j].pin == u[i].pin) { std::printf(" ERROR %-14s pin %2u is already used by %s\n", u[i].name, (unsigned)u[i].pin, u[j].name); ++bad; }
}
return bad;
}
int main() {
Use plan[] = {
{"left PWM", PIN_ML_PWM, R_PWM}, {"left dir", PIN_ML_DIR, R_DIGITAL},
{"right PWM", PIN_MR_PWM, R_PWM}, {"right dir", PIN_MR_DIR, R_DIGITAL},
{"trigger", PIN_TRIG, R_DIGITAL}, {"echo", PIN_ECHO, R_DIGITAL},
{"encoder L", PIN_ENC_L, R_INTERRUPT}, {"encoder R", PIN_ENC_R, R_INTERRUPT},
{"bumper", PIN_BUMP, R_DIGITAL}, {"battery", PIN_BATT, R_ADC}, {"LED", PIN_LED, R_DIGITAL},
};
const int n = (int)(sizeof plan / sizeof plan[0]);
std::printf("the build robot's plan (%d pins):\n", n);
for (int i = 0; i < n; ++i) std::printf(" %-10s pin %2u %s\n", plan[i].name, (unsigned)plan[i].pin, ROLE_NAME[plan[i].role]);
std::printf(" problems: %d\n", check(plan, n));
struct Mistake { const char* what; int index; uint8_t pin; };
const Mistake mistakes[] = {
{"left motor PWM moved to pin 4", 0, 4},
{"left encoder moved to pin 4", 6, 4},
{"echo wired to pin 1", 5, 1},
{"battery monitor moved to pin 7", 9, 7},
{"bumper on the same pin as the left direction line", 8, 4},
{"battery monitor on A4 (an I2C pin)", 9, 18},
};
std::printf("\nsix plans, each with one change:\n");
for (const Mistake& m : mistakes) {
Use copy[11];
for (int i = 0; i < n; ++i) copy[i] = plan[i];
copy[m.index].pin = m.pin;
std::printf(" %s:\n", m.what);
int bad = check(copy, n);
if (bad == 0) std::printf(" (no problem found)\n");
}
return 0;
}
the build robot's plan (11 pins):
left PWM pin 5 PWM
left dir pin 4 digital
right PWM pin 6 PWM
right dir pin 7 digital
trigger pin 8 digital
echo pin 12 digital
encoder L pin 2 interrupt
encoder R pin 3 interrupt
bumper pin 11 digital
battery pin 14 analog in
LED pin 13 digital
problems: 0
six plans, each with one change:
left motor PWM moved to pin 4:
ERROR left PWM pin 4 cannot do PWM
ERROR left dir pin 4 is already used by left PWM
left encoder moved to pin 4:
ERROR encoder L pin 4 cannot do interrupt
ERROR encoder L pin 4 is already used by left dir
echo wired to pin 1:
ERROR echo pin 1 is reserved (USB serial or I2C)
battery monitor moved to pin 7:
ERROR battery pin 7 cannot do analog in
ERROR battery pin 7 is already used by right dir
bumper on the same pin as the left direction line:
ERROR bumper pin 4 is already used by left dir
battery monitor on A4 (an I2C pin):
ERROR battery pin 18 is reserved (USB serial or I2C)
And for the board, the same header makes a wrong pin a build error. With the left motor's speed pin moved to pin 4 (and its direction line to 9), the Uno build stopped with:
static assertion failed: a motor speed pin must be PWM-capable and not reserved
The table is my transcription of the Uno R3 pin map. If a pin is wrong in the table, the check is wrong in the same way, so it is worth verifying against the board's own pinout once.
3. PWM: three timers, and one of them keeps the time
analogWrite(pin, 0..255) does not produce an analog voltage. It switches the pin fully on and fully off at a fixed frequency, and the fraction of each period spent on is the duty. A motor, which responds slowly, sees the average. The pulses come from one of the chip's three timers, each of which drives two pins: Timer0 pins 5 and 6, Timer1 pins 9 and 10, Timer2 pins 3 and 11. The frequency is the clock divided by the prescaler times the number of steps, 256 in fast mode and 510 in phase-correct mode (which counts up and down):
// e_pwm.cpp -- PWM frequencies of the Uno's three timers, and what an 8-bit duty does to a speed command (host build)
#include <cstdio>
#include <cmath>
#include "conv.h"
int main() {
const double F = 16000000.0;
std::printf("PWM frequency = F_CPU / (prescaler x steps); fast PWM has 256 steps, phase-correct 510:\n");
std::printf(" timer mode prescaler frequency Hz period us pins\n");
struct Row { const char* timer; const char* mode; int pre; int steps; const char* pins; };
const Row rows[] = {
{"Timer0", "fast (Arduino)", 64, 256, "5, 6"},
{"Timer1", "phase-correct", 64, 510, "9, 10"},
{"Timer2", "phase-correct", 64, 510, "3, 11"},
{"Timer1", "phase-correct", 8, 510, "9, 10"},
{"Timer1", "phase-correct", 1, 510, "9, 10"},
{"Timer1", "fast", 1, 256, "9, 10"},
};
for (const Row& r : rows) {
double hz = F / ((double)r.pre * r.steps);
std::printf(" %-6s %-14s %9d %12.2f %9.2f %s\n", r.timer, r.mode, r.pre, hz, 1.0e6 / hz, r.pins);
}
std::printf("\n8-bit duty: speed 0..0.500 m/s becomes a count 0..255, one count = %.3f mm/s\n", 0.5 / 255.0 * 1000.0);
double worst_round = 0, worst_trunc = 0, sum_trunc = 0;
int n = 0;
for (int i = 0; i <= 500; ++i) { // every commanded speed in 1 mm/s steps
float v = i / 1000.0f;
double er = std::fabs(speed_to_pwm(v, 0.5f) * 0.5 / 255.0 - v) * 1000.0;
double et = std::fabs(speed_to_pwm_truncating(v, 0.5f) * 0.5 / 255.0 - v) * 1000.0;
if (er > worst_round) worst_round = er;
if (et > worst_trunc) worst_trunc = et;
sum_trunc += (speed_to_pwm_truncating(v, 0.5f) * 0.5 / 255.0 - v) * 1000.0;
++n;
}
std::printf(" worst speed error with rounding: %.3f mm/s\n", worst_round);
std::printf(" worst speed error with truncation: %.3f mm/s (mean signed error %.3f mm/s: always low)\n", worst_trunc, sum_trunc / n);
std::printf(" speed_to_pwm(0.0009) = %u, (0.0010) = %u, (0.2500) = %u, (0.5000) = %u, (0.9000) = %u, (-0.1) = %u\n",
(unsigned)speed_to_pwm(0.0009f, 0.5f), (unsigned)speed_to_pwm(0.0010f, 0.5f), (unsigned)speed_to_pwm(0.25f, 0.5f),
(unsigned)speed_to_pwm(0.5f, 0.5f), (unsigned)speed_to_pwm(0.9f, 0.5f), (unsigned)speed_to_pwm(-0.1f, 0.5f));
return 0;
}
PWM frequency = F_CPU / (prescaler x steps); fast PWM has 256 steps, phase-correct 510:
timer mode prescaler frequency Hz period us pins
Timer0 fast (Arduino) 64 976.56 1024.00 5, 6
Timer1 phase-correct 64 490.20 2040.00 9, 10
Timer2 phase-correct 64 490.20 2040.00 3, 11
Timer1 phase-correct 8 3921.57 255.00 9, 10
Timer1 phase-correct 1 31372.55 31.88 9, 10
Timer1 fast 1 62500.00 16.00 9, 10
8-bit duty: speed 0..0.500 m/s becomes a count 0..255, one count = 1.961 mm/s
worst speed error with rounding: 0.980 mm/s
worst speed error with truncation: 1.941 mm/s (mean signed error -0.969 mm/s: always low)
speed_to_pwm(0.0009) = 0, (0.0010) = 1, (0.2500) = 128, (0.5000) = 255, (0.9000) = 255, (-0.1) = 0
Two settings in the table matter for a robot. First, the defaults are low frequencies: 490 Hz and 977 Hz are within hearing, so a motor driven by them typically whines, and a period of about 2 ms is long enough that a small motor may run unevenly (not tested here). Setting a timer to prescaler 1 gives 31 kHz, beyond hearing. Second, Timer0 is also the clock. The Arduino core counts Timer0's overflows to produce millis() and micros() (it is in the core's wiring.c, which I read: the overflow period is hard-coded as 64 × 256 clock cycles). If a program changes Timer0's prescaler to quiet motors on pins 5 and 6, every time in the program, and every timer built on it from Programming for Robotics with Arduino C++ 1, runs at the wrong rate. The build robot's two motors are on Timer0 (pins 5 and 6) because that is simple, and so the plan leaves Timer0 alone; a quieter drive would put the motors on Timer2's pins (3 and 11) and then give up pin 3 for an interrupt. A plan, not a default, decides.
The second half of the output is the other seam, the speed to duty conversion. 255 steps over 0.5 m/s is 1.961 mm/s a step, so the controller can only ask for speeds on that grid. speed_to_pwm adds 0.5 before the cast to round to the nearest step; without it the C++ cast truncates, and the speed is always a little low (mean error -0.969 mm/s, worst 1.941, against 0.980 for rounding). The same function clamps, so a command of 0.9 m/s gives 255 and -0.1 gives 0, never a value that wraps around in a uint8_t. It does not say 0.5 m/s is what a duty of 255 will really give: that depends on the motors, the battery and the load, and has to be measured on the robot (a calibration the chapter does not have, which is why V_MAX_MPS is labelled an assumption in the sketch).
4. The ADC: ten bits and 104 microseconds
analogRead(pin) returns 0 to 1023 for 0 to 5 V (the reference is the supply, so a supply that sags makes every reading wrong in step). One count is 4.888 mV. A conversion takes 13 ADC clocks, and the Arduino core sets the ADC clock to 125 kHz, so one reading takes 104 microseconds and analogRead waits for it. Noise on the input shows up as a spread in the counts; averaging N readings reduces the spread by √N, at N times the time:
// e_adc.cpp -- the 10-bit ADC: step size, conversion time, and averaging noisy readings (host build; the noise is a MODEL, not a measurement of a real input)
#include <cstdio>
#include <cmath>
#include <random>
#include "conv.h"
int main() {
const double ADC_CLOCK_HZ = 16000000.0 / 128.0; // Arduino sets the prescaler to 128: 125 kHz
const double conv_us = 13.0 / ADC_CLOCK_HZ * 1.0e6; // one conversion takes 13 ADC clocks
std::printf("one count = %.3f mV (5 V / 1023); ADC clock %.0f Hz; one conversion = %.0f us = %.0f readings per second\n",
5000.0 / 1023.0, ADC_CLOCK_HZ, conv_us, 1.0e6 / conv_us);
double worst = 0;
for (uint16_t c = 0; c <= 1023; ++c) {
double d = std::fabs(counts_to_mv(c) - counts_to_volts(c) * 1000.0);
if (d > worst) worst = d;
}
std::printf("integer counts_to_mv() against the float version, all 1024 counts: worst difference %.3f mV\n\n", worst);
std::mt19937 rng(11);
std::normal_distribution<double> noise(0.0, 1.5); // ASSUMED: 1.5 counts of noise on the input (0.5 means a good input, 3 a poor one)
const double true_counts = 409.6; // 2.000 V: between two counts, on purpose
std::printf("true input 2.000 V = 409.6 counts, noise sigma 1.5 counts (assumed), 4000 trials per row:\n");
std::printf(" readings averaged spread (std dev, counts) spread mV time per answer us spread x sqrt(N)\n");
for (int N : {1, 4, 16, 64, 256}) {
double sum = 0, sum2 = 0;
const int trials = 4000;
for (int t = 0; t < trials; ++t) {
long total = 0;
for (int i = 0; i < N; ++i) {
double x = true_counts + noise(rng);
long c = std::lround(x); // the converter rounds to a whole count
if (c < 0) c = 0;
if (c > 1023) c = 1023;
total += c;
}
double avg = (double)total / N;
sum += avg;
sum2 += avg * avg;
}
double mean = sum / trials, sd = std::sqrt(sum2 / trials - mean * mean);
std::printf(" %17d %26.3f %9.2f %18.0f %16.3f\n", N, sd, sd * 5000.0 / 1023.0, N * conv_us, sd * std::sqrt((double)N));
}
// The caveat: averaging only helps when noise dithers the reading across counts. With NO noise every reading is the same whole count.
long same = std::lround(true_counts);
std::printf("\nwith no noise at all, 256 readings of 409.6 counts average to %ld: %.1f counts (%.2f mV) from the truth, and averaging more cannot fix it\n",
same, std::fabs(same - true_counts), std::fabs(same - true_counts) * 5000.0 / 1023.0);
return 0;
}
one count = 4.888 mV (5 V / 1023); ADC clock 125000 Hz; one conversion = 104 us = 9615 readings per second
integer counts_to_mv() against the float version, all 1024 counts: worst difference 0.499 mV
true input 2.000 V = 409.6 counts, noise sigma 1.5 counts (assumed), 4000 trials per row:
readings averaged spread (std dev, counts) spread mV time per answer us spread x sqrt(N)
1 1.547 7.56 104 1.547
4 0.764 3.74 416 1.529
16 0.381 1.86 1664 1.523
64 0.190 0.93 6656 1.517
256 0.095 0.46 26624 1.515
with no noise at all, 256 readings of 409.6 counts average to 410: 0.4 counts (1.96 mV) from the truth, and averaging more cannot fix it
The last column is nearly constant (1.52): the spread falls as 1/√N, and 64 readings take a 1.5-count noise down to 0.93 mV in 6.66 ms. The noise is an assumption of 1.5 counts, a moderate input, and the figures follow from that, not from a measured input. The last line is the caveat: if there is no noise at all, every reading is the same whole count and averaging cannot recover the 0.4 count between them. Averaging helps only because noise spreads the readings across neighbouring counts.
Converting counts to a voltage can be done in integers: counts_to_mv multiplies by 5000 in a uint32_t and divides by 1023, rounding, and it differs from the float version by at most 0.499 mV. Compiled for the Uno, a sketch that does this and writes a PWM duty with the integer version is 1118 bytes of flash; the identical sketch with the float version is 1818 bytes, 700 bytes larger, because the AVR has no floating-point hardware and the float multiply and divide come from a software library. The robot code still uses floats (the controller needs them) and the cost is paid once; the lesson is not to add a second float function for a job that integers do exactly.
5. A sensor in digital pins, without blocking
The common HC-SR04 ultrasonic sensor has two pins: a 10-microsecond pulse on trigger sends a burst of sound, and echo then goes high for the time the sound takes to travel to an object and back. The distance is the width of that pulse times the speed of sound (343 m/s in dry air at about 20°C) over two. Arduino's pulseIn() measures the width, but it waits inside the call until the pulse ends or its timeout passes, which is exactly the delay() problem of Programming for Robotics with Arduino C++ 1 in a new coat. How long it would block a 20 ms control period:
// e_echo.cpp -- the non-blocking echo driver against a fake sensor, polled every 10, 100 and 1000 us; and the time a blocking pulseIn() would take instead (host build, fake clock)
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "echo.h"
#include "conv.h"
struct FakeSensor { // an object at distance d: echo is high from the end of the trigger for the round trip
float d_m;
uint32_t t_trig_fall;
bool trig_prev;
bool armed;
explicit FakeSensor(float d) : d_m(d), t_trig_fall(0), trig_prev(false), armed(false) {}
bool echo(uint32_t now, bool trig) {
if (trig_prev && !trig) { t_trig_fall = now; armed = true; } // the trigger just fell: the sound pulse leaves now
trig_prev = trig;
if (!armed || d_m > 4.0f) return false; // beyond about 4 m there is no echo
uint32_t w = m_to_echo_us(d_m);
return now >= t_trig_fall && now < t_trig_fall + w;
}
};
// Returns the measured distance in metres, or -1 on a timeout. `waited_us` is the time the measurement took; the caller was free for all of it.
static float measure(float d, uint32_t poll_us, uint32_t* took_us) {
Echo e;
FakeSensor s(d);
bool trig = false;
uint32_t t = 1000; // an arbitrary start time
e.start();
uint32_t t_start = t;
for (;;) {
bool echo = s.echo(t, trig);
Echo::Status st = e.update(t, echo, trig);
if (st != Echo::BUSY) {
*took_us = t - t_start;
return st == Echo::READY ? echo_us_to_m(e.width_us()) : -1.0f;
}
t += poll_us;
}
}
int main() {
std::printf("worst distance error of the polled state machine over distances 0.10 to 3.50 m in 50 mm steps (a fake sensor, no noise):\n");
std::printf(" polled every worst error mm expected: one poll = %s\n", "poll_us x 0.1715 mm/us");
for (uint32_t poll : {10u, 100u, 1000u}) {
double worst = 0;
for (int i = 0; i <= 66; ++i) {
float d = 0.10f + 0.05f * i;
uint32_t took;
float m = measure(d, poll, &took);
double err = std::fabs(m - d) * 1000.0;
if (err > worst) worst = err;
}
std::printf(" %9u us %13.1f %.1f mm\n", (unsigned)poll, worst, poll * 0.1715);
}
std::printf("\ntime the board is stuck inside pulseIn() for one reading, against a 20 ms control period (the echo width plus the 10 us trigger):\n");
std::printf(" object at echo width us blocked ms share of a 20 ms period\n");
for (float d : {0.3f, 1.0f, 2.0f, 3.5f}) {
uint32_t w = m_to_echo_us(d);
std::printf(" %6.1f m %12u %10.2f %6.1f %%\n", d, (unsigned)w, (w + 10) / 1000.0, (w + 10) / 200.0);
}
std::printf(" nothing there: pulseIn() waits its timeout, 30 ms by the setting used here: %.1f ms, %.0f %% of the period (a control task cannot run for 30 ms in a 20 ms slot)\n",
30.0, 30.0 / 20.0 * 100.0);
uint32_t took;
float m = measure(2.0f, 100, &took);
std::printf("\nnon-blocking, object at 2.000 m, polled every 100 us: measured %.3f m, took %u us of which the program was FREE for all but the 100 us polls\n", m, (unsigned)took);
m = measure(5.0f, 100, &took);
std::printf("object at 5.000 m (out of range): result %s after %u us\n", m < 0 ? "TIMEOUT (-1)" : "a distance", (unsigned)took);
return 0;
}
worst distance error of the polled state machine over distances 0.10 to 3.50 m in 50 mm steps (a fake sensor, no noise):
polled every worst error mm expected: one poll = poll_us x 0.1715 mm/us
10 us 1.6 1.7 mm
100 us 17.0 17.2 mm
1000 us 165.5 171.5 mm
time the board is stuck inside pulseIn() for one reading, against a 20 ms control period (the echo width plus the 10 us trigger):
object at echo width us blocked ms share of a 20 ms period
0.3 m 1749 1.76 8.8 %
1.0 m 5831 5.84 29.2 %
2.0 m 11662 11.67 58.4 %
3.5 m 20408 20.42 102.1 %
nothing there: pulseIn() waits its timeout, 30 ms by the setting used here: 30.0 ms, 150 % of the period (a control task cannot run for 30 ms in a 20 ms slot)
non-blocking, object at 2.000 m, polled every 100 us: measured 2.007 m, took 11900 us of which the program was FREE for all but the 100 us polls
object at 5.000 m (out of range): result TIMEOUT (-1) after 30100 us
At 1 m pulseIn holds the board for 5.84 ms (29 % of a 20 ms period); at 3.5 m it holds it for the whole period (102 %); and with nothing in front of the sensor it waits for its full timeout, longer than the period. A robot that is stuck facing open space would run its control loop late exactly when it has nothing to see. The driver in echo.h is therefore a state machine: start makes it raise the trigger, update is called as often as the loop can, it is handed the time and the echo pin's level and gives back the trigger's level, and it measures the width itself from the moment it sees the pin rise to the moment it sees it fall.
// echo.h -- a NON-BLOCKING driver for an HC-SR04 style ultrasonic sensor, as a state machine. Plain C++11: it never reads a pin or a clock itself;
// the caller passes in the time and the echo level and gets back the trigger level to write. That is what lets a PC test it.
#pragma once
#include <stdint.h>
#include "timing.h"
class Echo {
public:
enum Status : uint8_t { BUSY, READY, TIMEOUT };
enum State : uint8_t { IDLE, TRIG_HIGH, WAIT_RISE, WAIT_FALL };
Echo() : state_(IDLE), t0_(0), rise_(0), width_(0) {}
void start() { if (state_ == IDLE) state_ = TRIG_HIGH; } // ask for one measurement; a request while one is running is ignored
bool idle() const { return state_ == IDLE; }
uint32_t width_us() const { return width_; } // valid after READY
// Call as often as you like. `trig` is the level the trigger pin should have after this call.
Status update(uint32_t now_us, bool echo, bool& trig) {
switch (state_) {
case IDLE:
trig = false;
return BUSY;
case TRIG_HIGH: // the sensor wants a trigger pulse of at least 10 us
if (t0_ == 0 && !trig) { trig = true; t0_ = now_us ? now_us : 1; return BUSY; }
if (elapsed(now_us, t0_) >= 10) { trig = false; state_ = WAIT_RISE; }
return BUSY;
case WAIT_RISE:
if (echo) { rise_ = now_us; state_ = WAIT_FALL; return BUSY; }
if (elapsed(now_us, t0_) > TIMEOUT_US) return finish(TIMEOUT);
return BUSY;
case WAIT_FALL:
if (!echo) { width_ = elapsed(now_us, rise_); return finish(READY); }
if (elapsed(now_us, t0_) > TIMEOUT_US) return finish(TIMEOUT);
return BUSY;
}
return BUSY;
}
static const uint32_t TIMEOUT_US = 30000; // 30 ms after the trigger: the sensor's range is about 4 m (23 ms)
private:
Status finish(Status s) { state_ = IDLE; t0_ = 0; return s; }
State state_;
uint32_t t0_, rise_, width_;
};
The first block of the output shows the price. The width is measured by polling, so the error is up to one poll interval: 17.0 mm when polled every 100 microseconds, 165.5 mm when polled every millisecond, in line with the 0.1715 mm of distance in each microsecond (the speed of sound halved). The program was free for all of the measurement except the polls. This is a fake sensor: it models the echo as a clean pulse starting the instant the trigger falls, which ignores the sensor's burst delay and any noise, and it never lets two readings overlap. A real sensor adds a fixed offset and variation, and the machine's lower limit on what it can resolve then depends on how fast the real loop() runs, which was not measured. Challenge 1 asks how fast that has to be for 10 mm, and a pin-change interrupt can replace the polling (the interrupt tools arrive in Programming for Robotics with Arduino C++ 4).
6. UART, I2C and SPI, and what each costs
Three buses carry most of what a robot talks to, and the first thing to know about each is its time cost. They are compared by arithmetic here, and then by the memory their libraries use.
The three buses in one paragraph
UART (Serial): two wires, no clock, both ends must agree on the rate; one byte is 10 bits on the wire (start, 8 data, stop). I2C (Wire): two wires shared by many devices, each with an address; every byte is followed by an acknowledge bit (9 clocks a byte); the standard clocks are 100 and 400 kHz. SPI: a clock, data out, data in and one select line per device; no addresses and no acknowledge, and fast (a clock of the CPU clock divided by 2 to 128).
// e_bus.cpp -- what UART, I2C and SPI cost in time: baud-rate error, how long a log line takes, how long a sensor read takes (host build; arithmetic, not a measurement of a board)
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "conv.h"
int main() {
const uint32_t F = 16000000UL;
std::printf("UART: the divisor UBRR gives the nearest rate the clock can make (U2X = double-speed mode, which Arduino uses)\n");
std::printf(" wanted baud mode UBRR actual baud error %%\n");
for (uint32_t baud : {9600UL, 57600UL, 115200UL, 230400UL, 250000UL, 500000UL, 1000000UL}) {
uint16_t un = uart_ubrr_normal(F, baud), u2 = uart_ubrr_u2x(F, baud);
double an = F / (16.0 * (un + 1)), a2 = F / (8.0 * (u2 + 1));
std::printf(" %11lu normal %5u %11.0f %+7.2f\n", (unsigned long)baud, (unsigned)un, an, (an - baud) / baud * 100.0);
std::printf(" %11s U2X %5u %11.0f %+7.2f\n", "", (unsigned)u2, a2, (a2 - baud) / baud * 100.0);
}
std::printf("\na 40-character log line (10 bits per character on the wire) against a 20 ms control period:\n");
std::printf(" baud us per character time for 40 characters ms fits in 20 ms?\n");
for (uint32_t baud : {9600UL, 57600UL, 115200UL, 250000UL}) {
double us_char = 10.0 / baud * 1.0e6, ms_line = 40.0 * us_char / 1000.0;
std::printf(" %6lu %15.1f %25.2f %s\n", (unsigned long)baud, us_char, ms_line, ms_line < 20.0 ? "yes" : "NO: the 64-byte buffer fills and Serial.print blocks");
}
std::printf("\nreading 14 bytes from a sensor register (one register-address byte first), by bus clock:\n");
std::printf(" bus clock bus clocks time us share of a 20 ms period\n");
for (uint32_t scl : {100000UL, 400000UL}) {
uint32_t us = i2c_transfer_us(scl, 14, 1);
std::printf(" I2C %6lu %9u %7lu %6.2f %%\n", (unsigned long)scl, (unsigned)(9 * (1 + 1 + 14) + 2), (unsigned long)us, us / 200.0);
}
for (uint8_t div : {4, 16, 128}) {
uint32_t us = spi_transfer_us(F, div, 15); // a register address byte plus 14 data bytes
std::printf(" SPI F/%-3u %9u %7lu %6.2f %%\n", (unsigned)div, 8 * 15, (unsigned long)us, us / 200.0);
}
return 0;
}
UART: the divisor UBRR gives the nearest rate the clock can make (U2X = double-speed mode, which Arduino uses)
wanted baud mode UBRR actual baud error %
9600 normal 103 9615 +0.16
U2X 207 9615 +0.16
57600 normal 16 58824 +2.12
U2X 34 57143 -0.79
115200 normal 8 111111 -3.55
U2X 16 117647 +2.12
230400 normal 3 250000 +8.51
U2X 8 222222 -3.55
250000 normal 3 250000 +0.00
U2X 7 250000 +0.00
500000 normal 1 500000 +0.00
U2X 3 500000 +0.00
1000000 normal 0 1000000 +0.00
U2X 1 1000000 +0.00
a 40-character log line (10 bits per character on the wire) against a 20 ms control period:
baud us per character time for 40 characters ms fits in 20 ms?
9600 1041.7 41.67 NO: the 64-byte buffer fills and Serial.print blocks
57600 173.6 6.94 yes
115200 86.8 3.47 yes
250000 40.0 1.60 yes
reading 14 bytes from a sensor register (one register-address byte first), by bus clock:
bus clock bus clocks time us share of a 20 ms period
I2C 100000 146 1460 7.30 %
I2C 400000 146 365 1.82 %
SPI F/4 120 30 0.15 %
SPI F/16 120 120 0.60 %
SPI F/128 120 960 4.80 %
Three results to remember. Baud rates are approximations: 115200 is not available exactly, and the divider gives 111111 (-3.55 %) in normal mode or 117647 (+2.12 %) in double-speed mode. The Arduino core uses double-speed mode (I read it: it computes the divisor for double speed first, and falls back to normal only when the divisor does not fit, and for 57600 on a 16 MHz board as a special case), so Serial at 115200 runs 2.12 % fast, which works against a PC whose own rate is accurate because UART receivers tolerate a few percent. At 230400 the normal-mode error is 8.51 % and would not.
Printing is a transfer, and the bytes leave at one every 86.8 microseconds at 115200 (10 bits). A 40-character line takes 3.47 ms; at 9600 baud it takes 41.67 ms, longer than the loop. The Uno's Serial has a 64-byte transmit buffer, and when it is full print()waits (the core's write() spins on a full buffer; I read it). That is the same trap as delay(); challenge 3 puts a number on it.
An I2C register read has a fixed cost: 14 bytes plus the register address is 146 bus clocks, 1460 microseconds at 100 kHz (7.3 % of a 20 ms period) and 365 at 400 kHz (1.82 %). The cost is the same whether the device is fast or slow, and six devices, each read for 14 bytes every period at 100 kHz, would spend over 40 % of every period on the bus. (The 146 counts 9 clocks a byte for the address byte, the register byte and the 14 data bytes, plus two for the start and stop; it ignores the repeated start and any time the device stretches the clock, so a real transfer is a little longer.) The library costs are real compiler reports:
Sketch (each does one transfer in loop())
Flash
RAM
empty
444 bytes
9 bytes
+ Serial at 115200, one println(F(...))
1492 bytes (+1048)
188 bytes (+179)
+ Wire (I2C) at 400 kHz
2876 bytes (+2432)
225 bytes (+216)
+ SPI
840 bytes (+396)
10 bytes (+1)
Wire costs 216 bytes of RAM, over 10 % of the board (the library keeps send and receive buffers; the compiler’s report does not break the figure down); Serial costs 179 bytes for its 64-byte transmit buffer and 64-byte receive buffer and bookkeeping; SPI costs almost nothing. These are the first of the bills that the budget table at the end of the chapter adds up.
7. Reading a datasheet: a register map into a driver
An I2C chip is a numbered list of one-byte registers. A datasheet's register map says what each means; a driver is a translation of that table into code. The example is the MPU-6050, a common six-axis motion sensor, whose map (as I know it; check the datasheet of your part) has these entries that matter here:
Register
Address
What the map says
WHO_AM_I
0x75
always reads 0x68
PWR_MGMT_1
0x6B
bit 6 is SLEEP and is set at power-up: the chip starts asleep
ACCEL_CONFIG / GYRO_CONFIG
0x1C / 0x1B
bits 4:3 pick the range: ±2/4/8/16 g (16384/8192/4096/2048 counts per g) and ±250/500/1000/2000 deg/s (131/65.5/32.8/16.4 counts per deg/s)
ACCEL_XOUT_H ...
0x3B … 0x48
14 bytes: accelerometer X, Y, Z, temperature, gyro X, Y, Z; each a signed 16-bit number, high byte first; temperature in °C is raw / 340 + 36.53
The driver is a template on the bus, the same idea as the robot being a template on its hardware, so the PC can test it with a fake chip and the board runs it over Wire. It reads all 14 bytes in one burst, so every value is from the same instant:
// imu.h -- a register-level driver for an MPU-6050 style accelerometer + gyroscope, written from the register map. Plain C++11; the bus is a template parameter.
// A Bus must provide: bool write_reg(uint8_t dev, uint8_t reg, uint8_t value);
// bool read_regs(uint8_t dev, uint8_t reg, uint8_t* buf, uint8_t n); (both return false if the device does not answer)
#pragma once
#include <stdint.h>
namespace mpu {
const uint8_t ADDR = 0x68; // the 7-bit I2C address with the AD0 pin low
const uint8_t REG_GYRO_CONFIG = 0x1B;
const uint8_t REG_ACCEL_CONFIG = 0x1C;
const uint8_t REG_ACCEL_XOUT_H = 0x3B; // 14 bytes from here: accel X,Y,Z (H,L each), temperature (H,L), gyro X,Y,Z (H,L each)
const uint8_t REG_PWR_MGMT_1 = 0x6B; // bit 6 = SLEEP, and it is SET after a power-up
const uint8_t REG_WHO_AM_I = 0x75; // always reads 0x68
const uint8_t WHO_AM_I_VALUE = 0x68;
} // namespace mpu
struct ImuSample { float ax_g, ay_g, az_g; float temp_c; float gx_dps, gy_dps, gz_dps; };
inline int16_t be16(uint8_t hi, uint8_t lo) { return (int16_t)(((uint16_t)hi << 8) | lo); } // two bytes, high first, as a SIGNED number
template <class Bus>
class Imu {
public:
enum Error : uint8_t { OK, NO_ANSWER, WRONG_DEVICE };
explicit Imu(Bus& bus) : bus_(bus), accel_lsb_per_g_(16384.0f), gyro_lsb_per_dps_(131.0f) {}
// accel_range 0..3 = +-2, 4, 8, 16 g; gyro_range 0..3 = +-250, 500, 1000, 2000 deg/s. Register field = bits 4..3.
Error begin(uint8_t accel_range = 0, uint8_t gyro_range = 0) {
uint8_t who = 0;
if (!bus_.read_regs(mpu::ADDR, mpu::REG_WHO_AM_I, &who, 1)) return NO_ANSWER;
if (who != mpu::WHO_AM_I_VALUE) return WRONG_DEVICE;
if (!bus_.write_reg(mpu::ADDR, mpu::REG_PWR_MGMT_1, 0x00)) return NO_ANSWER; // clear SLEEP: until then every data register reads zero
if (!bus_.write_reg(mpu::ADDR, mpu::REG_ACCEL_CONFIG, (uint8_t)((accel_range & 3) << 3))) return NO_ANSWER;
if (!bus_.write_reg(mpu::ADDR, mpu::REG_GYRO_CONFIG, (uint8_t)((gyro_range & 3) << 3))) return NO_ANSWER;
static const float ACCEL_LSB[4] = {16384.0f, 8192.0f, 4096.0f, 2048.0f}; // counts per g, from the datasheet table
static const float GYRO_LSB[4] = {131.0f, 65.5f, 32.8f, 16.4f}; // counts per deg/s
accel_lsb_per_g_ = ACCEL_LSB[accel_range & 3];
gyro_lsb_per_dps_ = GYRO_LSB[gyro_range & 3];
return OK;
}
bool read(ImuSample& s) { // ONE burst of 14 bytes: all values from the same instant
uint8_t b[14];
if (!bus_.read_regs(mpu::ADDR, mpu::REG_ACCEL_XOUT_H, b, 14)) return false;
s.ax_g = be16(b[0], b[1]) / accel_lsb_per_g_;
s.ay_g = be16(b[2], b[3]) / accel_lsb_per_g_;
s.az_g = be16(b[4], b[5]) / accel_lsb_per_g_;
s.temp_c = be16(b[6], b[7]) / 340.0f + 36.53f;
s.gx_dps = be16(b[8], b[9]) / gyro_lsb_per_dps_;
s.gy_dps = be16(b[10], b[11]) / gyro_lsb_per_dps_;
s.gz_dps = be16(b[12], b[13]) / gyro_lsb_per_dps_;
return true;
}
private:
Bus& bus_;
float accel_lsb_per_g_, gyro_lsb_per_dps_;
};
A fake MPU-6050 (a few dozen lines, only the registers the driver touches, with the sleep behaviour of the map) and four experiments:
// e_imu.cpp -- the register-level driver against a FAKE MPU-6050 that implements only the registers imu.h uses (host build).
// The fake is written from my reading of the register map; it shows that the driver does what the map says, not what a real chip does.
#include <cstdio>
#include <cmath>
#include <cstring>
#include "imu.h"
struct FakeMpu {
uint8_t reg[128];
uint8_t who; // what WHO_AM_I will say (0x68 for the right chip)
bool present;
float ax, ay, az, temp, gx, gy, gz; // the "physical" truth: g, deg/C, deg/s
FakeMpu() : who(0x68), present(true), ax(-0.25f), ay(0.10f), az(0.95f), temp(25.0f), gx(3.0f), gy(-7.5f), gz(-12.5f) {
std::memset(reg, 0, sizeof reg);
reg[0x6B] = 0x40; // power-up value: SLEEP bit set
}
static void put(uint8_t* p, long v) { p[0] = (uint8_t)((v >> 8) & 0xFF); p[1] = (uint8_t)(v & 0xFF); }
uint8_t read1(uint8_t r) {
if (r == 0x75) return who;
if (r >= 0x3B && r <= 0x48) {
if (reg[0x6B] & 0x40) return 0; // asleep: the data registers read zero
static const float ACC[4] = {16384.0f, 8192.0f, 4096.0f, 2048.0f}, GYR[4] = {131.0f, 65.5f, 32.8f, 16.4f};
float a = ACC[(reg[0x1C] >> 3) & 3], g = GYR[(reg[0x1B] >> 3) & 3];
uint8_t d[14];
put(d + 0, std::lround(ax * a)); put(d + 2, std::lround(ay * a)); put(d + 4, std::lround(az * a));
put(d + 6, std::lround((temp - 36.53f) * 340.0f));
put(d + 8, std::lround(gx * g)); put(d + 10, std::lround(gy * g)); put(d + 12, std::lround(gz * g));
return d[r - 0x3B];
}
return reg[r & 127];
}
bool write_reg(uint8_t dev, uint8_t r, uint8_t v) { if (!present || dev != 0x68) return false; reg[r & 127] = v; return true; }
bool read_regs(uint8_t dev, uint8_t r, uint8_t* buf, uint8_t n) {
if (!present || dev != 0x68) return false;
for (uint8_t i = 0; i < n; ++i) buf[i] = read1((uint8_t)(r + i));
return true;
}
};
static void show(const char* label, const ImuSample& s) {
std::printf(" %-34s a = (%+.3f, %+.3f, %+.3f) g T = %.2f C w = (%+.2f, %+.2f, %+.2f) deg/s\n", label, s.ax_g, s.ay_g, s.az_g, s.temp_c, s.gx_dps, s.gy_dps, s.gz_dps);
}
int main() {
ImuSample s;
{
FakeMpu chip;
std::printf("1. read the data registers WITHOUT waking the chip:\n");
Imu<FakeMpu> imu(chip);
imu.read(s);
show("after power-up, still asleep", s);
}
{
FakeMpu chip;
Imu<FakeMpu> imu(chip);
std::printf("2. begin(), then read (truth: a = (-0.250, 0.100, 0.950) g, T = 25 C, w = (3.0, -7.5, -12.5) deg/s):\n");
int err = (int)imu.begin(); // a separate statement: the ORDER in which printf's arguments are evaluated is not defined
std::printf(" begin() returned %d (0 = OK); PWR_MGMT_1 is now 0x%02X\n", err, chip.reg[0x6B]);
imu.read(s);
show("+-2 g, +-250 deg/s", s);
}
{
FakeMpu chip;
Imu<FakeMpu> imu(chip);
imu.begin(3, 3); // +-16 g, +-2000 deg/s
imu.read(s);
show("+-16 g, +-2000 deg/s (range set)", s);
}
std::printf("3. errors the driver can report:\n");
{
FakeMpu chip;
chip.present = false;
Imu<FakeMpu> imu(chip);
std::printf(" no chip on the bus: begin() = %d (1 = NO_ANSWER)\n", (int)imu.begin());
FakeMpu other;
other.who = 0x70;
Imu<FakeMpu> imu2(other);
std::printf(" a different chip (WHO_AM_I 0x70): begin() = %d (2 = WRONG_DEVICE)\n", (int)imu2.begin());
}
std::printf("4. two classic mistakes, with the same chip and the same truth:\n");
{
FakeMpu chip;
Imu<FakeMpu> imu(chip);
imu.begin();
uint8_t b[14];
chip.read_regs(0x68, 0x3B, b, 14);
uint16_t wrong = ((uint16_t)b[0] << 8) | b[1]; // the same two bytes as an UNSIGNED number
std::printf(" ax raw bytes 0x%02X 0x%02X: signed %d -> %+.3f g; as unsigned %u -> %+.3f g (the sign is lost)\n",
b[0], b[1], (int)be16(b[0], b[1]), be16(b[0], b[1]) / 16384.0f, (unsigned)wrong, wrong / 16384.0f);
Imu<FakeMpu> forgot(chip); // the chip is set to +-16 g but the driver still divides by 16384
chip.reg[0x1C] = 3 << 3;
forgot.read(s);
show("chip at +-16 g, driver at +-2 g", s);
}
return 0;
}
1. read the data registers WITHOUT waking the chip:
after power-up, still asleep a = (+0.000, +0.000, +0.000) g T = 36.53 C w = (+0.00, +0.00, +0.00) deg/s
2. begin(), then read (truth: a = (-0.250, 0.100, 0.950) g, T = 25 C, w = (3.0, -7.5, -12.5) deg/s):
begin() returned 0 (0 = OK); PWR_MGMT_1 is now 0x00
+-2 g, +-250 deg/s a = (-0.250, +0.100, +0.950) g T = 25.00 C w = (+3.00, -7.50, -12.50) deg/s
+-16 g, +-2000 deg/s (range set) a = (-0.250, +0.100, +0.950) g T = 25.00 C w = (+2.99, -7.50, -12.50) deg/s
3. errors the driver can report:
no chip on the bus: begin() = 1 (1 = NO_ANSWER)
a different chip (WHO_AM_I 0x70): begin() = 2 (2 = WRONG_DEVICE)
4. two classic mistakes, with the same chip and the same truth:
ax raw bytes 0xF0 0x00: signed -4096 -> -0.250 g; as unsigned 61440 -> +3.750 g (the sign is lost)
chip at +-16 g, driver at +-2 g a = (-0.031, +0.013, +0.119) g T = 25.00 C w = (+3.00, -7.50, -12.50) deg/s
Read the output as four lessons, each a mistake that a datasheet's register map predicts:
The chip starts asleep. Experiment 1 skips the wake-up, and every value is exactly zero. Note the temperature: 36.53 °C, because a raw zero in the temperature formula is a believable temperature. A zero that reads as a plausible number is more dangerous than an obvious fault, so the driver’s begin() clears the SLEEP bit before anything is read.
Verify the identity. Experiment 3 shows begin() telling apart no answer from another chip at the same address (WHO_AM_I 0x70), which are different wiring faults.
Bytes are signed. The same two bytes (0xF0, 0x00) are -4096, or -0.250 g, as a signed number and 61440, or +3.750 g, as an unsigned one: the sign is gone and the robot would believe it had a 3.75 g shove. be16() builds a signed 16-bit value on purpose.
The scale goes with the range. Setting the chip to ±16 g and dividing by the ±2 g constant reads (-0.031, 0.013, 0.119) g where the truth is (-0.250, 0.100, 0.950): eight times too small. Experiment 2 also shows the price of range: at ±2000 deg/s the 3.0 deg/s turn reads 2.99, because a count is 0.061 deg/s there and 3.0 is not a whole number of counts.
This is a driver tested against my reading of the map. A real chip can also disagree with its own datasheet (a different silicon revision, a clone with another WHO_AM_I), and a real bus can return an error mid-transfer; the driver reports the second by returning false, and the sketch logs it, but nothing here tested it on hardware.
8. Wiring the build robot
The robot of this course has two driven wheels with an H-bridge motor driver for each (a speed pin and a direction pin), an ultrasonic sensor, two wheel encoders, a bumper switch, a battery-voltage divider and an IMU. The plan in section 2 gives each a pin, and the reasoning is in the table:
Part
Pin
Why that pin
left motor speed / direction
5 / 4
5 is PWM (Timer0 B); 4 is plain digital
right motor speed / direction
6 / 7
6 is PWM (Timer0 A); 7 is plain digital. Both motors share a timer, so they share a frequency
ultrasonic trigger / echo
8 / 12
any digital pins; 9 and 10 stay free for Timer1 and a servo later
wheel encoders
2 and 3
the only two interrupt-capable pins; reserved now, used in Programming for Robotics with Arduino C++ 4
bumper switch
11
digital input with the internal pull-up, so the switch just connects the pin to ground
battery voltage
A0 (14)
an analog input, through a divider so 5 V is never exceeded
IMU (SDA / SCL)
A4 / A5
the fixed I2C pins
USB serial
0 and 1
reserved: anything wired here disturbs uploads and Serial
The sketch below is the whole of it. PinHW has the same two functions as chapter 1’s SimHW, so WallRobot<PinHW> is the same robot code with real pins. The echo state machine is polled on every pass of loop() because it needs fine time resolution, while everything else hangs off the scheduler. The bumper is read on every pass as well and latches an emergency stop, so the controller can no longer move the robot: an earlier draft only wrote a speed of zero, which the next 20 ms act would simply have overwritten.
// robot_ch2.ino -- Programming for Robotics with Arduino C++, chapter 2: the wall robot on REAL pins.
// Compile-checked for the Arduino Uno R3 (arduino:avr:uno). NOT run on a board: no board was attached.
#include <Wire.h>
#include "scheduler.h"
#include "log.h"
#include "robot.h"
#include "conv.h"
#include "echo.h"
#include "imu.h"
#include "pins.h"
const float V_MAX_MPS = 0.5f; // the speed that a PWM count of 255 is taken to mean (a calibration the chapter does NOT supply)
// ---- the hardware as WallRobot sees it: the same two functions as SimHW in chapter 1 ----
class PinHW {
public:
PinHW() : range_m_(9.99f), estop_(false) {}
float range_m() { return range_m_; }
void drive(float v) { // forward only in this chapter; the direction lines are fixed
uint8_t duty = estop_ ? 0 : speed_to_pwm(v, V_MAX_MPS); // once the bumper has latched the stop, the controller can no longer move the robot
analogWrite(PIN_ML_PWM, duty);
analogWrite(PIN_MR_PWM, duty);
}
void set_range(float m) { range_m_ = m; }
void emergency_stop() { estop_ = true; drive(0.0f); } // latched until the board is reset
private:
float range_m_;
bool estop_;
};
// ---- the I2C bus as Imu<> wants it ----
struct WireBus {
bool write_reg(uint8_t dev, uint8_t reg, uint8_t value) {
Wire.beginTransmission(dev);
Wire.write(reg);
Wire.write(value);
return Wire.endTransmission() == 0;
}
bool read_regs(uint8_t dev, uint8_t reg, uint8_t* buf, uint8_t n) {
Wire.beginTransmission(dev);
Wire.write(reg);
if (Wire.endTransmission(false) != 0) return false; // false = keep the bus (repeated start)
if (Wire.requestFrom(dev, n) != n) return false;
for (uint8_t i = 0; i < n; ++i) buf[i] = Wire.read();
return true;
}
};
static PinHW hw;
static WallRobot<PinHW> robot(hw, 0.25f, 1.5f, V_MAX_MPS);
static Echo echo;
static WireBus wire_bus;
static Imu<WireBus> imu(wire_bus);
static ImuSample imu_sample;
static Scheduler<7> sch;
static RingLog<32> blackbox;
static bool trig_level = false;
static uint16_t battery_mv = 0;
enum { MSG_BOOT = 0, MSG_RANGE = 1, MSG_NO_ECHO = 2, MSG_IMU_FAIL = 3, MSG_BATT = 4 };
static void echo_start_task(void*, uint32_t) { echo.start(); } // one measurement per 60 ms, the sensor's recommended minimum cycle
static void imu_task(void*, uint32_t now) { if (!imu.read(imu_sample)) blackbox.add(now, LOG_WARN, MSG_IMU_FAIL, 0); }
static void battery_task(void*, uint32_t now) {
battery_mv = counts_to_mv(analogRead(PIN_BATT));
blackbox.add(now, LOG_DEBUG, MSG_BATT, (int16_t)battery_mv);
}
static void report_task(void*, uint32_t now) {
Serial.print(now); Serial.print(F(" ms range ")); Serial.print(robot.range(), 3);
Serial.print(F(" m cmd ")); Serial.print(robot.command(), 3);
Serial.print(F(" m/s az ")); Serial.print(imu_sample.az_g, 2);
Serial.print(F(" g batt ")); Serial.print(battery_mv); Serial.println(F(" mV"));
}
void setup() {
Serial.begin(115200);
pinMode(PIN_ML_DIR, OUTPUT); pinMode(PIN_MR_DIR, OUTPUT);
digitalWrite(PIN_ML_DIR, HIGH); digitalWrite(PIN_MR_DIR, HIGH); // forward
pinMode(PIN_ML_PWM, OUTPUT); pinMode(PIN_MR_PWM, OUTPUT);
pinMode(PIN_TRIG, OUTPUT); pinMode(PIN_ECHO, INPUT);
pinMode(PIN_BUMP, INPUT_PULLUP); pinMode(PIN_LED, OUTPUT);
Wire.begin();
Wire.setClock(400000);
Imu<WireBus>::Error e = imu.begin();
blackbox.add(millis(), e == Imu<WireBus>::OK ? LOG_INFO : LOG_WARN, MSG_BOOT, (int16_t)e);
sch.add(WallRobot<PinHW>::sense_task, &robot, 20);
sch.add(WallRobot<PinHW>::think_task, &robot, 20);
sch.add(WallRobot<PinHW>::act_task, &robot, 20);
sch.add(echo_start_task, 0, 60);
sch.add(imu_task, 0, 20);
sch.add(battery_task, 0, 1000);
sch.add(report_task, 0, 500);
}
void loop() {
// the echo state machine is polled on EVERY pass: it needs microsecond-level looks, the scheduler's millisecond periods are too coarse for it
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(9.99f); blackbox.add(millis(), LOG_WARN, MSG_NO_ECHO, 0); }
if (digitalRead(PIN_BUMP) == LOW) hw.emergency_stop(); // the bumper is read on every pass, not on a 20 ms schedule
sch.run(millis());
}
9. The budget
The compiler’s report for robot_ch2.ino on the Uno, from the figures in this chapter:
Build
Flash (of 32,256)
RAM by globals (of 2,048)
Left for the stack
Programming for Robotics with Arduino C++ 1 sketch (log of 16)
4950 bytes (15 %)
473 bytes (23 %)
1575 bytes
robot_ch2.ino: Serial, Wire, 7 tasks, log of 32, echo and IMU drivers
9606 bytes (29 %)
936 bytes (45 %)
1112 bytes
Adding real hardware roughly doubled the flash (4950 to 9606) and the RAM (473 to 936). Of the RAM, Serial accounts for about 179 bytes, Wire for about 216, the 32-record log for 256 (8 bytes each, as in chapter 1), and the rest is the scheduler's seven tasks and the drivers. Flash still has 70 % free; RAM has 1112 bytes left for the stack, a comfortable margin only until a deeper call chain or a bigger buffer arrives, and, as in chapter 1, that figure is what is available: the stack’s real depth was not measured because the sketch was not run.
The time budget for one 20 ms control period, by arithmetic from this chapter (the model, not a measurement of a board): one 14-byte IMU read at 400 kHz is 365 microseconds (1.8 %); one ADC reading is 104 microseconds (0.5 %); the echo state machine costs only its polls; and a 40-character status line at 115200 baud is 3.47 ms of wire time, which does not block while it fits in the 64-byte buffer. The scheduler and Periodic from chapter 1 measure the lateness of each task, and the first thing to do on a real board is to read those numbers.
Challenges
Challenge 1: How fast must the echo be polled?
Using the Echo state machine and a fake sensor, find how often it must be polled for the distance error to stay under 10 mm. Test intervals of 20, 40, 50, 58, 60, 80 and 200 microseconds, over 67 distances from 0.10 to 3.40 m, and vary where the polls fall in time relative to the sensor (8 phases). Compare the answer with the arithmetic (10 mm ÷ 0.1715 mm per microsecond).
Challenge 2: How much averaging can the loop afford?
For ADC noise of 0.3, 1.5 and 4.0 counts (assumed), find the smallest number of readings (a power of two) whose average has a spread under 1 mV, and its cost in time at 104 microseconds a reading as a share of a 20 ms period. Say what the third case means for the design.
Challenge 3: When does a log line stall the robot?
Model the Uno's 64-byte transmit buffer (it accepts 64 bytes without waiting, then print() waits for space, and the wire drains one byte per 10 bit-times). A task prints a line of L bytes every 20 ms for two seconds. For 9600, 57600 and 115200 baud and L of 20, 40, 64, 100 and 200 bytes, report the longest single wait and the share of real time spent waiting.
Pins. A digital pin is a bit in DDRx, PORTx, PINx. A port toggle compiles to sbi/cbi (450 bytes of flash for the sketch); digitalWrite costs 734 bytes (+290), its specialised copy is 144 bytes and 66 instructions. No speed on a board was measured.
Pin table. Six PWM pins (3, 5, 6, 9, 10, 11), two interrupt pins (2, 3), pins 0 and 1 are USB serial, A4 and A5 are I2C. A constexpr table with static_assert makes a wrong pin a build error.
PWM. 976.56 Hz (Timer0, pins 5 and 6), 490.20 Hz (Timers 1 and 2). Prescaler 1 on Timer1 phase-correct gives 31,372.55 Hz. Timer0 also keeps millis(): do not change its prescaler. One duty step is 1.961 mm/s of 0.5 m/s; round (worst 0.980 mm/s), do not truncate (worst 1.941, always low).
ADC. 4.888 mV a count; 104 us a reading (9615 a second). Averaging 64 readings cut an assumed 1.5-count noise to 0.93 mV in 6.66 ms; it needs noise to work. Integer conversion vs float: 1118 vs 1818 bytes of flash.
Echo.pulseIn blocks for the whole echo (5.84 ms at 1 m, 20.42 ms at 3.5 m, its timeout with nothing there). The state machine polled every 100 us has a worst error of 17.0 mm (fake sensor).
Buses. 115200 baud is +2.12 % in double-speed mode (the core’s choice). A 40-character line is 3.47 ms at 115200 and 41.67 ms at 9600. 14 bytes over I2C: 1460 us at 100 kHz, 365 us at 400 kHz. Libraries: Serial +179 B RAM, Wire +216 B RAM (+2432 B flash), SPI +1 B RAM.
IMU. The chip starts asleep (all zeros, temperature 36.53 °C); check WHO_AM_I; bytes are signed; the scale follows the range. Tested against a fake chip only.
Budget.robot_ch2.ino: 9606 bytes flash (29 %), 936 bytes RAM (45 %), 1112 bytes available to the stack.
Challenges. Echo under 10 mm needs polling every 58 us or faster (9.8 mm), 60 us gives 10.1; averaging to 1 mV needs 8, 64 or 512 readings for noise of 0.3, 1.5 and 4.0 counts (0.83, 6.66, 53.25 ms); at 9600 baud a 40-byte line every 20 ms makes print() wait 21.67 ms each time.
Not run: anything on a board. Chip facts come from my memory of the datasheets; check them.
Next: Programming for Robotics with Arduino C++ 3, A Simulator to Test In
Programming for Robotics with Arduino C++ 3 (planned; not yet written) builds the thing that has been standing in for the world all along: a small C++ simulator of a two-wheel robot on the PC, with noisy range sensors and encoders, behind the same hardware interface as PinHW, so that the robot code in this chapter can be compiled for the board and for the host and run against the same recorded worlds.