Time, Clocks and Sensor Alignment

A LiDAR scan stamped 12 ms after its capture puts every point where the robot will be, not where it was. At 3.4 m/s that is 40.8 mm per point, and a wall seen going out and coming back lands twice, 81.6 mm apart.

Drive the robot faster, then switch where the stamp comes from. The end walls split only when the robot moves. Then we build, piece by piece, clocks, stamps, sync, shutters, offset estimation, interpolation and the latency budget.

You need speed times time, a sine wave and a little Python. We build the rest from zero.

Lesson 2 of the Robotics Engineering track. Before: Lesson 1, Coordinate Frames. Next: Lesson 3, Uncertainty. Lesson 1 asked which frame a number is in. This lesson asks which instant.

Drive faster, watch the walls split

3.4 m/s

Illustrative room, 10 m by 6 m; LiDAR at 10 Hz, 120 beams, 5 mm range noise, seeded. The software maps each point with the pose at its stamp. The circle magnifies the right wall: 0.36 m across, 3 m tall; points seen while turning are faint.

Chapter 0

The Smear: Twelve Milliseconds at Delivery Pace

Fit the error against speed, and read a time out of the slope

A sidewalk robot maps well at walking pace. Above 2 m/s the walls go thick, then double, and half the loop closures fail. Nobody touched the estimator in six weeks.

The team logs one route at four speeds. The residual grows with speed: 14 mm at 0.8 m/s, 47 mm at 3.4 m/s. Divide error by speed and you get seconds, but the four ratios slide from 17.5 ms down to 13.8 ms. That slide is a clue, not noise.

Fit the line, do not divide

Four logged runs (blue dots). Switch between the ratio view and the line fit. Then drag the offset Δt and see the speed where its line crosses the yellow 50 mm budget.

12 ms

The four runs are the lesson's illustrative ticket. The fit is ordinary least squares; we checked it with numpy.

A ratio equals the slope only if the line runs through zero. This one does not. A fixed floor of a few millimetres, from calibration and feature noise, sits under every run, and dividing by a small speed inflates it most. So fit the line. The slope is 12.65 ms, the intercept 4.08 mm, and the residuals stay under a quarter millimetre.

Why does a time become a distance? Call the robot's speed v and the gap between when a sensor captured its data and the time written on it Δt (delta-t). The software places the data where the robot was at the wrong instant.

Say it aloud

e equals v times delta-t.

e
e the position error the timing adds to each measurement, in metres.
v
v the robot's speed, in metres per second.
Δt
delta-t the stamp minus the true capture instant, in seconds. Positive means the stamp is late.
In plain words

During the gap delta-t the robot keeps moving at speed v. Multiply the two: that distance, e, is how far off the software puts the data.

With numbers

Δt = 0.012 s. At v = 1.4 m/s, e = 16.8 mm: inside a 50 mm budget, so nobody files a bug. At v = 3.4 m/s, e = 40.8 mm, 82% of the budget from timing alone.

Turning is worse. The heading also moves during Δt, by the turn rate ω (omega) times Δt, and a wall at range r slides sideways by r times that angle. At 60°/s, 1.047 rad/s, the angle is 0.72°, and a wall 5 m away moves 62.8 mm.

Symptom: the map is crisp when slow and doubles when fast; the estimator code has not changed.

Measure: log one route at three or more speeds and fit error against speed. A slope in seconds is a timing bug; the intercept in metres is a geometry bug.

Fix: find where Δt comes from (the next five chapters) and remove it, or measure it and subtract it (Chapter 5).

The road

  1. Clocks: offset, drift in ppm, and jitter.
  2. Stamp site: capture time, not arrival time.
  3. Sync: NTP, PTP and the trigger wire.
  4. Shutter: exposure and the rolling shutter.
  5. Find the offset: cross-correlate gyro and camera.
  6. Interpolate: a pose between two samples.
  7. Buffers: pairing messages and the latency budget.
  8. Showcase: the alignment bench and its speed limit.
  9. Field guide: the bug table and the code.
Residuals at four speeds fit e = m v + b with m = 12.65 ms and b = 4.08 mm. What do the two numbers mean?

Chapter 1

Every Clock Has an Offset, a Rate and a Wobble

Model a clock with three numbers, and see why the rate is the one that grows

The robot has five clocks: the host, the camera board, the IMU's microcontroller, the LiDAR and the network card. Each counts the ticks of its own crystal. No two crystals tick at the same rate.

Three numbers describe a clock against true time. The offset is how far it reads from truth right now. The rate error, or drift, is how fast that offset grows, quoted in parts per million (ppm): 50 ppm gains 50 µs each second. The jitter is the random wobble of each reading around that line.

Call true time t, the clock's offset b, its rate error ε (epsilon) and its jitter η (eta). The clock reads C:

Say it aloud

C of t equals t, plus b, plus epsilon times t, plus eta.

C(t)
C of t what the clock reads at true time t, in seconds.
t
t true time, counted from the last sync, in seconds.
b
b the offset at the last sync, in seconds. Measure it once and subtract it.
ε
epsilon the rate error, a pure number: 46 ppm is 0.000046.
η
eta the jitter: a random, zero-mean wobble on each reading.
In plain words

Start from true time t. Add the fixed offset b. Add the drift, epsilon times the time since the last sync. Add a little random jitter eta. The offset you can subtract; the drift term keeps growing until the next sync.

With numbers

With made-up crystals: the camera board runs +30 ppm and the IMU board −16 ppm, so their relative ε is 46 ppm. A 3 ms alignment spec survives 0.003 / 0.000046 = 65 s. After an hour unsynced they disagree by 165.6 ms.

Let two clocks drift, then sync them

The purple line is how far the camera clock reads from the IMU clock. Warm ticks are syncs that pull it back to zero. Change the crystal grade and the sync interval, and keep the line inside the yellow spec.

30 s
0.20 ms

Illustrative crystals and a 3 ms spec. Grades follow common datasheet classes (MEMS about ±50 ppm, TCXO about ±2 ppm); the exact numbers are for this toy.

Read it as a design rule: the worst offset just before a sync is ε times the interval, plus a few jitters. Sync two MEMS crystals every second and the drift adds only 46 µs. Run one robot under a 120 s outage of its time source: a 2 ppm TCXO drifts 240 µs, a 50 ppm part 6.0 ms. Crystals and their temperature drift are taught from the chip up in What Time Is It on a Chip.

Symptom: PTP reports a lock within nanoseconds, yet the fused map gets worse each minute after boot.

Measure: log the system clock minus the network card's clock once a second. A straight ramp is a free-running crystal; its slope is the rate error (46 µs per second at 46 ppm).

Fix: on Linux, ptp4l disciplines the card's clock and phc2sys copies it to the system clock that drivers read. Run and supervise both, and alarm on that difference.

Two boards drift 46 ppm apart. Your alignment spec is 3 ms. Roughly how often must you sync them, ignoring jitter?

Chapter 2

Capture Time, Not Arrival Time

Follow one frame down the pipeline, and split its stamp error into a delay and a wobble

A stamp should name the instant the light hit the sensor. Most stacks write a different instant: the moment a callback ran. Between the two sit the exposure, the transfer, the driver and the scheduler.

Follow one frame from a 30 Hz global-shutter camera. The exposure lasts 4 ms, so its middle comes 2 ms after the start. The transfer over USB takes about 6 ms, the driver wakes about 1.5 ms later, and the ROS callback runs about 2.5 ms after that. Each stage has a mean and a wobble.

Choose where to write the stamp

Top: one frame's journey, exposure first. Bottom: the stamp error over 2,000 simulated frames. Pick a stamp site. Then turn on subtract the mean, and see what is left.

Illustrative stage times with Gaussian jitter, seeded: transfer 6.0 ± 1.0 ms, driver 1.5 ± 0.8 ms, callback 2.5 ± 3.0 ms; a sensor stamp wobbles 0.02 ms.

Call the true middle of the exposure tmid, the mean delay of the chosen stamp site L (the latency) and its random part η. The stamp the software reads is tstamp:

Say it aloud

t-stamp equals t-mid, plus L, plus eta.

tstamp
t-stamp the time written in the message header.
tmid
t-mid the true middle of the exposure: the instant the image best describes.
L
L the latency: the mean delay from t-mid to the stamp site, in seconds. It repeats, so you can measure it.
η
eta the jitter: this frame's random part. Its spread is sigma.
In plain words

Take the true capture instant t-mid. Add the latency L of every stage before the stamp. Add this frame's jitter eta. You can subtract L once; eta changes every frame, so it stays.

With numbers

Callback stamp: L = 2 + 6.0 + 1.5 + 2.5 = 12.0 ms. Independent jitters add as variances: σ = √(1.0² + 0.8² + 3.0²) = 3.26 ms. At 3.4 m/s that jitter alone is 11.1 mm of one-sigma noise, after the mean is gone.

The 12 ms of Chapter 0 is this L. A driver stamp at the last byte has L = 9.5 ms and σ = 1.28 ms. A sensor stamp at mid-exposure has neither. The stamp site matters more than the sync protocol: a perfect clock cannot repair a number taken after 3 ms of scheduler noise.

Symptom: IMU-heavy fusion jerks every 80 ms, though the IMU runs at 400 Hz.

Measure: plot the IMU stamps. If 32 samples share one stamp, the node stamped a whole FIFO packet with now(); the oldest sample is 31 × 2.5 ms = 77.5 ms older than its stamp.

Fix: back-date each sample from the newest by the sample period, or use the sensor's sample counter (FIFO, Watermark and Timestamps).

A callback stamp has L = 12 ms and σ = 3.3 ms. You measure L and subtract it. What error is left?

Chapter 3

NTP, PTP and the Trigger Wire

Align the clocks with a protocol, or align the captures with a pulse

A protocol pulls one clock onto another. Both NTP and PTP swap four timestamps: the client sends a request, the server notes its arrival and its reply, the client notes the reply's return. Averaging the two directions cancels the trip time. Failure Detection and Time, Chapter 3 derives the offset formula and lets you fool it.

The cancellation needs one thing: the trip out and the trip back must take the same time. Call the trip out dout and the trip back dback. The protocol's estimate of the offset is wrong by θerr (theta-err):

Say it aloud

Theta-err equals d-out minus d-back, all over two.

θerr
theta-err the error in the estimated clock offset, in seconds. The protocol cannot see it.
dout
d-out the true one-way delay from client to server.
dback
d-back the true one-way delay from server to client.
In plain words

The protocol assumes each trip took half the round trip. If d-out is longer than d-back, half of the difference lands in the offset estimate as theta-err.

With numbers

With made-up delays: NTP over Wi-Fi, 7 ms out and 2 ms back, gives θerr = 2.5 ms, which is 8.5 mm at 3.4 m/s. PTP through a loaded store-and-forward switch, one 1500-byte frame (12 µs at 1 Gb/s) ahead in one direction only: θerr = 6 µs, or 20 µm.

Compare sync methods on one ruler

Each bar is the timing error a method leaves, on a log scale from 10 ns to 100 ms. Pick a method and drag the path asymmetry. The read-out turns the error into millimetres at your speed.

…

Illustrative sizes. Sourced: RFC 5905 says clients on fast LANs stay within a few hundred microseconds; IEEE 1588-2008 says PTP supports accuracy in the sub-microsecond range. The trigger bar assumes a few microseconds of wiring and trigger delay.

PTP and NTP solve the same equations. PTP wins because a PTP network card stamps the packet in hardware as it crosses the wire, so the operating system's delays never enter the measurement. PTP-aware switches also report how long each packet waited inside them.

A hardware trigger does something different: one electrical pulse starts every sensor's exposure. It aligns the captures, not the clocks. You still need one mapping from the trigger's counter to host time, and a camera with auto-exposure still moves its mid-exposure instant (Chapter 4). The pin-level side is in Hardware Timestamps.

Symptom: PTP converges to a steady offset, but LiDAR deskew is off by the same few microseconds on every robot of one build.

Measure: log PTP's measured path delay while you load one direction of the link. If it shifts, the path is not symmetric.

Fix: use transparent or boundary clocks on every hop, make the path symmetric, or set a static asymmetry correction in ptp4l.

Why can a symmetric round trip of 10 ms still give a perfect NTP offset, while an asymmetric one of 9 ms cannot?

Chapter 4

Exposure and the Rolling Shutter

Give each row of an image its own capture time, and stamp the middle of the light

An image is not one instant. A global shutter exposes all rows together for an exposure time E; the image best describes the middle of E. A stamp at the start of exposure is E/2 early. With auto-exposure, E moves from 1 ms in sun to 10 ms in shade, so that bias moves from 0.5 ms to 5 ms. You cannot calibrate a constant out of it.

A rolling shutter exposes the rows one after another. Row 0 starts first; the last row starts one readout time later. Each row is its own capture instant.

Call the start of row 0's exposure t0, the exposure time E, the readout time Tro, the number of rows H and the row index r. The middle of row r's exposure is trow:

Say it aloud

t-row equals t-zero, plus E over two, plus r times T-r-o over H.

trow
t-row the instant row r best describes: the middle of its exposure.
t0
t-zero when row 0 starts to expose.
E / 2
E over two half the exposure time: moves the stamp to the middle of the light.
r
r the row index, 0 at the top.
Tro
T-r-o the readout time: from the first row's start to the last row's start. Zero for a global shutter.
H
H the number of rows. T-r-o over H is the line time.
In plain words

Start at t-zero. Add half the exposure E to reach the middle of the light. Then add one line time, T-r-o over H, for each row r below the top.

With numbers

With made-up sensor numbers: H = 1,080 rows, Tro = 16 ms, so one line takes 14.8 µs. The middle row, r = 540, is 8.0 ms after row 0. Panning at 60°/s with a 1,000 px focal length, the image moves 16.8 px between the top row and the bottom row.

Pan past a pole, row by row

Left: the camera turns past a pink pole. Right: the image, built one row at a time. Raise the readout time or the pan rate and the pole leans. Turn on per-row times to undo it.

16 ms
60°/s

Illustrative pinhole camera: 1,000 px focal length, 1,080 rows, pole 3 m away. The image shift is f ω times the row's time offset, the small-angle form.

The lean is the readout time made visible. For geometry on a moving robot, a global shutter removes the problem. For a rolling shutter, carry the line time with each image and let the estimator use one pose per row, or per band of rows. Visual-inertial systems that model it appear in VNAV Lecture 11.

Symptom: features near the top and bottom of the image disagree with the IMU on fast turns; the middle rows fit.

Measure: plot the reprojection error against the row index. A straight trend that flips sign with the turn direction is the rolling shutter.

Fix: stamp the middle row (or each row) with trow, put the line time in the camera info, or switch to a global-shutter sensor.

A rolling-shutter camera has a 16 ms readout. The driver stamps each image at row 0's mid-exposure. Which row's capture time is that stamp wrong for by about 16 ms?

Chapter 5

Measure the Offset You Cannot See

Shake the robot, then slide one rotation-rate trace over the other until they match

The gyro measures the turn rate directly. The camera gives it too: the rotation between two frames, divided by the frame period. If the camera's stamps are late, its trace is the gyro's, shifted right.

So shake the robot by hand for a few seconds, record both, and slide the camera trace until it lines up with the gyro. The cross-correlation scores the line-up: multiply the two traces sample by sample and add.

Slide the camera trace until it fits

Blue is the gyro, purple the rate from the camera, stamped late by a hidden offset. Drag the lag τ to slide purple. The lower plot scores every lag. Press Find the peak, then try the smooth sway.

0 ms
0.30

Simulated, seeded: 8 s of motion, gyro at 200 Hz, camera at 30 Hz, both resampled onto a 1 kHz grid; the hidden offset is 12 ms. Rates are in rad/s.

Call the gyro rate g, the camera-derived rate c, the sample times tk and a trial lag τ (tau). The estimate of the offset is the lag with the largest score:

Say it aloud

Tau-hat equals the argmax over tau of the sum over k of g of t-k, times c of t-k plus tau.

τ̂
tau-hat the estimated offset: how late the camera's stamps are, in seconds.
argmaxτ
the argmax over tau the trial lag that makes the sum largest.
Σk
the sum over k add one product for each sample time on the grid.
g(tk)
g of t-k the gyro's turn rate at sample time t-k, with its mean removed.
c(tk + τ)
c of t-k plus tau the camera's turn rate read tau later on its own stamps, mean removed.
In plain words

For each trial lag tau, read the camera trace c tau later than the gyro trace g. Multiply the pairs and add them. The tau with the biggest total is tau-hat.

With numbers

In our seeded numpy run with a true offset of 12.0 ms and almost no noise, the peak lands at 11.8 ms. Over 40 recordings with heavy camera noise, the hand shake gives 11.9 ± 1.1 ms. The smooth sway gives 12.0 ± 13.3 ms: the same mean, twelve times the spread.

The motion decides the answer. A slow sine looks almost the same shifted a little, so its peak is broad and noise moves it. Several frequencies give a sharp peak. A parabola through the peak and its two neighbours refines it below the grid step (the Code Lab below).

This is the quick bench test. Kalibr (Furgale, Rehder and Siegwart, IROS 2013) fits a continuous-time spline to the trajectory and estimates the offset with the extrinsics. Li and Mourikis (IJRR 2014) put the offset in the filter's state and estimate it online. Lesson 5, Calibration and Sensor Fusion 15 build both.

Symptom: the offset estimate changes by tens of milliseconds between two calibration runs.

Measure: look at the correlation curve. A broad hump, or several peaks a period apart, means the motion was too smooth or too periodic.

Fix: shake in all three axes with sharp, irregular motion for 10 to 30 s, and check the width of the peak, not only its position.

The robot sways at one slow, steady frequency during the shake test. What happens to the offset estimate?

Chapter 6

Ask for a Pose Between Two Samples

Interpolate the position on a line and the rotation on the sphere

A LiDAR captures a point at 12.3456 s; the pose stream has samples at 12.34 and 12.35 s. You need the pose between them. Reusing the older sample, a zero-order hold, can be 34 mm off at 3.4 m/s and 100 Hz.

Linear interpolation for position does far better. Call the largest acceleration a and the gap between pose samples h. Between two samples, a straight line differs from the true curved path by at most elin:

Say it aloud

The size of e-lin is at most a times h squared, over eight.

|elin|
the size of e-lin the gap between the straight line and the true path, in metres.
a
a the largest acceleration between the two samples, in metres per second squared.
h²
h squared the time between pose samples, in seconds, multiplied by itself.
In plain words

The path bends by a times h squared over two across the gap. The straight chord is worst at the middle, where the bend is a quarter of that. So square h, multiply by a, divide by eight.

With numbers

Pose at 30 Hz, h = 0.0333 s, peak acceleration a = 2.28 m/s²: |elin| ≤ 0.317 mm. A zero-order hold on the same stream at 3.4 m/s can be off by v h = 113 mm.

Rotation needs more. A blend of two quaternions is not unit length. Normalise it (NLERP) and you get a rotation, but not a steady turn rate. SLERP moves along the great circle of the unit sphere at a constant rate.

Call the two unit quaternions q0 and q1, stored scalar last (x, y, z, w) as in Lesson 1. The angle between them on the sphere is Ω (omega), with cos Ω = q0 · q1. The fraction of the way from t0 to t1 is u:

Say it aloud

q of u equals sine of one minus u times omega, times q-zero, plus sine of u omega, times q-one, all over sine omega.

q(u)
q of u the interpolated orientation, a unit quaternion.
q0
q-zero the orientation at the earlier sample t-zero.
q1
q-one the orientation at the later sample, sign-flipped first if q-zero dot q-one is negative.
sin((1 − u) Ω)
sine of one minus u omega the weight of q-zero; it falls as u grows.
sin(u Ω)
sine of u omega the weight of q-one; it grows with u.
sin Ω
sine omega divides both weights so that q of u stays unit length.
In plain words

Set u = (t − t-zero) / (t-one − t-zero). If q-zero dot q-one is negative, negate q-one. Weight q-zero by sine of (1 minus u) omega, q-one by sine of u omega, add, and divide by sine omega.

With numbers

A 90° turn between samples, so Ω = 45° on the sphere. At u = 0.25, SLERP gives 22.50°, exactly a quarter. NLERP gives 21.60°. Its worst error over the interval is 0.92°, near u = 0.22.

Interpolate a turn four ways

The robot turns 90° between two pose samples. Grey ticks mark where a steady turn would be at each quarter. Drag u and pick a method. Then let the second sample arrive with its sign flipped.

0.25

Exact maths, yaw only, scalar-last quaternions. −q1 is the same orientation as q1.

Symptom: once in a while the interpolated heading whips most of a turn and comes back, between two samples a few degrees apart.

Measure: print q0 · q1 for consecutive samples. A negative value is a sign flip: the same orientation, the other hemisphere.

Fix: negate q1 when the dot product is negative, then SLERP (Lesson 1, Chapter 4 has the double cover).

The pose stream drops from 30 Hz to 10 Hz. By how much does the worst linear-interpolation error grow, at the same acceleration?

Chapter 7

Buffers, Pairing and the Latency Budget

Index every buffer by capture time, pair messages by their stamps, and wait for the slowest sensor

Data arrives out of order. The IMU sample for 12.340 s comes 3 ms later; the LiDAR scan for the same instant comes 60 ms later. So key every buffer by capture time, and let a query find the two samples around it.

A query has two honest failures. Older than the buffer: the data was overwritten. Newer than the newest sample: you must wait, or extrapolate and say so. A buffer that clamps either case to the nearest sample invents motion. The Code Lab builds this ring buffer, the structure under tf2's transform buffer.

To fuse a camera image with a LiDAR scan, something must pair them. ROS 2's message_filters package does it. Its Python ApproximateTimeSynchronizer keeps a queue per topic and emits a set when the stamps span less than a tolerance (slop, newer releases call it tolerance_seconds). By default it reads the header stamps. An option pairs by arrival time instead, which brings back Chapter 2.

Pair two streams by their stamps

Top row: camera at 30 Hz. Bottom row: LiDAR at 10 Hz. Lines join the pairs the synchronizer emits. Drag the tolerance. Then pair by arrival time, and read the true capture gap.

20 ms

Illustrative streams, seeded. Camera latency 12 ± 3 ms, LiDAR 60 ± 2 ms. The pairing rule follows the Python synchronizer for two topics: the newest message takes the closest partner whose stamp is within the tolerance.

Now the budget. A fused state for capture time t needs every sensor's data for t. So it waits for the slowest: here the LiDAR, 60 ms. Add 12 ms of compute, and the estimate describes the world as it was 72 ms ago.

StageAge addedCan you remove it?
IMU arrives3 mshidden by the wait
Camera arrives12 mshidden by the wait
LiDAR arrives (sets the wait)60 msshorter scans, or fuse it later as a correction
Fusion compute12 msfaster code
Estimate age72 mspredict forward with the IMU

Worked number: at 3.4 m/s, 72 ms is 0.245 m. A controller that acts on that pose as if it were now steers a quarter metre late. So the last step integrates the IMU from t to now. The age is not an error once you know it; it becomes one when you ignore it.

Symptom: projected LiDAR points slide across the image on turns, though every stamp is right.

Measure: grep for a transform lookup at time 0. In tf2, time 0 means the latest transform, not the one at the scan's stamp.

Fix: look up the transform at the message's header stamp, with a timeout so the buffer can catch up.

A camera arrives 12 ms after capture and a LiDAR 60 ms after. Fusion takes 12 ms. How old is the fused estimate when it is published?

Chapter 8

Showcase: The Alignment Bench

Stack every timing error into one budget, and turn it into a speed limit

Back to the sidewalk robot. Each chapter gave it one source of timing error: a stamp site, a clock, a shutter, an interpolator. Each has a mean part, which shifts every point the same way, and a random part, which scatters them.

Means add with their signs. Random parts add as variances. For a budget, take the total mean plus two standard deviations, about 95% of frames. Multiply by speed and compare with the 50 mm localisation budget. The speed where they meet is the robot's speed limit.

Build the timing budget, read the speed limit

Left: the right wall of the room, magnified, as mapped going out and coming back. Right: the timing budget, one bar per source. Change one setting at a time, then press Fix it all.

3.4 m/s

Illustrative error model built from this lesson's numbers. Clock sync only matters for sensor stamps; host stamps share the fusion clock. Subtracting a measured offset leaves 1.1 ms of estimation error (Chapter 5). The magnified wall uses the mean only, plus the jitter as scatter.

Worked number: the ticket's robot uses callback stamps, a global shutter and a 100 Hz pose held, not interpolated. The mean is 12.0 + 5.0 = 17.0 ms; the spread is √(3.26² + 2.89²) = 4.36 ms. Mean plus two spreads is 25.7 ms, so at 3.4 m/s the error is 87 mm, and the speed limit is 1.94 m/s. That is the ticket: fine at walking pace, broken above 2 m/s.

Measure the 17 ms and subtract it, and the speed limit rises to 5.56 m/s, but the 4.5 ms of jitter is still there. Move to sensor stamps with PTP and interpolate, and the budget falls to well under a millisecond. Fix the stamp site first: it is the largest bar, and no later step can undo it.

Symptom: a fix that "should" help changes nothing on the map.

Measure: look at the bar sizes. Clock sync does nothing when the host takes the stamp, and a PTP upgrade cannot shrink a callback's 3 ms jitter.

Fix: rank the sources by size and fix the largest first; re-run the speed sweep of Chapter 0 to confirm the slope fell.

Callback stamps, measured and subtracted, PTP added. Which error is left in the largest share?

Chapter 9

Field Guide

Keep the bug table, the code and the next steps in one place

Every measurement has two labels: its frame (Lesson 1) and its instant. Stamp the instant the sensor captured, as close to the sensor as you can. Keep clocks disciplined, give each image row its own time, measure what offset is left, and interpolate on the sphere. When an error grows with speed, fit it against speed and read the slope in seconds.

BugSymptomSignature that names it
Arrival stamp (callback now())smear grows with speederror against speed has a slope in ms; 12 ms here
Free-running clockworse each minute after bootoffset is a straight ramp; slope = ppm
ptp4l without phc2sysPTP green, map driftingsystem clock minus card clock ramps
Asymmetric network pathsteady offset on one builderror = (dout − dback)/2; path delay shifts under load
Start-of-exposure stampbias changes with lightingoffset follows exposure / 2
Rolling shutter ignoredtop and bottom rows disagree on turnsreprojection error trends with row index
FIFO stamped as onejerks at the packet ratemany samples share one stamp
Hold instead of interpolatesawtooth error at the pose rateerror up to v h
Quaternion sign flipone whip between close samplesq0 · q1 < 0
tf lookup at time 0points slide on turnsuses the latest transform, not the stamp's
Pairing by arrivalfused pairs disagree when movingcapture gap = latency difference
python
import numpy as np

def mid_exposure_stamp(t_start, exposure, row=0, readout=0.0, rows=1):
    """t_row = t0 + E/2 + r * T_ro / H. readout = 0 for a global shutter."""
    return t_start + exposure / 2 + row * readout / rows

def fit_clock(t_ref, t_dev):
    """Fit t_dev = (1 + eps) t_ref + b. Returns offset b (s) and rate error (ppm)."""
    slope, b = np.polyfit(t_ref, t_dev, 1)
    return b, (slope - 1.0) * 1e6

def estimate_offset(t, gyro, t_cam, cam, max_lag=0.1, step=0.001):
    """Camera stamps late by tau: maximise sum g(t) c(t + tau), then refine."""
    g = gyro - gyro.mean()
    taus = np.arange(-max_lag, max_lag + step / 2, step)
    score = []
    for tau in taus:
        c = np.interp(t + tau, t_cam, cam)
        score.append(np.dot(g, c - c.mean()))
    k = int(np.argmax(score))
    y0, y1, y2 = score[k - 1], score[k], score[k + 1]
    return taus[k] + 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2) * step

def slerp(q0, q1, u):
    """Scalar-last unit quaternions (x, y, z, w). Flip q1 onto q0's hemisphere first."""
    q0, q1 = np.asarray(q0, float), np.asarray(q1, float)
    d = float(np.dot(q0, q1))
    if d < 0:
        q1, d = -q1, -d
    if d > 0.9995:                       # nearly equal: NLERP is safe
        q = q0 + u * (q1 - q0)
        return q / np.linalg.norm(q)
    om = np.arccos(d)
    return (np.sin((1 - u) * om) * q0 + np.sin(u * om) * q1) / np.sin(om)

def bracket(ts, tq):
    """Index i and fraction u with ts[i] <= tq <= ts[i+1]. None if tq is outside."""
    if len(ts) < 2 or tq < ts[0] or tq > ts[-1]:
        return None                       # overwritten, or wait for data
    i = min(int(np.searchsorted(ts, tq, side='right')) - 1, len(ts) - 2)
    return i, (tq - ts[i]) / (ts[i + 1] - ts[i])

def speed_limit(mean_s, sigma_s, budget_m=0.05):
    """Largest speed whose 95% timing error (mean + 2 sigma) fits the budget."""
    return budget_m / (abs(mean_s) + 2 * sigma_s)

We ran every function above in numpy on the lesson's examples: speed_limit(0.017, 0.00436) gives 1.94 m/s, and the slerp matches the Code Lab's check.

Where it sits. Real stacks put PTP in the network (IEEE 802.1AS, gPTP, is its profile for automotive and audio Ethernet), sensor stamps in hardware, and the remaining offset in the estimator's state. Continuous-time estimators query the trajectory at each measurement's own instant, which removes the interpolation step.

Keep going

Read next

The habit. For every measurement, ask "which instant?" before "which frame?". Then, when something smears, plot the error against speed: a slope in seconds is a clock you can find.
Which single change most often fixes a speed-dependent smear?

Now teach it: press Present or Teach and explain why 12 ms doubles a wall at 3.4 m/s and not at 1 m/s. Then go back to the room and predict the wall gap at 2 m/s before you drag.

Time, Clocks and Sensor Alignment · Robotics Engineering, Lesson 2
Previous: Coordinate Frames · Next: Uncertainty · Back to Gleams