A sensor reading is only useful if it has the right units and the right time. A 12 ms delay turns a swinging arm into a 3.6 degree error. Bring a part up so both are true.
Learn how a new sensor or motor joins a robot: the wire it talks on, the driver that reads it, the clock that stamps it, the loop that drives it, and the limits that keep it safe.
Switch between Arrival stamp and Sensor stamp, then drag the bus delay. Watch the brain’s picture of the arm fall behind the truth. Then we build, piece by piece, the whole path from a chip’s pins to a robot that listens, speaks and moves.
You need a little programming sense and the idea of a sine wave (a smooth back-and-forth). We build the rest from zero.
This lesson is built from primary sources, not slides: the NXP I2C specification, the Linux kernel timestamping guide, the ros2_control documentation and standard references on SPI, CAN, USB, EtherCAT, PTP, brushless motors and integral windup. The full list, with links, is in the Field Guide. Every idea is taught in our own words and devices.
Toy arm: it swings 40 degrees either side of centre at 1.2 swings per second, so its peak speed is 301 degrees per second. The delay values are illustrative; Chapter 4 shows how to measure real ones.
Chapter 0
Follow a single sensor reading from the chip to the robot’s brain and see why bring-up is about bytes, time and limits
Imagine a small robot head on your desk. It listens through a microphone array, speaks through a speaker and turns toward you with a neck motor. Today you add one part: a new motion sensor, a chip the size of a grain of rice, for the neck.
You solder it on, power the board and run the demo. The neck jerks, then shakes, then drifts to one side. The chip works. The code compiles. Still the robot is wrong. This chapter shows where such failures hide.
A sensor reading does not jump from the chip into your program. It crosses five hops, and each hop can damage it. The word for this whole job is integration: making a new part a trusted member of the robot.
Hop one is the sensor itself. It measures something physical, such as how fast the head turns, and turns that into a number inside the chip. Hop two is the bus: the wires and the rules that carry the number to the computer. Think of a bus as a postal route. The number is the letter, and the rules say who may post and when.
Hop three is the driver, the small program that reads the bus and hands the bytes to the rest of the software. Hop four is the time stamp: the label that says when the number was true. Hop five is the robot state, a clean value with a unit, such as “neck turning at 0.8 radians per second, measured at 10.0421 seconds”. The brain only ever sees that last form.
The same path runs backward for a motor. The brain writes a command. A control loop turns it into a current. A driver chip turns the current into power on the wires. A safety layer sits in front and can say no.
Each hop has its own failure, and each has its own symptom. A wrong unit makes the neck jerk, because a number ten times too big drives a motor ten times too hard. A stale time stamp makes the neck shake, because the brain corrects an old error and overshoots. A control loop that is too slow also shakes it. A missing limit lets one bad command break a gear.
The rest of this lesson takes the hops in order. Chapters 1 and 2 cover the bus. Chapter 3 covers the driver and the units. Chapters 4 and 5 cover time and fusion. Chapters 6 to 8 cover the motor, the control loop and the limits. Chapter 9 puts the loop together.
Start with the cheapest damage to measure: age. A reading is born at the sensor and gets older at every hop. The age of a reading is the time between the moment it was true and the moment the brain uses it. Age is what the hero at the top of this page was showing.
The device below follows one reading through five hops. Switch the driver between two ways of reading the bus. In polling the driver checks the chip on a timer, like checking your mailbox every ten minutes. In an interrupt the chip raises a signal the moment a reading is ready, like a doorbell. Slide along the path and watch the age grow.
Each block is one hop and its width is its delay. Drag the slider to move the reading along the path. Then switch the driver between polling and interrupt.
Illustrative delays: sensor filter 0.5 ms, bus transfer 0.4 ms (14 bytes at 400 kHz I2C, worked out in Chapter 1), driver 5.0 ms on average when it polls at 100 Hz (half of the 10 ms timer period) or 0.1 ms on an interrupt, software queue 1.0 ms, brain 0.5 ms. Your robot’s numbers will differ; Chapter 4 shows how to measure them.
With polling the reading arrives at the brain about 7.4 ms old. With the interrupt it is about 2.5 ms old. The chip, the wires and the brain did not change. Only the driver changed, and it cut the age by two thirds.
Notice where the time goes. The wire itself is the shortest block. The waiting is the longest. Most integration trouble is waiting, not transferring. This is why we spend a whole chapter on time.
A reading must be correct in two ways. It must have the right value: the right unit, the right axis, the right byte order. And it must have the right time: a stamp that says when it was true. A reading with a perfect value and a wrong time is as bad as the reverse. The hero showed it: a correct angle that is 12 ms late is wrong by 3.6 degrees.
A motor has a third need. A command must be safe, not only correct and timely. A command to spin a joint at ten times its safe speed is a valid number and a disaster. That is why limits get their own chapter.
Chapter 1
Count how long a reading takes to cross I2C and SPI, and learn why a bus can be too busy for its sensors
You have a board with a microcontroller and four sensors: two motion chips, a temperature chip and a magnet sensor in the neck joint. Each one needs a way to send readings to the controller. You have only a few pins and no room for a cable per chip. So the chips share wires.
A shared set of wires, plus the rules for using them, is a bus. Two buses dominate the inside of a robot board. They are I2C and SPI. They solve the same problem in opposite ways, and the difference decides which one you use.
I2C (say “I squared C”) uses two wires. SCL is the clock: a line that ticks, and one bit moves on each tick. SDA carries the data bits. Every chip on the bus connects to both wires, like houses on one street.
Many chips on one pair of wires needs a rule for who talks. I2C gives every chip a 7-bit address, a number from 0 to 127, set partly by the chip’s maker. One chip, the controller, starts every conversation. It sends the address it wants. Only the chip with that address answers.
The conversation has a fixed shape. The controller pulls SDA low while SCL is high. That is a START. It sends the address and one bit that says read or write. The chip pulls SDA low on the ninth tick to say “I am here”. That is an ACK, short for acknowledge. Then bytes follow, each followed by an ACK. The controller ends with a STOP: SDA goes high while SCL is high.
Each byte therefore costs nine clock ticks: eight data bits and one ACK. Remember that number. It sets the speed.
Chips on an I2C bus can only pull a wire low. They never push it high. A pull-up resistor connects each wire to the supply voltage and pulls it high when no chip is pulling it low. This design is called open-drain. It is what lets many chips share a wire without two of them fighting.
The resistor and the wire’s own capacitance form a slow ramp. Capacitance is the wire’s habit of soaking up charge, like a sponge that fills before the water level rises. A bigger resistor or a longer wire makes the rise slower. The NXP I2C specification limits the rise time to 1000 ns at 100 kHz, 300 ns at 400 kHz and 120 ns at 1 MHz, with at most 400 pF on the bus in the first two modes (check the specification table for the 1 MHz mode). The specification gives the largest allowed resistor:
300 ns / (0.8473 × 100 pF) = 3,541 Ω (the largest pull-up for a 100 pF bus at 400 kHz)
A common value of 4.7 kilohms is too big for that bus. You would see slow, rounded edges and corrupted bytes. A 2.2 kilohm resistor works. The lower limit comes from the other side: the resistor must be large enough that a chip can still pull the wire low.
SPI takes the opposite design. It has a clock wire (SCLK), a data wire from the controller (MOSI), a data wire back (MISO) and one chip select wire (CS) per chip. The controller pulls one chip’s CS low. That chip, and only that chip, listens and answers. There are no addresses, because the wire itself picks the chip.
Data moves both ways on every tick, so a read costs no more clocks than the bytes themselves. There is no ACK. The controller cannot tell whether a chip is plugged in or asleep. The SPI standard sets no top clock speed, so each chip’s datasheet and your wiring set the limit. Parts commonly run at 10 MHz and more.
SPI also has four modes, named by two settings. CPOL says whether the clock idles low or high. CPHA says on which clock edge the chip samples the data. If the controller and the chip disagree, every byte arrives shifted by a bit. Reading a chip’s datasheet for its mode is the first SPI bring-up step.
Take a typical motion chip. One burst read returns 14 bytes: three accelerometer axes, a temperature and three gyroscope axes, two bytes each. On I2C the controller sends the chip address, a register number and a restart with the address again, then reads 14 bytes. That is 17 bytes at 9 ticks each, 153 ticks, plus about 3 for START, restart and STOP.
(9 × 17 + 3) / 400,000 Hz = 156 / 400,000 = 0.39 ms (I2C at 400 kHz)
The same read on SPI sends one command byte and clocks in 14 bytes: 15 bytes of 8 ticks, so 120 ticks. At 10 MHz that is 12 microseconds. SPI is about 30 times quicker here, because it pays for no addresses, no ACKs and a faster clock.
Now the trap. Six such chips on one 400 kHz I2C bus, each read 1,000 times a second, need 6 × 0.39 ms = 2.34 ms of bus time in every 1 ms. The bus is asked for 234% of its time. It cannot keep up, so samples are late or dropped. The device lets you find that edge.
Each block is one 14-byte burst read of one chip. The row is one sample period. Choose a bus, add chips, raise the sample rate. Blocks that spill past the end mean the bus is overloaded.
Computed from the bit counts above for a 14-byte burst: I2C is 9 ticks per byte over 17 bytes plus about 3 for START, restart and STOP; SPI is 15 bytes of 8 ticks. Clock speeds are the I2C modes in NXP UM10204 and a common SPI clock. Real buses add small gaps between transfers, so real loads are a little higher.
Two ways out exist. Lower the load: read fewer bytes, or read at a lower rate. Or split the load: put half the chips on a second bus. Many motion chips also have a small FIFO, a queue inside the chip that stores readings. You read the queue in one longer burst, so you pay the overhead once for many samples.
The deeper lesson is that a bus has a budget. Before you add a chip, work out its transfer time and add it to the others. That is a ten-minute sum, and it prevents a week of mystery dropouts.
Chapter 2
Compare CAN, USB and EtherCAT by who is allowed to speak, how far they reach and how steady their timing is
The neck sensor is on the head board. The motors for the shoulders are a metre away, behind a spinning joint, next to a switching power supply that crackles with electrical noise. I2C and SPI were made for centimetres of clean copper. Here they fail. You need a different kind of bus.
Three buses cover most of what a speaking, listening, moving robot needs. CAN links motor drives and sensors across the body. USB links cameras, microphone arrays and the computer. EtherCAT links many joints that must move in step. Each answers one question differently: who may talk, and when?
CAN uses two twisted wires, called CANH and CANL. A bit is the difference between them, not the level on either. When noise hits both wires equally, the difference stays the same. This is a differential signal, and it is why CAN survives next to motors. A 120 ohm resistor sits at each end of the cable. It stops the signal from bouncing back like an echo.
CAN has no controller. Every node can start a message at any time. A message has an identifier (ID): an 11-bit number that says what the message is, such as “left elbow current”. It does not say who it is for. Every node hears every message and keeps the ones it cares about.
If two nodes start together, CAN settles it bit by bit, in a step called arbitration. A 0 bit is dominant: it wins over a 1 on the wire. A 1 bit is recessive. Each node sends its ID from the top bit down and listens at the same time. If a node sends a 1 but hears a 0, another node has a lower ID. It stops at once and waits. No data is lost and no time is wasted. The lowest ID always goes first.
So an ID is also a priority. You give the emergency stop a tiny number and the temperature report a big one. The device below lets you set three IDs and watch the contest.
Three nodes send their 11-bit IDs at the same moment. The bottom row is the wire: a 0 on any node pulls it to 0. A node that sends 1 and sees 0 drops out. Drag the IDs.
The rule is the CAN arbitration rule: dominant 0 beats recessive 1 on the wire, so the lowest ID wins. The 111 bit frame length is computed from the classical frame layout (47 bits of start, ID, control, CRC, ACK, end and gap, plus 64 data bits) before bit stuffing, at 1 Mbit/s. Two nodes with the same ID would collide; real systems never allow that.
Classical CAN carries up to 8 data bytes per message, and runs up to 1 Mbit/s on a cable shorter than 40 metres. Longer cable needs a slower rate: 125 kbit/s reaches about 500 metres. CAN FD raises the payload to 64 bytes and the data rate to several megabits a second.
Count the cost. An 8-byte message holds 111 bits before stuffing, so at 1 Mbit/s it holds the wire for 111 microseconds. The bus carries at most about 9,000 such messages a second. Ten motor drives that each report every millisecond use 10 × 111 µs = 1.1 ms in every 1 ms. That bus is overloaded, exactly as in Chapter 1.
USB works the other way round. No device may send anything unless the host computer asks first. The host walks the bus and polls each device in turn. This is why USB is simple to plug in and easy to scale, and why it is not strictly timed.
USB gives four kinds of transfer. Control carries setup commands. Bulk carries big, patient data, such as a file. Interrupt carries small data that needs a regular check. Isochronous carries a stream with a steady rhythm and no resends, such as audio from a microphone array. At full speed (12 Mbit/s) the host marks a start of frame once per millisecond, and the audio rides on that beat.
USB fits cameras, microphone arrays and speakers well. The cost is that the host operating system schedules the polls, so the timing wobbles by a millisecond or more. For a motor current loop that is too loose. For a camera frame it is fine, as long as the frame is stamped (Chapter 4).
EtherCAT keeps a master and many slave devices, but it changes how the data travels. The master sends one frame down the line. Each slave reads its own bytes and writes its reply into the same frame as it passes through. A slave does not wait for the whole frame. It works on the fly. The frame loops back to the master with every reply inside.
Think of a mail cart that rolls past every desk. Each person drops in a letter and picks one up without the cart stopping. One trip serves the whole office. EtherCAT runs on ordinary 100 Mbit/s Ethernet cable and reaches cycle times of 100 microseconds or less, with up to 65,535 nodes on one segment.
It also has distributed clocks: every slave sets its clock to a shared reference, so all joints can act at the same instant. The standard targets under 1 microsecond of jitter between slaves. Chapter 4 shows the idea behind that.
A worked example. Ten joints each send 8 bytes of state and receive 8 bytes of command: 160 bytes of payload. At 100 Mbit/s that is 160 × 8 / 100,000,000 = 12.8 microseconds on the wire, plus headers and a short delay per slave. A 1 kHz loop fits with room to spare, where the CAN bus above did not.
Use the question each bus answers. Need cheap, rugged links to a few drives or sensors, with priorities? CAN. Need a camera, a microphone array or a speaker, and the host can wait a millisecond? USB. Need many joints tightly timed with a common clock? EtherCAT. Many robots use all three, side by side.
Chapter 3
Turn 14 raw bytes from a chip into a value in metres per second squared, and learn the three ways it goes wrong
The bus now works. Your code sends a read and gets back fourteen bytes: 40 00 00 1C FF F0 0B 8A .... They are not yet an acceleration. They are not even numbers yet. They are a packed box of bits, and you must know the chip’s private labelling to open it.
The program that does this opening is the driver. A driver has one job: hide the chip’s private language and offer the rest of the robot a plain, honest value. “Acceleration on the x axis, in metres per second squared, taken at this time.” Everything above the driver should never see a register again.
Every driver follows the same script, taken from the chip’s datasheet, the manual that lists its registers. A register is a numbered byte of memory inside the chip, such as a switch or a result slot.
Step 1 alone prevents hours of grief. A chip that returns the right identity proves that power, wiring, address, bus speed and byte framing all work. Always read the identity first.
The chip’s converter turns a physical quantity into an integer called counts. A 16-bit converter has 65,536 possible counts. For a signed value the chip uses two’s complement: counts run from −32,768 to 32,767, and the top bit marks a negative number. A count of zero means zero acceleration.
To get a real value you multiply by a scale. The datasheet gives it as sensitivity, counts per unit. Take a chip whose range is set to ±2 g (g is the pull of gravity). It spreads its 65,536 counts over 4 g, so 16,384 counts mean 1 g.
0x4000 = 16,384 counts ÷ 16,384 = 1.000 g × 9.80665 = 9.81 m/s² (a chip with one axis pointing straight up)
The first is byte order. A 16-bit count sits in two bytes. Big-endian sends the high byte first. Little-endian sends the low byte first. Chips differ. If you assume the wrong order, the bytes 40 00 become 0x0040, which is 64 counts, not 16,384. The reading is 0.004 g instead of 1 g. The robot thinks it is in free fall.
The second is sign. If you read the two bytes as an unsigned number, a small negative value such as −16 (bytes FF F0) becomes 65,520. A tiny wiggle below zero turns into a huge positive jump. This is the classic cause of an arm that snaps to full speed when a joint crosses zero.
The third is range. You set ±8 g in step 3 but use the ±2 g scale in step 5. Every value comes out four times too small. Nothing crashes. The robot just feels four times less force than it really does, so a controller pushes four times too hard to fix it.
The device shows all three. Set the true reading with the slider. The top row is what the chip put on the wire. The bottom row is what your driver decided. Break the driver, one setting at a time.
The chip measures the true acceleration and sends two bytes, high byte first. Your driver rebuilds the number. Turn on a mistake and see how wrong the robot’s value becomes. Set a negative value to see the unsigned mistake.
Illustrative chip: 16-bit signed counts, sensitivity 16,384 counts per g at ±2 g and half that each time the range doubles, which is the common layout for MEMS accelerometers. The true value is clipped to the chip’s range, because a real converter saturates.
Notice that the three mistakes look different from the outside. A swap gives a value near zero. A sign mistake gives a giant jump at zero. A range mistake gives a clean but scaled copy. Learn the three symptoms and you can name a decode bug in a minute from a plot.
Even a correct decode is not yet a good value. A real chip has a bias: it reads a little above or below zero when still. You find it by holding the chip still, averaging a few hundred readings and subtracting that average. This is the b in the equation. It changes with temperature, so good drivers store it per unit.
The chip also has its own idea of x, y and z, printed as a dot on its package. You might solder it sideways. The driver multiplies the three values by a fixed rotation matrix (a small table of numbers that turns one set of axes into another) so that every sensor reports in one shared robot frame. Get this wrong and the neck turns the wrong way. The sensors lesson from AA274A and the calibration lesson go deeper.
FF F0 as an unsigned number. The joint angle sensor crosses zero going slightly negative. What does the robot see?Chapter 4
Stamp every reading at the moment it was true, and make two clocks agree by timing a round trip
The robot hears you say its name. The microphone array records the sound. The camera sees your face turn. The neck sensor feels the head move. Three streams arrive at the brain within a few milliseconds of each other. Which one happened first?
The brain cannot answer by looking at when each stream arrived. Arrival order depends on the bus, the driver and a busy operating system. It can answer only if each reading carries a label of its own: the time it was true. That label is the time stamp. This chapter is about getting that label right.
A software time stamp is taken by code. The driver wakes up, reads the clock and writes the time next to the data. It is easy and needs no special parts. But the code runs after the event. Between the event and the clock read sit the bus transfer, an interrupt, and the scheduler that decides which program runs next. That gap is not fixed. It changes from one reading to the next. The change is called jitter.
A hardware time stamp is taken by a circuit at the instant of the event. A network card can latch its clock, meaning copy it into a register, the moment a packet crosses its pins. A camera chip can latch it at the middle of its exposure. A motor drive can latch it at its control tick. No software sits in between, so the jitter is tiny.
The Linux kernel offers both for network packets. The flag SOF_TIMESTAMPING_RX_SOFTWARE asks for a stamp taken just after the driver hands the packet to the kernel. The flag SOF_TIMESTAMPING_RX_HARDWARE asks for a stamp made by the network adapter itself, from its own clock, which the kernel exposes as a PTP hardware clock. The kernel guide explains that the hardware stamp is reported separately so that you can tell the two apart.
The rule for the robot is short. Stamp as close to the physics as you can. If a part can stamp in hardware, use that stamp. If it cannot, stamp in the interrupt handler, not later in a queue. And never trust the time a message arrived as the time it was true. That is exactly what the hero at the top of the page showed.
Stamping at the source creates a new problem. The sensor board has its own clock. The computer has another. Two clocks differ in two ways. They show different times, an offset. And they tick at slightly different speeds, a drift. A typical quartz crystal is accurate to some tens of parts per million. A drift of 20 parts per million moves a clock by 20 microseconds every second, or 1.2 milliseconds every minute. After ten minutes two clocks that started equal are 12 ms apart.
So a stamp from the sensor board is a time on the board’s clock. To compare it with the camera you must convert it to one shared clock. The job is clock synchronisation. The standard method, used by PTP (the Precision Time Protocol, IEEE 1588) and, in spirit, by EtherCAT’s distributed clocks, is to time a round trip.
Picture two people with watches that disagree. Anna stands at one end of a corridor and Ben at the other. Anna shouts “now!” and notes her watch: t1. Ben hears it and notes his watch: t2. Ben shouts back and notes his watch: t3. Anna hears it and notes her watch: t4. Four numbers, two watches.
The time from Anna to Ben, read as t2 minus t1, equals the true delay plus Ben’s offset. The time from Ben to Anna, read as t4 minus t3, equals the true delay minus Ben’s offset. Subtract the two and the delay cancels. Add them and the offset cancels.
(5 + 1) − (1 − 5) = 6 − (−4) = 10; ½ × 10 = 5 ms (a 5 ms offset with 1 ms of delay each way)
Look at the catch. The method assumes the delay is the same in both directions. If the way out takes 1.0 ms and the way back takes 3.0 ms, the formula still halves the difference, and the answer is wrong by half the difference: 1.0 ms. The error from an unequal path is the main limit of the method. Hardware stamps shrink the other source of error, the jitter in each t.
Run it yourself. Set the true offset and the two delays. Then choose how the four stamps are made. Press Run an exchange several times and see how much the answer wobbles.
The leader clock is on the left, the follower on the right. Four stamps give an offset estimate. Make the path lopsided to see the asymmetry error. Switch to software stamps to add jitter.
The formulas are the standard two-way time transfer used by PTP. The jitter sizes are illustrative, not measurements: 1 microsecond for a hardware latch and 0.3 ms for a software read on a busy system. The follower waits 2 ms between receiving and replying.
Two lessons come out of the device. With hardware stamps and equal delays, the estimate is almost exact. With software stamps, each exchange is off by a random few tenths of a millisecond, and you must average many exchanges and filter the result. With unequal delays, no amount of averaging helps, because the bias is built in.
A working robot runs a sync service in the background. It sends exchanges every second or so, estimates both the offset and the drift, and steers each clock slowly instead of jumping it. A jump backward would make time run in reverse for some code. Then every sensor driver stamps with the shared clock, or with its own clock plus a known conversion. The sensor fusion lesson on time sync goes further into estimating the offset.
Two special cases show up on a speaking robot. The audio converter has a sample counter that ticks at 48,000 samples a second, and a sample number is a very good clock for sound. You still need to map it once to the shared clock. A camera exposes for some milliseconds, so stamp the middle of the exposure, not the start and not the readout.
Chapter 5
Line up sensors that run at different rates and arrive at different delays, so the filter sees one consistent past
The robot turns its head to follow you. To know where its head points, it uses two sensors. The motion chip reports turn rate 200 times a second and is almost instant. The camera reports a picture 30 times a second, and each picture arrives about 40 ms after it was taken, because the image must be read out, compressed and sent.
The two sensors disagree in rate and in delay. Yet one filter must combine them into one estimate of where the head points. Putting sensors together like this is sensor fusion. The fusion filter itself, often a Kalman filter, is the subject of its own lesson. This chapter covers what you must give it.
A fusion filter wants four things with every measurement. First, the value, in standard units (metres, radians, seconds), in a known frame (Chapter 3). Second, the time stamp of when it was true (Chapter 4). Third, the uncertainty: a number that says how much to trust it. Fourth, which sensor it came from, so the filter applies the right model.
Uncertainty is the part that is easy to forget. A filter is a weighted average at heart. It trusts a quiet sensor more than a noisy one. If you tell it that the camera and the gyro are equally good, it will blend them as equals, and the result will be worse than either alone. The datasheet gives a noise figure for each chip. You can also measure it: hold the sensor still for a minute and compute the spread of its readings.
A filter works in two moves. In predict, it moves its estimate forward in time using a model, such as “the head keeps turning at the last rate”. In update, it pulls the estimate toward a new measurement. The fast sensor gives many small updates. The slow sensor gives few big ones.
Predict and update need the time of each measurement. The filter predicts exactly to the stamp, and then updates. If the stamp is wrong, the filter updates at the wrong moment, and the estimate is pulled toward a stale truth.
The camera frame arrives 40 ms late. Its stamp says it was exposed at 123.4 ms. But at arrival, the filter may already have processed gyro readings up to 163 ms. There are two honest ways to handle this.
The first way is interpolation. Keep a short buffer of the fast sensor. When the slow measurement arrives, look up the fast sensor’s value at the slow stamp. Two fast samples bracket the stamp. Blend them by how close the stamp is to each:
α = (123.4 − 120) / (125 − 120) = 0.68; x = 0.32 × 0.50 + 0.68 × 0.60 = 0.568 rad/s (gyro samples 0.50 and 0.60 rad/s at 120 and 125 ms)
The second way is rollback and replay. The filter keeps a short history of its own states. When a late measurement arrives, it rewinds to the stamp, applies the measurement, and replays every fast reading since. It is more work and gives the exact answer. Many robots do this for the camera, and use interpolation for simpler cases.
Both ways depend on one habit: stamp at the source (Chapter 4), then buffer and sort by stamp, not by arrival. Run the device to see what a wrong stamp costs.
The curve is the true turn rate. Ticks are 200 Hz gyro samples. The camera took a picture at the green mark and it arrives later. Choose which stamp pairs the frame with the gyro.
Illustrative signal: turn rate 0.5 + 0.5 sin(2π × 2 Hz × t) rad/s, sampled at 200 Hz, with linear interpolation between neighbours. The 40 ms delay is a typical order of size for a compressed camera stream, not a measurement of one camera.
With the exposure stamp, the pair is nearly perfect, off by the tiny error that straight-line interpolation makes between two samples 5 ms apart. With the arrival stamp, the filter pairs the frame with a gyro value from 40 ms later, when the head was turning at a different rate. The error is large. It grows with the delay and with how fast the signal changes.
Rule 3 is worth a second look. A stamp from the future means the sensor clock is ahead of the shared clock. A very old stamp means a queue is backed up. Both are bugs you want to see in a log, not hide inside a smooth estimate. The Kalman filter lesson and time sync and calibration show how to estimate such offsets inside the filter.
Chapter 6
Learn how a voltage becomes torque, how PWM sets the voltage, and why a stalled motor draws a dangerous current
The neck needs to turn. Your code says “speed 2 radians per second”. A computer pin cannot move a neck. It can switch a tiny current on and off. Between that pin and the neck sit a motor that makes the torque and a motor driver that makes the power.
This chapter follows the command downhill: from a number to a voltage, from a voltage to a current, from a current to a twist.
Start with a brushed DC motor, the simplest kind. Current through its coil makes a magnetic force, and the force turns the shaft. The twist, called torque, is proportional to the current:
The second equation hides the most important idea in motors. A spinning motor is also a generator. As it speeds up, it produces a voltage that pushes against the supply. That voltage is the back-EMF (EMF means electromotive force, a voltage). At the speed where the back-EMF equals the supply, no net voltage is left, no current flows and the motor stops speeding up. That is the no-load speed.
Now see the danger. When the shaft is held still, ω is zero and the back-EMF is zero. All the supply voltage falls on the small resistance R. The current is V divided by R, which can be huge. This is the stall current. A joint pushing against a wall, or a gear that jams, draws it.
A computer cannot output 7.3 volts. A driver switches the full supply, say 24 V, fully on or fully off, very fast. The fraction of time it is on is the duty cycle. The motor coil smooths the pulses, so the motor sees the average. 50% duty gives 12 V. This is pulse width modulation, PWM. It wastes almost no energy in the driver, because a switch that is fully on or fully off dissipates little.
PWM frequency matters for a robot that must be heard. At a few kilohertz the coil hums at that pitch, and a microphone nearby picks up a whine. Drivers on quiet robots often switch at 20 kHz or higher, above human hearing. Chapter 7 returns to this, because the control loop can run at the PWM rate.
To turn the motor both ways you need to flip the current. The classic circuit is the H-bridge: four switches arranged like the letter H, with the motor as the crossbar. Close the top left and the bottom right switches, and current flows one way. Close the other pair, and it flows the other way. Closing both switches on one side at once is a short circuit, called shoot-through, so driver chips insert a small dead time between switching one off and the other on.
A brushed motor has contacts, called brushes, that flip the coil current as the shaft turns. They wear out, spark and add electrical noise. A brushless DC motor (BLDC) removes them. The magnets spin and the coils stay fixed, and an electronic controller flips the current in three phases at the right moments. To know the moments, it needs the rotor position, from Hall sensors (small chips that sense the rotor magnets), from an encoder (a disc that counts shaft turns), or from the back-EMF in the undriven coil (a sensorless design).
The cost is more complex electronics. The gain is higher efficiency, longer life and no brush noise. A brushless motor can also hold torque at zero speed. Many robot joints use them, often behind a gearbox. The best known control method for them is field-oriented control (FOC): the drive measures the phase currents, rotates them into a frame that turns with the rotor, and controls the part that makes torque. You do not need to build this to integrate a joint. You do need to know that the drive has an inner current loop inside it, because Chapter 7 builds on it.
Take a 24 V supply and a brushed motor with R = 0.5 ohm and Kt = Ke = 0.05 (a toy motor). At 50% duty the motor sees 12 V. With no load, the current is near zero, so the speed is 12 / 0.05 = 240 rad/s, about 2,290 rpm. Add a load of 0.25 N·m. The current rises to 0.25 / 0.05 = 5 A, which drops 2.5 V across R. The speed falls to (12 − 2.5) / 0.05 = 190 rad/s. Stall at 100% duty draws 24 / 0.5 = 48 A and produces 2.4 N·m, with 48 × 48 × 0.5 = 1,152 W of heat in the coil.
Try it. The device draws the PWM waveform and the operating point. Raise the load until the motor stalls.
The top trace is the 24 V PWM the driver makes. The bars show speed, current and coil heat. Drag the duty up, then drag the load up until the motor stalls.
Toy motor, illustrative numbers: 24 V supply, 0.5 ohm coil, Kt = Ke = 0.05, so stall is 48 A and 2.4 N·m. The model is the two equations above with a steady-state balance; it ignores inductance, friction and the driver’s own current limit.
Two things stand out. At any duty, adding load pulls the speed down and the current up. And once the load passes the stall torque for that duty, the shaft stops, the current is V divided by R, and the heat climbs steeply because heat grows with the square of the current. A joint left in that state for a few seconds can burn its coil.
That is why every real driver has a current limit, and why Chapter 8 makes limits a first-class part of the design. The limit is not a luxury. It is the thing that lets you test a new controller without a smoking motor.
Chapter 7
Build a PID controller from three simple urges, see integral windup, and stack fast loops inside slow ones
The brain says: turn the neck to 1 radian. The motor does not know what a radian is. It knows current. Between “go to 1 radian” and “send 3 amps” sits a control loop: a small program that measures where the neck is, compares that with where it should be, and picks a current. It repeats this a thousand times a second.
The distance still to go is the error: target minus measurement. A PID controller turns the error into a command with three urges, added together.
The P term is a spring. It pushes in proportion to the error. Far from the target, push hard. Close, push gently. The I term is patience running out. It adds up the error over time, so a small error that never goes away eventually gets a big push. It removes the leftover error that P alone leaves when something, such as gravity, pushes back. The D term is a brake. It reacts to how fast the error changes, and pushes against fast motion, which calms the overshoot.
Three lines of code do it. Each cycle you read the angle, compute the error, update the sum, and write the command. Tuning means choosing three numbers. Raise Kp until the response is quick but starts to ring, add Kd to calm it, and add a little Ki last to kill the leftover error.
Real motors have limits. The driver may allow only 10 A. Suppose the neck must move a long way. The error is large, the P term asks for 60 A, the driver clips it to 10 A, and the neck accelerates as fast as it can. Meanwhile the I term keeps adding up the big error, because the neck has not arrived. When the neck finally arrives, the I sum is huge. It keeps pushing, and the neck sails past the target. Only after it overshoots does the error change sign and unwind the sum.
This failure is integral windup. The symptom is a big overshoot after a large move, where a small move is fine. You measure it by plotting the I term: it climbs while the command is clipped. Two standard fixes exist. Clamping stops the sum from growing while the command is clipped. Back-calculation pulls the sum back so that the unclipped command matches what the driver allowed. Both come down to one rule: do not wind the sum when the output cannot follow.
A single loop from angle to current has to be good at everything: stiff when still, gentle in a long move, safe against the current limit. A better design stacks loops, each doing one job. This is a cascaded control loop.
The outer loop watches the angle. It does not command current. It commands a speed: a bigger error means a faster requested speed, up to a speed limit. The middle loop watches the speed. It compares the requested speed with the measured speed and commands a current. The innermost loop, usually inside the motor driver, makes the actual current match that request.
Think of a driver steering a car to a parking space. You choose a target speed from the distance left. You press the pedal to hold that speed. The engine controller holds the throttle. Each layer asks the layer below for something simple.
Each inner loop must be faster than the loop around it, or the outer one chases a moving target. A common rule of thumb is five to ten times faster. In a joint drive the current loop often runs at 10 to 20 kHz, in step with the PWM of Chapter 6. The speed loop runs at a few kilohertz, and the angle loop at one kilohertz or at a few hundred hertz. So the whole stack runs at kilohertz rates, and the timing of Chapter 4 and the deadline of Chapter 9 both matter.
The cascade has another gift: limits live at the right layer. The speed limit sits between the outer and middle loops. The current limit sits at the inner loop. A long move becomes a smooth ramp, not a slam.
Compare them on the same neck. The device simulates a motor with inertia, friction and a 10 A limit, stepped 1 radian. Switch between one PID loop and the cascade. Turn the anti-windup off and on.
Top: the angle against the 1 radian target. Bottom: the motor current, with the 10 A limit as pink lines. Choose a loop, change the gain, and toggle the windup guard.
Simulated at 1 kHz: inertia 0.002 kg·m², friction 0.002, Kt 0.05, current limit ±10 A. Single loop: Kp 60, Ki 300, Kd 3.2 (times the gain scale). Cascade: angle P loop 12 with an 8 rad/s speed limit, speed PI loop K 1.2 and Ki 15, ideal current inside. Toy numbers, not a real joint. The guard stops the sum growing while the command is clipped.
With one loop and no guard, the neck overshoots by about a quarter of the move: the sum wound up while the command sat at the limit. With the guard, the overshoot drops. With the cascade, the speed limit means the command barely clips, so the neck glides in with almost no overshoot. The price of the cascade is more numbers to tune and more places to get a unit wrong.
Tune a cascade in the order of the layers. First check the current loop: command a small step and watch the measured current follow it. Then close the speed loop and tune it with the angle loop open. Only then close the angle loop. If you tune the outer loop first, you tune it against an inner loop that is still changing, and you will chase your own tail.
The AA274A lesson on tracking and the control lesson from VNAV build the maths of these loops. This chapter gave you the engineering shape.
Chapter 8
Stack clamps, edge slowdowns and a watchdog so that one bad command or one silent brain cannot hurt the robot
The robot head is running a new behaviour. A bug in the planner divides by zero and sends the neck a speed that is not a number. A second later it sends 400 radians per second. A third later it sends nothing at all, because the brain has crashed. What should the neck do?
The neck cannot judge the brain. It can only refuse. So every actuator needs layers of refusal between the brain and the motor. This chapter lists the layers, from the gentlest to the hardest.
Before anything else, validate. A value that is not a number (the broken result of a divide by zero), infinite, or outside any sane range is rejected, not clipped. A rejected command keeps the last good one for a short time, then triggers the safe state. Clipping a broken value would hide the bug. Rejecting it tells you about it.
Every joint has a speed limit, a torque or current limit and a position range. A clamp cuts any request to the allowed range: ask for 400 rad/s on a joint limited to 2 rad/s and you get 2. Set the limits from the mechanics and the motor, not from what the planner usually asks. The planner is the part most likely to be wrong.
Add a limit on how fast the command may change, the rate limit. A step from 0 to 2 rad/s in one millisecond is a violent jerk even if 2 rad/s is allowed. A ramp is gentler on gears and on the people nearby.
A neck that can turn ±1.2 radians has a hard stop at each end. Driving into it at full speed bangs the gear. So the allowed speed shrinks as the joint nears the end. Over the last 0.3 radian the limit falls in a straight line to zero. This is an edge slowdown, also called a soft limit. If the joint is already past the limit, only a command that moves it back is allowed.
Behind the soft limit sits a hard one: a switch or sensor at the real end that cuts the motor in hardware if the soft limit fails.
All the layers above assume the brain is still talking. What if it stops? A motor that keeps its last command turns at that speed forever. A watchdog is a timer in the low-level controller. Each valid command from the brain resets it. If the timer reaches its timeout, such as 50 ms, with no new command, the controller assumes the brain is dead and moves to the safe state.
The word for the brain’s periodic message is a heartbeat. The watchdog must live in the layer closest to the motor, in a different chip or at least a different program, so a crash in the brain cannot also crash the watchdog.
What is the safe state? It depends on the joint. For most joints it is torque off: the motor coasts. For a neck that holds up a heavy head, torque off drops the head, so the safe state may be to brake or to hold position. For a large arm near people, it is usually power cut with a mechanical brake. Decide the safe state for each joint on purpose, and write it down.
The last layer is the emergency stop: a physical button that opens a switch in the motor power line. It works even if every program is broken. Everything above it is polite. This one is final. A speaking, moving robot that works near people needs one that a person can reach in one second. Machines that can hurt people fall under safety standards. Check the rules for your product and market; this lesson covers the engineering of the layers, not certification.
The device passes one request through the layers of a neck joint. Move the joint toward an end and ask for more speed than allowed. Then stop the brain and watch the watchdog count.
Bars show the speed after each layer. Pink marks the layer that cut it. Move the neck angle, change the request, then press Brain goes silent.
Illustrative limits for a toy neck: speed ±2 rad/s, position range ±1.2 rad with the slowdown over the last 0.3 rad, watchdog timeout 50 ms. The silence timer is slowed 20 times so you can watch it; in reality 50 ms passes in the blink of an eye. Rate limiting is left out here for clarity.
Try the setting that started the chapter. At 1.1 radians with a request of 3 rad/s, the speed clamp cuts it to 2, and the edge slowdown cuts it again to 0.67, because the neck is only 0.1 radian from its end. Silence the brain and the final bar drops to zero when the timer reaches 50 ms. Three layers, each doing one small thing.
Write the limits first. Before you tune a loop, decide the speed, current, range, timeout and safe state, and put them in a configuration file in one place. Then test them: send a broken value, send a huge value, unplug the brain, and check that the joint ends in the safe state each time. A limit that was never triggered in a test is a limit you do not know works.
The driver’s own current limit from Chapter 6 is the same idea one layer lower. It protects the coil even if every software layer fails.
Chapter 9
Wrap every part in the same read, update, write cycle, and keep that cycle inside its time budget
The brain does not want to know that the neck sensor lives on an I2C bus at address 0x68, or that the shoulder drive speaks EtherCAT. It wants one simple picture: here are the joints, here is where each one is, here is what I can ask of it. All the work of the earlier chapters exists to make that picture honest.
This chapter shows the shape of the software that hides the hardware, and the rule that keeps it alive: a loop that must finish on time, every time.
A common design, used by the ros2_control framework, splits the hardware from the controllers. Hardware components are plug-ins with two methods: read() gets the latest values from the device, and write() sends the latest commands to it. A component is a sensor (read only), an actuator (one joint) or a system (many joints on one bus, such as an EtherCAT chain).
Each component exposes two lists. State interfaces are values the hardware reports, such as position and velocity. Command interfaces are values the hardware accepts, such as a target velocity. A controller is a plug-in that reads some state interfaces, compares them with a reference, and writes some command interfaces. A controller manager loads the controllers, switches them on and off, and refuses a combination where two controllers want the same command.
The point of the split: you can swap a motor, a bus or a controller by changing a configuration, and the rest does not change. That is also what makes a bring-up checklist possible. A new part is done when its component reads, writes and passes the tests.
The controller manager runs one cycle again and again. First it calls read() on the hardware: the newest state arrives, stamped. Then it calls update() on every active controller: the Chapter 7 loops run and compute commands. Then it calls write(): the commands go out, through the limits of Chapter 8, to the drives. The cycle repeats at a fixed rate, such as 1 kHz.
The order is the point. Read before update gives each controller the freshest state. Write after update gives the drives the freshest command. One slow step delays all the others.
The state that leaves the loop is not a bag of bytes. It is a record with a unit on every number and a stamp on the whole. Here is the neck, as the brain sees it after Chapters 1 to 8 have done their work.
Every field answers a question from an earlier chapter. The units answer Chapter 3. The stamp and age answer Chapter 4. The standard deviation feeds the fusion of Chapter 5. The command, the limits flag and the watchdog age come from Chapters 6 to 8. A brain that gets this record can plan. A brain that gets only a float cannot.
A control loop has a period: at 1 kHz, 1,000 microseconds. All three steps must finish inside it. The leftover time is the margin. If a cycle runs long, it misses its deadline: the commands go out late, and the next read comes late too. The loop is then not a loop of fixed rate. The velocity estimate, which divides a position change by the time step, becomes wrong. A control loop that misses deadlines can shake or run away.
The cost has two parts. The first is the steady work: bus read, controller math and bus write. The second is jitter: occasional extra delay from the operating system, such as another program using the processor, a delay while memory is fetched from disk, or an interrupt. Jitter is rare, which makes it dangerous. Your test passes a thousand times and fails on the thousand-and-first.
There are two defences. Keep the steady work small enough that the margin is large. And run the loop in a thread with a real-time scheduling policy, so that the operating system lets it pre-empt ordinary programs. Both are needed.
Use the device to feel the margin. Pick a rate, set the controller compute time and the size of the occasional jitter, and count the missed cycles in 400.
Top: the time budget of one cycle. Bottom: the length of 400 cycles, one bar each. A bar that crosses the pink line missed its deadline.
Illustrative: bus read 250 µs and bus write 250 µs per cycle, a jitter spike hits 2% of cycles and has a random size up to the slider value. Random numbers are seeded, so you see the same 400 cycles each time. Measure your own loop with a real clock; these values are not a benchmark.
At 1 kHz with 150 microseconds of compute, the steady work is 650 microseconds and the margin 350. A 300 microsecond spike never reaches the line. Push the spike to 500 and some cycles cross it. Move to 2 kHz and the period is 500 microseconds, shorter than the steady work. Every cycle misses, and no operating system can save a loop whose own work does not fit.
Chapter 10
Keep the numbers, a bring-up checklist and the core loop on one page, with every source linked
A part joins a robot through five hops and three kinds of correctness. The bus must have room (Chapters 1 and 2). The driver must turn bytes into true units (Chapter 3). Every reading must carry the time it was true (Chapters 4 and 5). The motor side must turn a command into torque within its limits (Chapters 6 to 8). And the whole thing must run inside a deadline and present one honest state to the brain (Chapter 9).
| Item | Value | Where it comes from |
|---|---|---|
| I2C speeds | 100 kHz, 400 kHz, 1 MHz; 400 pF at the first two speeds; rise time 1000, 300, 120 ns | NXP UM10204 |
| Largest I2C pull-up | R = tr / (0.8473 Cb); 3,541 Ω at 300 ns, 100 pF | NXP UM10204; worked here |
| 14-byte burst read | 0.39 ms on I2C 400 kHz; 12 µs on SPI 10 MHz | Counted here from bit counts |
| SPI | 4 wires, 1 chip select per chip, no ACK, 4 clock modes | SPI reference article |
| CAN | 8 data bytes, 11-bit ID, 120 Ω at each end, 1 Mbit/s under 40 m | CAN bus reference article |
| CAN frame time | 111 bits, 111 µs at 1 Mbit/s, before bit stuffing | Counted here from the frame layout |
| CAN FD | up to 64 data bytes | CAN bus reference article |
| USB | 12 Mbit/s full speed, 480 Mbit/s high speed; the host starts every transfer | USB reference article |
| EtherCAT | cycle 100 µs or less, clock jitter under 1 µs, 65,535 nodes, 100 Mbit/s | EtherCAT reference article |
| Clock offset | θ = ½ [ (t2 − t1) − (t4 − t3) ]; error is half the path asymmetry | PTP reference article |
| Clock drift | 20 ppm is 1.2 ms per minute | Arithmetic; 20 ppm is illustrative |
| Motor | τ = Kt I; V = I R + Ke ω; stall current V / R | Motor reference article; worked here |
| Windup fixes | clamping, back-calculation | Integral windup article |
| Loop rates | current 10 to 20 kHz, speed a few kHz, angle 1 kHz or less (rule of thumb) | Common practice; not a standard |
| Hardware stamp flag | SOF_TIMESTAMPING_RX_HARDWARE, with SOF_TIMESTAMPING_RAW_HARDWARE | Linux kernel timestamping guide |
| Control cycle | read(), then controller update(), then write() | ros2_control documentation |
This sketch is one joint from end to end. It is plain Python for reading, not a real-time driver. Each line is a choice from a chapter.
pythondef read_imu(bus, clock): raw = bus.read(0x68, reg=0x3B, n=14) # Ch 1: one burst, 0.39 ms at 400 kHz stamp = clock.now_from_sensor() # Ch 4: stamp at the interrupt, not later ax = int.from_bytes(raw[0:2], "big", signed=True) # Ch 3: order and sign a = (ax / SENS_G - BIAS_G) * 9.80665 # Ch 3: counts to m/s^2 return Reading(a, stamp, frame="base_link", var=VAR_A) # Ch 5: value, stamp, frame, noise def limit(v_req, pos, last_cmd_age_ms): if not math.isfinite(v_req): return 0.0 # Ch 8: reject, do not clip v = clamp(v_req, -VMAX, VMAX) room = (POS_MAX - pos) if v >= 0 else (pos + POS_MAX) v *= clamp(room / SLOW_ZONE, 0, 1) # Ch 8: edge slowdown return 0.0 if last_cmd_age_ms > 50 else v # Ch 8: watchdog to the safe state def cycle(hw, ctl, dt): s = hw.read() # Ch 9: freshest state w_ref = clamp(KP_ANGLE * (ctl.target - s.angle), -W_MAX, W_MAX) # Ch 7: angle loop ev = w_ref - s.speed raw = KP_SPEED * ev + KI_SPEED * ctl.i_sum # Ch 7: speed loop cur = clamp(raw, -I_MAX, I_MAX) if abs(raw) <= I_MAX: ctl.i_sum += ev * dt # Ch 7: windup guard hw.write(current=cur) # Ch 9: freshest command; driver runs the current loop
Read it line by line and name the chapter behind each choice. Only the units, the stamp and the limits make it safe to run on a real neck.
Integration is the layer between the physics and the clever parts. Above it sit fusion filters, planners and learned policies for a robot that speaks, listens and moves. Below it sit silicon and copper. A learned policy that sends actions at 20 Hz still needs this layer to turn each action into a smooth, limited, stamped motion at 1 kHz. A good integration layer makes a model look good. A bad one makes the best model shake.
No slides were used. This lesson was built from the following primary and reference sources, opened for this lesson. Figures for the I2C modes come from the NXP specification; we could not extract that PDF’s text automatically, so check the tables there before you design a board. For the exact part you use, the next stop is the vendor’s datasheet and application notes (for example from TI, Analog Devices, Infineon or Knowles).
Now press Present or Teach and explain one reading and one command out loud, from memory: the five hops, the stamp, the limits and the deadline. Then go back to the arm at the top and set the delay to 30 ms.