A spinning lidar needs 100 ms to draw one picture, so every point has its own moment. Give a point the wrong time and a moving robot sees its wall bend by speed times error.
Learn how PPS, NMEA and PTP set a lidar’s clock, how phase lock lines up several sensors, and how motion deskew uses every stamp.
Drive the robot at 3 m/s and choose One stamp per scan: the front wall tears. Choose Per-column stamps and it heals. Then put the clocks 25 ms apart and watch the whole room slide. Then we build, piece by piece, the firmware chain that keeps every stamp true.
You need a feel for speed times time equals distance and a little C. We build clocks, pulses and PTP from zero.
Built from the Ouster sensor documentation (Time Synchronization, Multi-Sensor Synchronization, GPS/GNSS Synchronization Guide, PTP Guide, Lidar Data Packet Format), the gpsd Time Service HOWTO and the Precision Time Protocol article. Part of Firmware from Zero to Expertise. Every room, robot and jitter in the devices is a model.
Model: one ring of 360 beams, one turn in 100 ms (10 Hz, the Ouster 1024x10 style rate), in a 7.6 m by 5.6 m room. The robot drives forward at constant speed and turn rate. Deskew places each point with the robot pose at that point’s stamp. Illustrative geometry, not a recording.
Chapter 0
See why a lidar point needs its own moment in time, and why a small timing error becomes a big error in space
A small delivery robot rolls down a hallway at 3 metres per second. On its roof sits a spinning lidar. The robot draws a map of the hallway from the lidar’s points. The map comes out wrong. The straight end wall shows a step, as if two walls met at a seam.
Nothing is broken. The lidar works. The wheels work. The map software has no bug. The fault is smaller than any of those: the program gave some points the wrong time.
To see why, start with what a spinning lidar is. It is a laser range finder on a motor. It sends a pulse of light, times how long the light takes to come back, and turns that time into a distance. The motor turns the head, so the next pulse points a little further round. After one full turn the lidar has measured a ring of distances. Our lidar turns 10 times a second, so one turn takes 100 ms.
One turn is one scan. Most software treats a scan as one photograph. A photograph shows one instant. A scan does not. The first point was measured at the start of the 100 ms. The last point was measured at the end. In between, the robot kept moving.
At 3 m/s the robot moves 3 × 0.1 = 0.3 m in 100 ms. That is 30 cm. If the program places all the points as if the robot stood still, the first and last points disagree by 30 cm. That is the step in the wall.
The cure has a name: motion deskew. Deskew gives each point its own timestamp. It then asks where the robot was at that moment, and puts the point in the right place. Chapter 3 builds it. Deskew only works if each timestamp is true. That is what this whole lesson is about.
You already met this in the hero. In One stamp per scan mode every point shares one time, and the walls tear. In Per-column stamps mode each point has its own time and the walls heal. In Stamps, clocks apart mode the stamps are fine but the lidar clock and the robot clock disagree. Now the whole room slides.
A timestamp is a number that says “this happened at this time”. A clock is a counter that adds one every tick. A timestamp is only as good as two things: how precisely the counter ticks, and whether the clock agrees with every other clock in the robot.
A robot has many clocks. The lidar has one. The inertial sensor (a small chip that measures turning and pushing) has another. The computer has a third. Each is a quartz crystal that vibrates at a slightly different speed. Chapter 1 shows how far they drift apart.
Here is the rule that drives the whole lesson. A timing error of e seconds at speed v becomes a position error of v × e metres. At 3 m/s, 1 ms of error is 3 mm. 10 ms is 3 cm. 100 ms is 30 cm. Time errors that look tiny in a log file become visible in the map.
A lidar point travels a long way before software uses it. The laser fires inside the sensor. The sensor builds a packet. The packet crosses a cable, a network chip, the operating system, and a driver. At last a program reads it. You can write the time down at any of these places. The later you write it, the more random delay it has picked up.
The Ouster lidar documentation states that all lidar and IMU data are stamped from a common timer with 10 ns precision. So the best place to take the stamp is inside the sensor, at the moment of measurement. Every later place is worse. Try each place below.
Pick where the program writes the time. Each bar is the distance error that stage’s timing error causes at your speed. The yellow line is a 1 cm budget.
The sensor figure (10 ns) is the Ouster documentation’s timer precision. The other three delays (1 µs, 100 µs, 5 ms) are illustrative typical sizes for a NIC with hardware stamping, a kernel driver, and a program woken by the scheduler. Measure your own system.
Read the bars. At 3 m/s a 5 ms program-side delay costs 1.5 cm, already over the budget. A 10 ns stamp costs 0.00003 cm. Nobody will ever see it. The firmware job in this lesson is to keep the error near the bottom of the chart all the way to the map.
One more point. Delay that is the same on every packet is easy to fix: subtract it. Delay that changes from packet to packet is called jitter. Jitter cannot be subtracted. That is why we stamp early, with hardware.
Two earlier ideas help. What time is it on a chip covers crystals and counters in depth. A later lesson on deterministic Ethernet covers the PTP standard in depth; here we teach just enough of it to run a lidar. If you want the maths of how a pose is used afterwards, see lidar-inertial factor graphs.
Chapter 1
Count the ticks of a crystal, see why no two counters agree, and measure how far they wander apart
Take a kitchen timer with no display. All it does is tap a table 1,000 times a second. You count the taps. After 5,000 taps you say five seconds have passed. That is a clock: a steady tapper and a counter.
Inside a chip the tapper is a crystal oscillator, a small slice of quartz that vibrates at a fixed rate when you give it power. A circuit turns each vibration into a pulse. A timer peripheral counts the pulses. The number in the timer register is the clock’s time. To change ticks into seconds you divide by the tick rate. A counter at 84 MHz adds 84,000,000 each second, so one tick lasts about 11.9 ns.
This is also how the lidar keeps time. The Ouster documentation says the sensor stamps every lidar and IMU sample from one common timer with 10 ns precision. In its default mode, called TIME_FROM_INTERNAL_OSC, that timer counts from the moment the sensor powers on. The first stamp after boot is a small number, not a date.
A counter has a fixed number of bits. When it passes its top value it falls back to zero. We call this wrap-around. A 32-bit counter ticking once per microsecond wraps after 232 µs, about 4,295 s, or 71.6 minutes. A program that compares two such stamps with a plain “is A bigger than B” breaks at the wrap. The lidar uses 64 bits of nanoseconds, which wrap after 264 ns, about 584 years. That is why the packet column timestamp is a 64-bit integer.
For a smaller counter the safe habit is to subtract, not compare. In unsigned arithmetic, now − then gives the right elapsed ticks even across one wrap. The code below shows the idiom.
No crystal is perfect. Its real rate differs from its label by a small fraction. We write that fraction in ppm, parts per million. A clock that is 20 ppm fast gains 20 millionths of a second every second: 20 µs per second.
Small numbers add up. Here is the worked example, step by step.
Two clocks that started together are nearly half a metre apart in the map after one hour. Temperature moves the rate too, so the gap does not even grow in a straight line.
Set how fast each clock runs. The warm line is the gap between them over time. Turn on Fix once a second to see what a pulse every second does to the gap.
Illustrative: each clock keeps a constant rate error. Real crystals also drift with temperature and age (see the clocks lesson). The correction resets the gap to zero at each whole second, which is what a PPS pulse allows in Chapter 4.
Drag the correction on. The gap no longer grows without limit. It climbs for one second, then drops to zero. The largest gap is now the rate error times one second: 40 µs for our two clocks. That is the key trick of this lesson. We cannot make a crystal perfect, so we reset it often.
You can measure a crystal’s error with one wire. A GPS receiver outputs a pulse once a second whose spacing is very exact. Feed the pulse to a timer’s input capture pin. Input capture copies the timer count into a register at the instant an edge arrives, in hardware, with no interrupt delay in the stamp. The difference between two captures is the number of your ticks per true second.
c/* STM32F446 (Nucleo-F446RE): TIM2 is a 32-bit timer; PPS on its channel 1 input. Assume you configured the timer clock to count at exactly 84 MHz nominal. */ static volatile uint32_t last_cap; static volatile int32_t ppm_x10; /* error in tenths of a ppm */ void TIM2_IRQHandler(void) { if (TIM2->SR & TIM_SR_CC1IF) { uint32_t cap = TIM2->CCR1; /* hardware copied the count at the edge; reading clears the flag */ uint32_t dt = cap - last_cap; /* unsigned subtract: correct across a wrap */ last_cap = cap; int32_t diff = (int32_t)dt - 84000000; /* ticks gained (+) or lost (-) in one true second */ ppm_x10 = diff * 10 / 84; /* 84 ticks = 1 ppm at 84 MHz */ } }
Read the code from the top. The hardware stores the count in CCR1 when the edge arrives. The interrupt may run microseconds later, but the stored value does not change. That is why input capture beats stamping inside an interrupt. If diff is +1,680 ticks, the clock runs 20 ppm fast, because 1,680 / 84 = 20.
On real hardware. Use an STM32 Nucleo-F446RE and any GPS module with a PPS output. Wire PPS to the TIM2 channel 1 pin (check the pin in the board manual). Log ppm_x10 once a second for ten minutes with the board in still air, then blow gently on the crystal side with a warm hand and repeat. You should see the rate move.
Chapter 2
Follow a scan from the first column to the last, and find the stamp that each column carries
Picture a lighthouse. Its beam sweeps round once, and a ship watching it sees a flash only when the beam points its way. A spinning lidar is a lighthouse that also measures. Each time the head points a new way, it fires, listens, and records one column of distances.
A column is one firing direction: for a sensor with 32, 64 or 128 beams stacked one above another, it holds that many distances at once. Our model uses one beam, so a column is one distance. The Ouster documents call the number of columns in one turn the scan width. A mode named 1024x10 means 1,024 columns per turn and 10 turns per second.
Start with what is known. In 1024x10 the head turns 10 times a second, so one turn lasts 100 ms. It fires 1,024 columns in that time. So one column takes 100 ms / 1,024 = 97.66 µs.
The sensor does not send columns one at a time. It groups them in UDP packets (a packet is one chunk of data sent over a network). The Ouster packet-format page lists the packet rate for each mode: 320 packets per second for 512x10, 640 for 1024x10 or 512x20, and 1,280 for 2048x10 or 1024x20. Divide columns per second by packets per second and the answer is 16 columns per packet in every case. For 1024x10: 1,024 × 10 = 10,240 columns per second, and 10,240 / 640 = 16.
One packet therefore covers 16 × 97.66 µs = 1.5625 ms of rotation, which is 5.6 degrees of azimuth. Packets arrive every 1.5625 ms. If the network stamps each packet when it arrives, those 16 columns all get one time, but they were fired across 1.56 ms. At 3 m/s that spread is 4.7 mm. Small, but it is pure waste when each column already carries its own.
Choose a mode, then drag the column. The wedge is the packet that holds it. The bar below is the whole 100 ms or 50 ms scan, cut into packets.
Mode names and packet rates are from the Ouster Lidar Data Packet Format page; columns per packet (16) is derived from them. The azimuth rule is the encoder angle formula in the Ouster Firmware User Manual (v2.5.3). The docs do not say which edge of a column its stamp marks, so check that on your firmware before trusting sub-column precision.
A packet carries no angle field. The sensor sends a measurement ID for each column, a 16-bit counter that runs from 0 up to 511, 1,023 or 2,047, depending on the mode. The angle comes from the ID. The Ouster Firmware User Manual gives the encoder angle as 2π × (1 − ID / scan width), in radians.
Work it for column 768 in 1024x10. The fraction is 768 / 1,024 = 0.75. So θ = 2π × 0.25 = π/2, which is 90 degrees. The time since the turn began is 768 × 97.66 µs = 75 ms. At 3 m/s the robot moved 22.5 cm since column 0. Column 768 and column 0 are 22.5 cm apart in robot position. That is the number deskew must remove.
Each column header holds a 64-bit timestamp in nanoseconds, the 16-bit measurement ID, and a status flag. The status says 1 for a good column and 0 for a column that was dropped or disabled. The stamp and the ID are what you need.
Why keep both? The stamp says when. The ID says which way. If a packet is lost, the stamps of its neighbours still tell you exactly how long the gap was. If you only had the frame’s first stamp, you would rebuild every other time from the ID and assume a perfect, steady spin. The motor is not perfect. The sensor’s own stamp is better than your reconstruction.
The scan boundary has its own counter. The frame ID goes up by one every time the head crosses azimuth zero. Software that cuts a stream into scans should cut at the frame ID change, not at a fixed time.
c/* The fields of one column, already decoded from the packet bytes. */ typedef struct { uint64_t ts_ns; /* column timestamp, nanoseconds on the sensor timer */ uint16_t meas_id; /* 0 .. W-1 */ uint8_t valid; /* 1 = good column, 0 = dropped or disabled */ } col_hdr_t; /* Encoder angle in radians, from the documented rule. */ static inline double col_theta(const col_hdr_t *c, uint16_t W) { return 6.283185307179586 * (1.0 - (double)c->meas_id / W); } /* Seconds from the first column of this scan to this column. */ static inline double col_dt(const col_hdr_t *c, uint64_t scan_start_ns) { return (double)(c->ts_ns - scan_start_ns) * 1e-9; /* unsigned subtract, then convert */ }
Note the order in col_dt. We subtract two 64-bit integers first and only then convert to double. A double holds about 15 to 16 decimal digits. A time since 1970 in nanoseconds has 19. Converting first would throw away the nanoseconds.
On real hardware. With an Ouster sensor on a laptop, record one second of packets. Print ts_ns and meas_id for the first 40 columns. Check that the stamps rise by about 97.66 µs per ID in 1024x10 mode and that IDs wrap to 0 once per 100 ms.
Chapter 3
Move every point of a scan to one common moment, and learn how a clock gap turns into metres
You are in a moving train, and you take a panorama photo by sweeping your phone slowly left to right. The pillars on the platform lean and smear. The phone took the left edge first and the right edge a second later, and the train moved in between.
A lidar scan is the same panorama. The fix is the same idea too: work out where you were at each instant of the sweep, and shift each slice by that amount.
Every point was measured from a slightly different spot. We want them all described from one spot, as if the robot had frozen. Pick that spot first. It is the pose at a reference time, usually the start of the scan, sometimes the middle. A pose is a position plus a heading: where the sensor is and which way it faces.
For each point we do three things. Find the pose at the point’s own stamp. Turn the point from sensor coordinates into world coordinates with that pose. Turn it back into sensor coordinates as seen from the reference pose.
The poses come from a faster motion source: wheel odometry or an IMU, a chip that measures turning and pushing hundreds of times per second. Its samples rarely land on a lidar stamp, so we interpolate between the two samples that bracket the stamp. Positions use a straight line between samples. Headings blend along the short way round; in 3-D that blend is called slerp.
If the robot also turns, the shift grows with distance. A turn of δθ radians moves a point at range r sideways by about r × δθ. At 0.5 rad/s, 75 ms is 0.0375 rad, or 2.15 degrees. A wall 20 m away slides 20 × 0.0375 = 0.75 m. Turning is the harsher case.
Now suppose the lidar says column 768 fired at 75 ms, but the pose source runs on a clock that is 10 ms off. The program asks the pose track for the pose at 75 ms and receives the pose that belongs to 65 ms or 85 ms. The shift is wrong by v × 10 ms = 3 cm when going straight, and by r × ω × 10 ms when turning.
Look back at the hero. In Stamps, clocks apart the whole scan lands off by the same gap. When the robot drives straight at constant speed that gap is a rigid slide of the room. When the robot turns or speeds up, it is no longer rigid, and walls smear. This is why the stamp must be true, not merely present.
The warm line is the error from driving. The pink line is the error from turning, at the range you choose. The blue line is their sum. Find where it crosses the yellow 1 cm line.
Model: error = v × gap for translation and r × ω × gap for rotation, added as an upper bound. The 1 cm budget is illustrative; set your own from your map accuracy needs.
Slide the range to 100 m and the turning line shoots up. A lidar that sees far needs a tighter clock than one that sees only a room. Slide the turn rate to zero and only the gentle driving line remains. Now read off the answer to the design question: the clock gap you can afford is the budget divided by (v + rω). For 1 cm at 3 m/s and 0.5 rad/s to 20 m: 0.01 / (3 + 10) = 0.77 ms. That is a tight target. It is why serious setups use hardware time sync and not software stamps.
c/* 2-D deskew: shift and rotate one point to the pose at t_ref. Poses come from a faster source (IMU or odometry); we interpolate between two samples. */ typedef struct { double t, x, y, yaw; } pose_t; static pose_t pose_at(const pose_t *a, const pose_t *b, double t) { double u = (t - a->t) / (b->t - a->t); /* 0 at sample a, 1 at sample b */ double dy = atan2(sin(b->yaw - a->yaw), cos(b->yaw - a->yaw)); /* short way round */ pose_t p = { t, a->x + u * (b->x - a->x), a->y + u * (b->y - a->y), a->yaw + u * dy }; return p; } static void deskew_point(double px, double py, pose_t ti, pose_t tref, double *ox, double *oy) { double wx = ti.x + cos(ti.yaw) * px - sin(ti.yaw) * py; /* to world with T(t_i) */ double wy = ti.y + sin(ti.yaw) * px + cos(ti.yaw) * py; double dx = wx - tref.x, dyy = wy - tref.y; /* back with the inverse of T(t_ref) */ *ox = cos(tref.yaw) * dx + sin(tref.yaw) * dyy; *oy = -sin(tref.yaw) * dx + cos(tref.yaw) * dyy; }
Run it per point, not per scan. Call pose_at with that point’s own column stamp, in the same clock as the pose samples. If the two sources use different clocks, no code here can save you. Chapters 4 to 6 give them one clock. The calibration lesson on calibration and time sync shows how to estimate a leftover constant gap, but a gap you can measure with a pulse is better than one you estimate.
On real hardware. With a Nucleo-F446RE reading an IMU and a lidar on a rolling cart, push the cart forward and back at about walking pace past a flat wall. Add a deliberate 20 ms offset to the IMU stamps in software. Compare the wall thickness in the deskewed cloud with and without the offset.
Chapter 4
Use a single electrical edge, once a second, to pull every clock back to the same instant
An orchestra tunes to one note. The oboe plays an A, and everyone matches it. Nobody needs to hear the oboe all night. They need it often enough that no violin drifts far.
A PPS signal, short for pulse per second, is that oboe. A GNSS receiver (the box that listens to navigation satellites such as GPS) knows true time from the satellites. Once every second it sends one clean electrical edge on a wire. The edge marks the exact start of a second. Nothing else rides on that wire.
How good is the edge? The gpsd Time Service HOWTO says the satellites deliver a top-of-second notice that is nominally accurate to 50 ns. After the receiver and the host add their own delays, the pulse is often good to about 1 µs. With a kernel that stamps the edge in an interrupt, that guide says a clock stable to ±1 µs is very doable. With a plain interrupt path, it says to expect about ±5 µs and about 20 µs of jitter. Those figures were observed on 2 GHz x86 PCs, so input capture on a microcontroller can do better. Compare that with the text message alone, which Chapter 5 shows is off by hundreds of milliseconds.
The Ouster sensor has an input called SYNC_PULSE_IN. The documentation describes it as an opto-isolated digital input on the external connector (opto-isolated means a tiny LED and light sensor pass the signal, so the grounds of the two boxes stay separate). It assumes the pulse arrives at 1 Hz. You choose the active edge with a setting named sync_pulse_in_polarity, for example ACTIVE_LOW or ACTIVE_HIGH.
You turn the feature on with timestamp_mode set to TIME_FROM_SYNC_PULSE_IN. The docs describe this mode as a free-running counter synced to the pulse input. In plain words: between pulses the sensor counts with its own crystal, as in Chapter 1. At each pulse it re-aligns to the start of a second. The error can never grow past about one second of drift, which is the sawtooth you saw in Chapter 1.
The docs give the counter step as on the order of 10 ns in this mode. They do not list a pulse width or a voltage. Take those from the sensor’s hardware manual and from your receiver’s datasheet.
Wrong edge. A receiver may hold the line high for 100 ms (illustrative; check your receiver) and then drop it. If the sensor listens for the wrong edge, every stamp is shifted by the pulse width. At 3 m/s that is 30 cm. The Ouster guide gives this advice: if sync_pulse_in does not report locked, check the PPS polarity.
A missing pulse. An obstructed antenna or a loose wire can drop an edge. The sensor then runs free for two seconds, and the drift doubles before the next edge fixes it.
Jitter. The edge itself may wobble by microseconds on a long cable, or the receiver may add its own delay. Jitter you cannot remove by subtraction. Keep the cable short and the edge sharp.
The purple line is the lidar stamp error right now, on a log scale. Each pulse pulls it down. Try the wrong edge, then skip the pulse at 3 s.
Model: error = sqrt((ppm × time since the last pulse)2 + jitter2 + edge offset2). A wrong edge adds a 100 ms offset, an illustrative pulse width. The 1 Hz rate and the polarity setting are from the Ouster docs.
With the right edge, the error rides between about the jitter and the crystal error times one second (20 µs at 20 ppm). That is well under the 1 cm budget of Chapter 3: 20 µs at 3 m/s is 0.06 mm. The wrong edge puts a flat 100 ms floor under everything, which is 30 cm at 3 m/s. The log scale shows why this bug hides: a 100 ms error is more than three orders of size above the rest, yet the sawtooth looks normal because it still repeats.
"locked": 1 under sync_pulse_in.json// POST http://<sensor>/api/v1/sensor/config (setting names from the Ouster docs) { "timestamp_mode": "TIME_FROM_SYNC_PULSE_IN", "sync_pulse_in_polarity": "ACTIVE_HIGH" } // GET http://<sensor>/api/v1/time then check: "sync_pulse_in": { "locked": 1, ... }
For a bench test with no GNSS receiver you can make your own PPS on a microcontroller. A timer in PWM mode does it. With a timer clock of 84 MHz, a prescaler of 8,399 gives 10 kHz, and a period of 10,000 ticks gives 1 Hz. A compare value of 1,000 holds the pin high for 100 ms.
c/* STM32F446 Nucleo: TIM2 CH1 as a 1 Hz, 100 ms-high test pulse (timer clock assumed 84 MHz). */ TIM2->PSC = 8399; /* 84 MHz / 8400 = 10 kHz */ TIM2->ARR = 9999; /* 10,000 ticks = 1 s */ TIM2->CCR1 = 1000; /* high for 1,000 ticks = 100 ms */ TIM2->CCMR1 = (TIM2->CCMR1 & ~TIM_CCMR1_OC1M) | (6 << TIM_CCMR1_OC1M_Pos); /* PWM mode 1 */ TIM2->CCER |= TIM_CCER_CC1E; TIM2->CR1 |= TIM_CR1_CEN;
This is only a test source. Its edge sits on your board’s own crystal, so it is exactly as accurate as that crystal. Real systems take the pulse from a GNSS receiver. Never connect a pin to the sensor before you check the input’s voltage and current needs in its manual.
On real hardware. Feed the test pulse to a second Nucleo that captures it with the Chapter 1 code. Swap the wires so the capture sees the falling edge. Measure the 100 ms shift.
Chapter 5
Read a line of GPS text, check that it arrived whole, and pair it with the right pulse
A train guard blows a whistle at the exact moment the train must leave. The whistle is sharp, but it carries no words. Later a clerk reads out “that was the 9:15”. You need both: the whistle for the instant, the clerk for the name.
PPS is the whistle. NMEA is the clerk. It is a text format that GNSS receivers send over a serial line, one sentence at a time. A sentence tells you which second the last pulse started, along with position and speed.
The Ouster sensor expects a standard $GPRMC message on its UART input (a UART is a simple serial port: one wire of bits, sent one after another at an agreed speed). The docs say the sentence starts with $, separates fields with commas, and introduces a checksum with *. A standard message holds at most 80 characters.
nmea$GPRMC,024041.00,A,5107.0017737,N,11402.3291611,W,0.080,323.3,020420,0.0,E,A*26 time UTC valid latitude N/S longitude E/W knots course date mag. var mode checksum
Three fields matter for time. Field 1, 024041.00, is the time of day: 02:40:41.00 UTC. Field 2, A, means the fix is valid; a V would mean void, and the time must not be trusted. Field 9, 020420, is the date, 2 April 2020. This sentence is modelled on the example in the Ouster GNSS guide, with its checksum recomputed by the method below.
A serial line can flip a bit. A checksum is a small number computed from the data so the receiver can test for damage. For NMEA you XOR every character between $ and *. XOR combines two bytes bit by bit and gives a 1 where the bits differ. The result, in two hex digits, follows the star.
Try it on a short piece. The characters “AB” are 0x41 and 0x42. 0x41 XOR 0x42 = 0x03. If one character changes, the XOR changes, and the receiver rejects the sentence. This catches any single flipped character but not every double error, so it is a guard, not a proof.
Here is the trap. The sentence does not arrive at the pulse. It arrives later. The gpsd Time Service HOWTO says its software assumes that after each fix the receiver asserts the 1PPS first and ships the sentences reporting that second afterwards. It also says fix reports are delayed in the receiver and on the link by as much as several hundred milliseconds, and the delay is not constant. For SiRF chipset receivers it noted about 170 ms of wobble between the true top of the second and the first sentence.
The serial line adds its own delay. A 9600 baud line sends about 960 characters per second, roughly 1 ms per character, as the same HOWTO notes. Our sentence plus its line ending is 81 characters. So it takes about 81 × 10 bits / 9,600 = 84 ms to arrive in full. At 4,800 baud it takes 169 ms. At 115,200 it takes 7 ms.
Add them. If the receiver holds the text for 450 ms and the line takes 84 ms, the sentence for second 41 arrives 534 ms after the pulse that started second 41. Which pulse is closest in time? The next one, only 466 ms away. A program that pairs each sentence with the nearest pulse will label that next pulse “second 41”, when it really starts second 42. Every stamp is then one whole second wrong. At 3 m/s that is 3 m.
Blue lines are pulses. Pink boxes are sentences, each naming the second of the pulse just before it. Raise the receiver delay and choose a pairing rule.
Illustrative delays. The several-hundred-millisecond receiver delay and the serial timing are from the gpsd HOWTO; your receiver differs, so measure it. The sentence has 81 characters with its line ending. The checksum in the box is computed live by the code below.
The rule that survives is: the sentence names the pulse before it. Take the latest pulse that came before the sentence arrived, and trust it as long as the total delay stays under one second. Raise the delay past 1,000 ms in the device and even that rule fails. Real receivers stay far below that, but a design that ignores the limit is hiding a bug.
Earth turns slightly unevenly, so civil time (UTC) sometimes adds a leap second to stay near the sun. Atomic time (TAI) never adds one, so it runs ahead of UTC by a whole number of seconds. The Ouster docs have a setting named nmea_leap_seconds. At the default of 0 the stamps follow the Unix epoch (seconds since 1 January 1970). The docs say a value of 37 makes the stamps match TAI, and their GNSS guide uses 37 for the time of writing. Check the current value before you rely on it.
Why care? Suppose the lidar stamps in TAI and the GNSS-aided pose uses UTC. They differ by 37 s. At 3 m/s that is 111 m. Nothing about the maths fails; the numbers just refer to different moments. Pick one time scale for the whole robot and write it in the log header.
c/* Validate a $GPRMC line and turn it into Unix seconds (UTC). Tested against the sentence above. */ static int nmea_ok(const char *s) { /* s points at '$' */ if (*s != '$') return 0; uint8_t x = 0; const char *p = s + 1; while (*p && *p != '*') x ^= (uint8_t)*p++; /* XOR everything between $ and * */ if (*p != '*') return 0; unsigned got; if (sscanf(p + 1, "%2x", &got) != 1) return 0; return x == got; } static int64_t days_from_civil(int y, unsigned m, unsigned d) { /* days since 1970-01-01 */ y -= m <= 2; int era = (y >= 0 ? y : y - 399) / 400; unsigned yoe = (unsigned)(y - era * 400); unsigned doy = (153 * (m > 2 ? m - 3 : m + 9) + 2) / 5 + d - 1; unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; return (int64_t)era * 146097 + doe - 719468; } static int rmc_unix(const char *s, int64_t *out) { int hh, mm, ss, dd, mo, yy; char st; if (!nmea_ok(s) || strncmp(s, "$GPRMC,", 7)) return 0; if (sscanf(s + 7, "%2d%2d%2d%*[^,],%c", &hh, &mm, &ss, &st) != 4 || st != 'A') return 0; const char *p = s; for (int i = 0; i < 9; i++) { p = strchr(p, ','); if (!p) return 0; p++; } if (sscanf(p, "%2d%2d%2d", &dd, &mo, &yy) != 3) return 0; *out = days_from_civil(2000 + yy, mo, dd) * 86400 + hh * 3600 + mm * 60 + ss; return 1; /* this second began at the pulse BEFORE the sentence; add nmea leap seconds if you want TAI */ }
The sentence above gives 1585795241, which is 2 April 2020, 02:40:41 UTC. The function rejects a corrupted line because the checksum fails, and rejects a void fix because the status is not A.
On real hardware. With an STM32 Nucleo-F446RE, read a GNSS module on USART2 at its default baud rate and a PPS on the TIM2 capture pin. Print, for each sentence, the milliseconds between the last PPS capture and the end of the line. You will see the receiver delay and its wobble directly.
Chapter 6
Set a clock over Ethernet by measuring a round trip, and see what breaks the measurement
Two friends stand in different cities and want their watches to agree. Anna calls Ben and says “my watch says 12:00:00 now”. Ben’s watch says 12:00:05 when the words arrive. Is Ben 5 seconds ahead? Not necessarily. The call itself took time. Ben needs to know how long it took.
Ben has a trick. He calls Anna back and says “my watch says 12:01:00 now”. If the call takes the same time in both directions, the two messages together reveal both the delay and the gap between the watches. That trick is the heart of PTP, the Precision Time Protocol, standard IEEE 1588.
PTP needs no extra signal wire. The Ouster docs say it works over a network that supports IEEE 1588. Once it has synchronized, the sensor time is in seconds and nanoseconds since 1970, and the counter must always count forward. So PTP replaces both the pulse and the text of the last two chapters with Ethernet packets.
Let o be how far the follower clock is ahead of the master, and d the one-way delay. The Sync trip gives t2 − t1 = o + d. The return trip gives t4 − t3 = −o + d. The Wikipedia article writes the same pair with different letters. Add them and the offset cancels. Subtract them and the delay cancels.
Work a full example. The follower runs 300 µs ahead. Each direction takes 50 µs. Then t2 − t1 = 300 + 50 = 350 µs. The return gives t4 − t3 = −300 + 50 = −250 µs. The offset is ½(350 − (−250)) = 300 µs. The delay is ½(350 + (−250)) = 50 µs. Both recovered exactly.
The trick needs both directions to take equal time. Now let the forward trip take 80 µs and the return 20 µs. The total round trip is still 100 µs, so the line still looks healthy. But t2 − t1 = 300 + 80 = 380, and t4 − t3 = −300 + 20 = −280. The offset estimate is ½(380 + 280) = 330 µs. It is 30 µs wrong, which is half of the difference between the two delays. Nothing in the four numbers warns you. The Wikipedia article states the rule: the accuracy of the follower depends on how well the assumptions hold.
What breaks symmetry? A switch that queues packets in one direction only, a busy link, or two cables of different length. This is why the Ouster PTP guide says to connect the sensor directly to the grandmaster if you can, or through at most one simple layer-2 gigabit switch, because several switches add unnecessary jitter.
Chapter 0 showed that stamping later adds jitter. PTP lives or dies by this. Hardware timestamping means the network chip itself writes the time into the packet as it leaves or enters the wire, with no software in the path. Software timestamping records the time in the kernel after the packet has climbed through queues and interrupts. The Wikipedia article notes that a master with PTP support in its network hardware can place an accurate time in the Sync message itself, with no follow-up message needed. It also says accuracy on a local network can be sub-microsecond.
The ladder shows one exchange. The dots below show the offset estimate from sixteen exchanges. Make the two delays unequal, then switch to software stamps.
Model: the formulas above on exact toy numbers. Software stamps add a random 0 to 150 µs (illustrative) to each receive stamp, t2 and t4; hardware stamps add none. Real PTP also filters and steers the clock in a servo loop.
With hardware stamps and equal delays, all sixteen dots sit on the true offset. Make the delays unequal and the dots sit together, but in the wrong place, shifted by half the difference. That is a bias: repeating the measurement does not help. Switch to software stamps and the dots scatter. That is jitter: averaging helps, and a servo does average. Both exist in real networks, and they need different cures. Bias needs a better path. Jitter needs better stamps or more filtering.
A PTP profile is a set of agreed settings so devices from different makers cooperate. The Ouster guide lists four. default is the IEEE 1588 default profile over UDP (layer 3). gptp is the generalised PTP of IEEE 802.1AS-2011 over Ethernet (layer 2). automotive-slave extends gPTP and disables the best-master selection so it settles faster. default-l2-relaxed uses layer 2 with a relaxed one-second time-step limit. The guide says the profile on the sensor and on the master must match. You set it with an HTTP PUT to /api/v1/time/ptp/profile.
The guide gives the checks for a healthy lock: the port state reads SLAVE, gm_present is true, and master_offset is under 1 µs. On the host you can ask the same of a Linux PTP master with the pmc tool from linuxptp.
sh# set the sensor profile, then read the state (command forms from the Ouster PTP guide) curl -X PUT -H "Content-Type: application/json" -d '"gptp"' http://<sensor_hostname>/api/v1/time/ptp/profile/ curl http://<sensor_hostname>/api/v1/time/ptp/profile # on a Linux PTP master host (eno2 is the guide's example NIC name) sudo pmc 'get PARENT_DATA_SET' 'get CURRENT_DATA_SET' 'get PORT_DATA_SET' 'get TIME_STATUS_NP' -i eno2
c/* The core arithmetic of PTP in integer nanoseconds. t1,t4 are on the master clock; t2,t3 on the follower. */ typedef struct { int64_t t1, t2, t3, t4; } ptp_ex_t; static int64_t ptp_offset_ns(const ptp_ex_t *e) { return ((e->t2 - e->t1) - (e->t4 - e->t3)) / 2; } static int64_t ptp_delay_ns(const ptp_ex_t *e) { return ((e->t2 - e->t1) + (e->t4 - e->t3)) / 2; } /* A step larger than a threshold: set the clock. A small offset: steer its rate instead, so the counter never jumps backwards (the sensor counter must always count forward). */
On real hardware. The clean exercise uses two Linux machines with hardware-stamping network cards running ptp4l from linuxptp. Run it once with a direct cable and once through two switches in series, and watch master_offset change. On a microcontroller board such as the STM32 Nucleo-F767ZI, look in its reference manual (RM0410) for the Ethernet MAC’s IEEE 1588 timestamp unit, and read the receive stamp that the hardware attaches to each Sync frame.
Chapter 7
Turn the heads of two or more lidars in step, and fire a camera when the lidar sweeps past it
Two people take a photo of the same bird from two sides. If one clicks now and the other clicks a second later, the bird has moved. The photos disagree even though both cameras are perfect. To combine them you want both clicks at the same instant.
Two spinning lidars on one robot have the same problem. Each head sweeps through the shared view once per turn. If one head passes the wall straight ahead at 0 ms and the other at 50 ms, they see the wall at different moments. On a moving robot, the two clouds of that wall do not line up, even when every stamp is correct. Chapters 4 to 6 gave the two sensors the same clock. This chapter makes them also look at the same time.
The phase of a spinning head is where it points at a given instant. Phase lock is a control loop that nudges the motor so the head points at a chosen angle at a chosen moment of every rotation. The Ouster documentation says the lock keeps the sensor passing through a set angle at the top, tenth or twentieth of a second, depending on rotation rate. The loop runs at 1,000 Hz.
It needs a trustworthy clock first. The docs require the sensor to be time-synchronized externally, with timestamp_mode set to TIME_FROM_PTP_1588 or TIME_FROM_SYNC_PULSE_IN, before it enters phase lock. Phase lock is a layer that sits on top of Chapters 4 to 6.
You switch it on with phase_lock_enable, which defaults to false. You choose the angle with phase_lock_offset, an integer from 0 to 360,000 in millidegrees (thousandths of a degree), measured in the lidar coordinate frame. The docs give the example offsets 180000, 90000 and 270000 for three sensors that must face forward at the same time. The sensors are mounted at different yaw angles, so each one needs a different offset for its head to point the same real direction at the same instant.
The docs list the accuracy under normal conditions. For OS0 and OS1 sensors (both generations) it is 0.5 degrees at 10 Hz and at 20 Hz. For the OS2 it is 5 degrees at 10 Hz and 10 degrees at 20 Hz. Turn an angle into time: one full turn is 360 degrees, and at 10 Hz a turn takes 100 ms. So 1 degree is 100 / 360 = 0.278 ms. A lock error of 0.5 degrees is 0.139 ms. At 3 m/s that is 0.42 mm. The OS2 at 10 Hz, 5 degrees, is 1.39 ms, or 4.2 mm.
The sensor reports trouble through alerts. The docs name 0x01000050 (a warning that the offset error passed its threshold), 0x01000051 (an error: the lock failed several times) and 0x01000024 (an error: the lock failed at startup). Your health monitor should watch for them. A lidar that lost phase lock still produces points, with stamps that are fine, but the sweeps no longer meet.
Both lidars face forward. The warm head belongs to sensor A, offset 0. Set sensor B’s offset, or turn the lock off and see where it lands by itself.
Model: both heads turn at 10 Hz and each points forward at the offset angle at the start of a turn. With the lock off, B’s phase is an arbitrary 137°, illustrative. The accuracies (0.5°, 5° at 10 Hz) and the millidegree offset units are from the Ouster Multi-Sensor Synchronization page. The offset is shown in degrees; the setting takes millidegrees (90° is 90000).
With the lock on and equal offsets, both heads are always at the same angle, and the delay between their sweeps of the wall ahead is zero, up to the lock accuracy. Slide B’s offset to 180 and the heads point opposite ways; the time between their sweeps of the front wall is 50 ms, which at 3 m/s means 15 cm of motion between the two views of one wall. Turn the lock off and B’s phase lands wherever it likes.
The sensor can also send a pulse out. The multipurpose_io_mode setting selects what drives SYNC_PULSE_OUT: the internal oscillator, the incoming sync pulse, the PTP clock, or the encoder angle. In the angle mode the sensor emits a pulse every time its head passes sync_pulse_out_angle (0 to 360 degrees). Wire that pulse to a camera’s trigger input, and the camera exposes when the lidar sweeps across the camera’s view. Then the picture and the points describe the same moment, with no software pairing at all.
Two limits come from the docs. Pulses are always evenly spaced. And pulse width times frequency must stay well under one second, or the output never returns to zero. At 10 Hz rotation and a 10 ms width, the docs put the limit at 9 pulses per rotation. A concrete case from the page, in 1024x10 mode: an angle of 360 degrees gives one pulse per turn, 10 Hz; an angle of 45 degrees gives eight pulses per turn, 80 Hz.
json// Sensor B: PTP clock, phase locked 90 degrees off sensor A, and a 10 ms pulse out each time the head passes 180 degrees. // POST http://<sensor>/api/v1/sensor/config (setting names from the Ouster docs) { "timestamp_mode": "TIME_FROM_PTP_1588", "phase_lock_enable": true, "phase_lock_offset": 90000, // millidegrees "multipurpose_io_mode": "OUTPUT_FROM_ENCODER_ANGLE", "sync_pulse_out_angle": 180, // degrees, 0 to 360 "sync_pulse_out_pulse_width": 10 // ms; width x frequency must stay far below 1 s }
On the camera side, firmware captures the trigger pulse with the same input-capture trick as in Chapter 1 and stamps the frame with the capture value. That stamp, once converted with the PTP-synchronized clock, is the lidar’s clock. Fusing the two then needs no guess. The next lessons in this series cover that hardware-stamp path in depth.
On real hardware. With two lidars and a Nucleo-F446RE watching both pulse outputs on timer capture pins, set equal pulse-out angles. Print the difference between the two capture values over a minute. With the lock on, it should sit near the lock accuracy; turn the lock off and watch it wander.
Chapter 8
Read the shape of a mapping error to find which clock, pulse, sentence or path is at fault
A doctor does not treat “the patient feels bad”. She asks where it hurts, takes one reading, and only then picks a cure. Timing bugs need the same order. “The map looks wrong” has at least eight different causes, and the cures do not overlap.
Every cause in this lesson leaves a different shape. The shape depends on three things: whether the error changes with speed, whether it changes with range, and whether it repeats every second. Learn the shapes and you can name the fault before you open a log.
Test 1: stop. Park the robot and take a scan. Every error that comes from timing needs motion to show. If the room still looks wrong at rest, the fault is in the geometry or calibration, not in this lesson.
Test 2: drive straight at a steady speed. Drive past a flat wall at 1, 2 and 3 m/s and measure how far the wall shifts along the direction of travel. A clock gap shows up as a shift that grows in a straight line with speed. The slope of shift against speed is the gap in seconds. If a wall sits 9 cm off at 3 m/s, the gap is 0.09 / 3 = 30 ms.
Test 3: turn in place. Spin the robot slowly while a far wall is in view. A clock gap now shows up as a sideways shift that grows with range. The shift divided by range times turn rate gives the same gap, measured a second way. If both tests give the same gap, you have a clock gap and nothing else.
nmea_leap_seconds and write the scale in the log header.Read the symptom, then pick the most likely cause. A wrong pick tells you why it does not fit.
The symptoms are built from the numbers in this lesson (3 m/s, 100 ms scans, 37 s, 50 ms between heads). They are teaching cases, not logs from a real robot.
The drive test is also an estimator. Each run gives a pair: speed v and measured shift s. The model is s = g × v, a line through the origin with slope g, the gap. The best slope in the least-squares sense (the one with the smallest total squared miss) is the sum of s × v over the sum of v squared.
c/* Estimate the lidar-vs-pose clock gap g (seconds) from straight drives. v[i] = speed in m/s, s[i] = measured wall shift along the heading in metres. */ double estimate_gap(const double *v, const double *s, int n) { double sv = 0, vv = 0; for (int i = 0; i < n; i++) { sv += s[i] * v[i]; vv += v[i] * v[i]; } return vv > 0 ? sv / vv : 0; /* 1, 2, 3 m/s and 0.03, 0.06, 0.09 m give 0.03 s = 30 ms */ }
Use the estimate as a diagnosis, not a cure. A leftover gap that you estimate will drift as crystals warm. A pulse or PTP keeps the gap near zero for good. Log the numbers that prove it: the sensor’s lock flags, the PTP master offset, and the difference between the sensor stamp and the time your program received the packet. The last one should hold steady; if it swells whenever the CPU is busy, you are stamping late.
On real hardware. With any lidar and a wheel-odometry cart, run the three tests on a flat wall: stop, straight at three speeds, spin in place. Compute the gap both ways. If the two numbers agree within about 1 ms, you have found a pure clock gap.
Chapter 9
Keep the numbers, the checklist and the core code for a lidar whose stamps survive fusion
A spinning lidar takes 100 ms to draw one picture, so each column needs its own stamp. A stamp is useful only if it is true, and true means every clock in the robot agrees. PPS sets where a second starts. NMEA says which second it is. PTP does both over Ethernet. Phase lock makes several heads look at the same time. Motion deskew then moves every point to one moment. Time error times speed is distance.
| Quantity | Value | Where it comes from |
|---|---|---|
| Scan period, 10 Hz modes | 100 ms | Mode names, Ouster packet format page |
| Column period, 1024x10 | 97.66 µs | Derived: 100 ms / 1,024 |
| Packet rate, 512x10 / 1024x10 / 2048x10 | 320 / 640 / 1,280 per s | Ouster packet format page |
| Columns per packet | 16 | Derived from the packet rates |
| Column timestamp | 64-bit ns | Ouster packet format page |
| Timer precision | 10 ns | Ouster Time Synchronization |
| Sync pulse in rate | 1 Hz assumed | Ouster Time Synchronization |
| PPS accuracy: satellite, after overhead, kernel PPS | 50 ns, ~1 µs, ±1 µs | gpsd Time Service HOWTO |
| Receiver delay of the text | up to several hundred ms | gpsd Time Service HOWTO |
| Standard NMEA sentence, longest | 80 characters | Ouster Time Synchronization |
| TAI minus UTC in the docs | 37 s | Ouster GNSS guide (check the current value) |
| Phase lock accuracy, OS0 and OS1 | 0.5° at 10 and 20 Hz | Ouster Multi-Sensor Synchronization |
| Phase lock accuracy, OS2 | 5° at 10 Hz, 10° at 20 Hz | Ouster Multi-Sensor Synchronization |
| Phase lock loop rate; offset range | 1,000 Hz; 0 to 360,000 millidegrees | Ouster Multi-Sensor Synchronization |
| Healthy PTP lock | SLAVE, master_offset under 1 µs | Ouster PTP guide |
| Error from a time gap | speed × gap (1 ms at 3 m/s is 3 mm) | This lesson |
| Counter wrap: 32-bit µs / 64-bit ns | 71.6 min / 584 years | Derived |
$GPRMC carries the date and time.c/* A boot-time gate: refuse to record unless the whole time chain says it is healthy. */ typedef struct { bool pps_locked; /* "sync_pulse_in" locked == 1 */ bool nmea_locked; /* "nmea" locked == 1 and last sentence valid ('A') */ bool ptp_slave; /* port_state == SLAVE and gm_present */ int64_t master_offset_ns; /* from the PTP status */ bool phase_locked; /* no 0x01000050 / 0x01000051 / 0x01000024 alert */ bool uses_pps; /* otherwise PTP */ } time_chain_t; bool time_chain_ok(const time_chain_t *s, int64_t budget_ns) { bool clock_ok = s->uses_pps ? (s->pps_locked && s->nmea_locked) : (s->ptp_slave && llabs(s->master_offset_ns) < budget_ns); return clock_ok && s->phase_locked; } /* budget_ns from Chapter 3: gap_max = position_budget / (v + r * w). 1 cm at 3 m/s, 0.5 rad/s, 20 m: 0.77 ms. */
This lesson is the top of the lidar track. Below it sit the physics of time of flight, the histograms that become range, and the point packets that carry the stamps. Beside it is the general clock story in What time is it on a chip and the pin-level stamping in Timestamp at the pin. A later lesson on deterministic Ethernet covers PTP, gPTP and TSN in full.
The Ouster pages do not state a pulse width or voltage for the sync input, do not say which edge of a column its timestamp marks, and give no oscillator drift figure. Two of their sample NMEA lines do not match their own checksums, and one sample timestamp is a day after its sentence date, so we recomputed the checksum for our sentence. The leap-second count of 37 is as the docs print it. Every delay and jitter value in the devices that is not in a source is labelled illustrative.
Now press Present or Teach and explain, from memory, how a 3 m/s robot with a 10 Hz lidar gets from a tearing wall to a straight one: the column stamp, the pose at that stamp, the pulse and the sentence that fix the second, and the PTP or phase-lock settings that keep it that way. Then go back to the room at the top, put the clocks 25 ms apart, and say how far the room should slide.