A spinning lidar finds a peak in a photon histogram, packs it into 12 bytes, and sends 254 million bits every second. Turn the knobs and see where the bytes go.
Learn how a range number becomes a point: the peak, the bit fields, the timestamp, the UDP packet and the bandwidth bill your firmware and your network must pay.
Pick the rows, the scan mode and the data profile. Watch one packet redraw to scale, and watch the megabits per second move against a 100 Mbps link. Then we build it piece by piece, from the peak to the parser.
You need a picture of a histogram (a bar chart of counts) and a little C. We build the rest from zero. Part of the Firmware from Zero to Expertise series, lidar track.
Built from the Ouster firmware user manual, sections “Lidar Data” and “Coordinate System”. The page is a model: no real sensor runs in your browser. Sources.
Packet sizes follow the Ouster formula 32 + 16 × (12 + n × s) + 32 bytes. The Mbps figure is that payload times packets per second; the page’s own table lists values up to 0.1% higher. Dual return is valid in the 1024×20 and 2048×10 modes only, so choosing it moves the mode there. The 100 Mbps line is a typical Fast Ethernet link, drawn for scale.
Chapter 0
See what actually crosses the cable, and why the firmware must choose every byte of it
You bolt a spinning lidar to a robot and plug its Ethernet cable into a computer. You expect points. Nothing like a point arrives. What arrives is a steady rain of small messages, about 1,280 of them every second, each a few thousand bytes of numbers.
Each message is a packet: a small bundle of bytes with a fixed layout, sent as one unit. Think of a letter in an envelope. The envelope has a fixed shape, so the mail carrier needs no idea what is inside. The sensor’s firmware (the program that runs on the chip inside the device) fills each envelope. The software on your computer opens it.
The packets travel by UDP, the User Datagram Protocol. UDP sends a message and forgets it. It makes no handshake and never resends. That choice keeps delay low, and it puts a duty on both ends: the sender must follow the layout exactly, and the receiver must notice when a letter goes missing. Ouster’s sensors send lidar data to UDP port 7502 by default.
A spinning lidar is a ring of laser beams on a motor. Picture 128 beams stacked in a vertical line. Each beam is one row, also called a channel. The motor turns the whole stack around a vertical axis.
The motor never stops. At fixed steps of angle the sensor reads all 128 beams. One set of 128 readings at one angle is a column. A full turn is a frame (also called a scan). In the 2048×10 mode the sensor takes 2,048 columns per turn and makes 10 turns per second.
Now count. One frame holds 2,048 × 128 = 262,144 points. Ten frames per second make 2,621,440 points every second. The time between two columns is 1 s / (10 × 2,048) = 48.8 µs. Your firmware has under 49 µs to deal with each column before the next one arrives.
Every point costs bytes. In the default Ouster profile one point takes 12 bytes. So the stream is about 2.6 million points times 12 bytes, which is 31 megabytes every second, and a little more once headers are added. Chapter 7 does that sum to the last byte.
The ring is the top view of one turn. Each tick is a column. Every 16 columns the sensor seals one packet. Pick how many columns a turn has, then press Spin one turn (slowed down).
A model, slowed from 100 ms to a few seconds so you can see it. The counts are exact for a 128-row sensor at 10 turns per second with 16 columns per packet, the Ouster default. Only 512, 1024 and 2048 columns are real scan widths.
Watch the read-out. At 2,048 columns a turn, one turn seals 128 packets. At ten turns per second that is 1,280 packets every second, which matches the rate you saw at the top of the page.
For each column the firmware does five things, in this order. It finds a peak in each row’s photon histogram. It turns the peak into a range number. It measures how bright the return was. It stamps the column with a time. It writes all of that into the envelope. This lesson walks those steps one by one.
Chapter 1 starts at the histogram you met in the SPAD and TDC lesson. Chapter 2 packs one point into bits. Chapter 3 adds the clock. Chapter 4 shows how your computer turns range back into x, y and z. Chapters 5 and 6 build and parse a whole packet. Chapters 7 and 8 count the bandwidth and the losses.
One note on how packets reach memory on the receiving side. Rings, queues and drops in a host buffer are the topic of a separate real-time lesson on rings, queues and drops. Here we only need the idea: packets arrive on a schedule you cannot pause, so something must be ready to catch them.
Throughout, we use the Ouster data format as the worked example, because its manual is public and exact. Other makers use other layouts, but the same questions appear in all of them: what is in the envelope, in what order, and how many bytes.
Chapter 1
Find the peak, refine it below one bin, and measure how bright it was
Stand in a dark hall with a torch and a stopwatch. You flash the torch at a far wall and listen for the glint. Light is so fast that your stopwatch is useless. A lidar solves this with a counter that ticks every nanosecond, and it does not trust a single flash.
Here is the plan. The laser fires thousands of short pulses at one spot. The detector, a SPAD (single-photon avalanche diode, a pixel that clicks once for each particle of light), records when each click happens. Each click goes into a bin: a slot that covers a fixed slice of time, say 1 ns. The list of counts per bin is a histogram. The earlier lesson on SPADs, TDCs and histograms built it. Here we use it.
Two kinds of light fill the bins. Light from your own laser, bounced off the wall, lands in a few bins close together: the peak. Sunlight and lamps land in every bin about equally: the floor, also called the ambient level. Your job is to find the peak above the floor and say when it happened.
Light travels 299,792,458 m/s, which is 299.79 mm per nanosecond. The pulse goes out and comes back, so it covers the distance twice. That gives the one formula of the whole field:
Each nanosecond of round trip is 149.9 mm of range, about 15 cm. So a bin that is 1 ns wide cannot, by itself, tell you the range better than 15 cm. Yet the packet has a field that stores range to 1 mm. How does the firmware get there?
Take a real-looking histogram, with bins numbered from 100. The counts are 4, 9, 28, 61, 37, 10, 4. Every other bin in the window holds about 4, so the floor is 4.
The two answers differ by 13 mm, almost a whole centimetre, from a bin that is 15 cm wide. The centroid works because the wall’s light spreads over several bins. Bin 104 holds more than bin 102, so the true peak sits a little right of the centre of bin 103. The tallest-bin method throws that hint away. Try it below.
The bars are photon counts per time bin. The teal line is the true wall. Drag the ambient light up until the peak sinks into the floor. Switch the bin width and press Re-shoot for a new random histogram.
A model. Photon counts are random draws around a Gaussian pulse of 1 ns spread carrying about 130 signal photons; ambient light is counts per 1 ns. The RMS figures come from 200 shots with the wall placed at random inside one bin. The 3-spread threshold is a common rule, not a particular sensor’s setting.
Read the RMS numbers under the plot. With wide bins the tallest-bin error is large and does not shrink as you re-shoot. It is a quantization error: the answer can only land on bin centres. The centroid error is smaller because it uses the shape. When the floor rises, the centroid grows noisy too, since every bin’s random wobble leaks into the weighted average.
The same histogram gives two more numbers. The signal is the total count of photons above the floor inside the peak: 125 in our example. The NIR value (near-infrared ambient light) is the floor itself, 4 per bin. Ouster’s manual calls the first “signal intensity photons” and the second “ambient near-infrared photons”.
Signal alone is a poor measure of the wall, because a far wall returns far less light than a near one. The firmware therefore also reports reflectivity, which the manual calls “calibrated reflectivity”. It is a number, 8 bits wide, that tries to say how shiny the surface is, whatever the distance. We have no public formula for the calibration, so treat it as a lookup the factory tuned.
Now the packet. In the standard profile the range field is 19 bits wide and counts in millimetres. The largest value is 219 − 1 = 524,287 mm, so the maximum range is 524 m. The low-data-rate profile uses 15 bits and counts in steps of 8 mm. Its maximum is 32,767 × 8 mm = 262.1 m. The code is one line:
c/* range in millimetres -> 15-bit field at 8 mm per step; 0 means no detection */ static inline uint16_t range15(float mm, bool detected) { if (!detected || mm <= 0.f) return 0; uint32_t q = (uint32_t)(mm / 8.f + 0.5f); /* round to nearest step */ return q > 0x7FFF ? 0x7FFF : (uint16_t)q; /* saturate at 262.1 m */ }
Look at the trade. The 8 mm step is coarse, but it is still much finer than the 15 cm bin. That is only possible because the centroid put sub-bin detail into the number first. Peak finding decides how accurate the range is. The field width only decides how much of that accuracy survives.
The symptom: a flat wall appears as a staircase of flat steps, each 15 cm from the next. The measurement: histogram many shots of one fixed wall. The ranges pile up on a few exact values spaced one bin apart. The cause is the tallest-bin rule. The fix is the centroid, or a curve fit through the peak, which lets the answer fall between bins.
A second symptom: in bright sun, distant dark objects vanish. The floor rose, the threshold rose with it (floor + 3 spreads), and the faint peak no longer clears it. The firmware writes range 0 for those points. Chapter 2 shows the ambient level is sent along with every point, so the host can tell “nothing there” from “too bright to see”.
On real hardware. Take an nRF52840 DK or an STM32 Nucleo and a VL53L1X-class single-point ranger on a breakout board. Aim it at a flat card at 500 mm. Log 1,000 readings and plot their histogram. Then move the card 1 mm at a time and count how many different values the sensor reports.
Chapter 2
Pack range, reflectivity, signal and ambient light into three words, and read them back without error
You have five numbers for one point: a range, a reflectivity, a signal count, an ambient count, and a window count. The packet has room for exactly 12 bytes per point. Your job is to fit the numbers in, so that the receiving program, written by someone else, reads the same values back.
This is the heart of firmware work with data formats. The format is a contract. Both sides agree where each number starts, how many bits it takes, and in which order the bytes go. If the contract is off by one bit, every value is wrong and nothing warns you.
A bit is a 0 or a 1. Eight bits make a byte, which holds a number from 0 to 255. A word here means 32 bits, four bytes in a row. Ouster’s manual says its data words are 32 bits wide and little-endian.
Little-endian means the least important byte comes first. Take the number 0x3CA7, which is 15,527. In a 32-bit word it is 0x00003CA7. On the wire the four bytes go out as A7, 3C, 00, 00. Think of writing a date as day, month, year: the small unit first. The STM32 and nRF52 Cortex-M parts are little-endian too, so a uint32_t in RAM already has this order.
Inside a word we count bit positions from 0 at the right. A field written [18:0] occupies bits 0 to 18, which is 19 bits. To mask a field means to keep only those bits: word & 0x7FFFF keeps the low 19. To shift means to slide bits left or right: word >> 16 moves bit 16 down to bit 0.
The default Ouster profile is named RNG19_RFL8_SIG16_NIR16: 19-bit range, 8-bit reflectivity, 16-bit signal, 16-bit NIR. Its block is three words. Reading the page’s bit diagrams from bit 0 upward gives this layout:
| Word | Bits | Field | Meaning |
|---|---|---|---|
| 0 | [18:0] | Range | Millimetres, 0 means no detection |
| 0 | [31:19] | Reserved | Unused, 13 bits |
| 1 | [7:0] | Reflectivity | Calibrated reflectivity |
| 1 | [15:8] | Reserved | Unused, 8 bits |
| 1 | [31:16] | Signal | Signal photons |
| 2 | [15:0] | NIR | Ambient near-infrared photons |
| 2 | [23:16] | Reserved | Unused, 8 bits |
| 2 | [31:24] | Window | Raw near-range signal photons |
Count the used bits: 19 + 8 + 16 + 16 + 8 = 67. The block holds 96. The other 29 bits are reserved, left for later firmware versions. Reserved bits cost bandwidth today and buy room to grow tomorrow. Our code writes zeros there.
The window field is a health check. It counts light bounced off the sensor’s own cover glass. A high value means dirt, a smear or a crack on the window, even when the range threshold would hide it. The manual says it “indicates potential window blockage”.
Use the point from Chapter 1: range 15,527 mm, reflectivity 142, signal 125, NIR 4, window 7. Build the three words step by step.
Each square is one bit: filled for 1, empty for 0. The colours match the fields. Drag a value and watch the right bits flip. Switch to the low-rate profile and see what is lost.
Layout read from the Ouster page’s bit diagrams (word, bit positions and widths). Reserved bits are written as zero here. The low-rate NIR is the 16-bit value divided by 16 and rounded down, our reading of “scaled down 16×”. Window is fixed at 7 and, in the low-rate profile, absent.
Slide ambient up to 15 in the low-rate profile. The stored NIR stays 0. Divide 15 by 16 and you get 0.9, which rounds down to 0. The 8-bit field cannot see small ambient levels. That is the price of the profile that saves two thirds of the bandwidth: 4 bytes per point instead of 12.
c/* RNG19_RFL8_SIG16_NIR16: one channel block = three 32-bit words */ static inline void pack96(uint32_t w[3], uint32_t range_mm, uint8_t refl, uint16_t sig, uint16_t nir, uint8_t win) { w[0] = range_mm & 0x7FFFF; /* [18:0] range, rest reserved = 0 */ w[1] = (uint32_t)refl | ((uint32_t)sig << 16); /* [7:0] refl, [31:16] signal */ w[2] = (uint32_t)nir | ((uint32_t)win << 24); /* [15:0] NIR, [31:24] window */ } static inline uint32_t range_of(const uint32_t w[3]) { return w[0] & 0x7FFFF; } static inline uint8_t refl_of(const uint32_t w[3]) { return w[1] & 0xFF; } static inline uint16_t sig_of(const uint32_t w[3]) { return w[1] >> 16; }
Notice the casts to uint32_t before every shift. Without them, a uint8_t or uint16_t is promoted to a signed int, and shifting a bit into the sign position (bit 31) is not defined by the C standard. The result may work on one compiler and fail on another.
The symptom: every range reads as a huge number, or reflectivity looks like noise. The measurement: write one known point, the vector above, and print the 12 bytes. Compare them with A7 3C 00 00 8E 00 7D 00 04 00 00 07, byte by byte. The first byte that differs names the bug: a wrong mask, a wrong shift, or swapped byte order.
The fix: keep that vector as a unit test that runs on your PC, with no hardware. A format bug that ships to a million sensors costs far more than a ten-line test.
On real hardware. On an STM32 Nucleo, fill a uint32_t w[3] with the vector above and send the 12 bytes over the ST-LINK virtual serial port at 115200 baud. Capture with a terminal logger and check the bytes. Then change the compiler flag from -O0 to -O2 and confirm the output does not change.
Chapter 3
Read the 12-byte column header: a 64-bit time, a column number and a validity bit
Your robot drives forward at 1 m/s and the lidar spins at 10 turns per second. One turn takes 100 ms. In that time the robot moves 10 cm. The first points of the turn were measured from one place, the last points from a spot 10 cm further on. If you pretend the whole turn happened in one instant, a flat wall comes out bent.
The cure starts in the packet. The sensor must say when each point was measured, and where the motor was pointing. Both live in the column header, a 12-byte block that comes before the channel blocks of each column. Ouster’s manual lists its three fields.
Timestamp. A 64-bit count of nanoseconds, stored as two 32-bit words: the low half first, then the high half. A timestamp is a number from a clock that ticks steadily. It means nothing alone. It means something when you compare two of them: their difference is the time between the events.
Why 64 bits? A 32-bit counter of nanoseconds wraps back to zero after 232 ns = 4.29 s. A 64-bit counter lasts 264 ns, about 584 years. If you keep only the low word, your timestamps jump backwards every 4.29 s. The code that joins the halves is one line, but it is easy to forget:
c/* column header: 12 bytes = 3 little-endian words */ typedef struct { uint32_t ts_lo; /* word 0: timestamp [31:0], ns */ uint32_t ts_hi; /* word 1: timestamp [63:32], ns */ uint32_t id_sta; /* word 2: [15:0] measurement ID, [16] STA, rest reserved */ } col_hdr_t; static inline uint64_t col_time_ns(const col_hdr_t *h) { return ((uint64_t)h->ts_hi << 32) | h->ts_lo; } static inline uint16_t col_id(const col_hdr_t *h) { return h->id_sta & 0xFFFF; } static inline bool col_valid(const col_hdr_t *h) { return (h->id_sta >> 16) & 1; }
Measurement ID. The column number, from 0 up to the scan width minus one: 511, 1023, 2047 or 4095, depending on the mode. It is 16 bits wide, so it fits. This number is the motor’s angle in disguise. Column 0 is at the zero-angle mark. Column 512 in a 1,024-column mode is half a turn later.
Status (STA). One bit. 1 means the column holds valid data. 0 means the column was dropped, or the sensor masked this azimuth on purpose. When STA is 0, the channel blocks are not meant to be used, so the host must skip them.
Two small formulas turn the header into physics. The first is from Ouster’s coordinate-system page. The encoder angle θenc (the motor angle in radians) falls as the measurement ID rises, because the sensor scans clockwise seen from above:
The second is plain division. If a turn lasts 1/f seconds and holds W columns, then each column lasts 1/(f × W) seconds, and column id is measured id/(f × W) seconds after column 0.
Work one case. The width is 1,024, the rate is 10 turns per second, and we read column 768. Each column lasts 97.66 µs. Column 768 comes 768 × 97.66 µs = 75.0 ms after column 0. Its angle is 360° × (1 − 768/1024) = 90°. A packet of 16 columns covers 16 × 97.66 µs = 1.56 ms of the turn.
The ring shows where the motor points. The bar shows how far into the turn we are. Drag the column number. Toggle STA to mark a column as dropped.
The start time of the turn (1,000,000,000,000 ns, 1,000 s after power-up) is made up for the demo. The division into columns and the angle formula follow the Ouster manual. The page gives one timestamp per column; any finer offset between rows of one column is not part of this packet.
Change the mode to 2,048 and the same angle needs twice the column number. The header always holds a column index, never an angle. Only the scan width tells you what the index means.
Look at the layout again. The packet holds one timestamp for each column, not for each point. All 128 points in a column share it. The host gives each point the time of its column. That is what a “per-point timestamp” means for this sensor, and it is a good bargain. It costs 12 bytes for 128 points instead of 8 bytes for each one, which would add 1,024 bytes to every column.
How wrong is that? If the rows of a column are read within that column’s time slot, the error inside one column is below one column time, 48.8 µs in the 2,048-column mode. A robot at 1 m/s moves 0.05 mm in that time. That is nothing. But stamping the whole frame with the first column’s time is wrong by up to 100 ms, which is 10 cm of motion at 1 m/s.
Turning is worse. A robot that spins at 90° per second turns 9° during one 100 ms frame. At a range of 15 m, 9° shifts a point sideways by 15 m × sin 9° = 2.3 m. The next lesson in this track, on lidar timing and sync, fixes that with each column’s own timestamp, a method called deskewing (PPS, NMEA, PTP and motion deskew).
The symptom: the point cloud has a seam, a vertical slice where the wall jumps by a few centimetres. The measurement: print the measurement ID and the timestamp for the last column of one frame and the first column of the next. They should differ by exactly one column time. If they differ by 100 ms or more, columns went missing in between. If the timestamps go backwards every 4.29 s, you read only the low word. The fix for the second is the 64-bit join shown above.
On real hardware. On an STM32 Nucleo, run a timer at 1 MHz and read it in a GPIO interrupt from a pulse generator at 10 kHz. Print the difference between successive reads. It should sit at 100 µs with a few microseconds of spread. That is the same measurement the lidar makes for its columns, in miniature. The timer lesson in the core course (timers, PWM and sampling) shows how.
Chapter 4
Turn a row, a column and a range into a point in space, using two angles and a little trigonometry
The packet says: row 17, column 768, range 15,527 mm. That is an address and a distance. It is not a place. To draw the point you must know where row 17 looks and where column 768 points. Neither is in the packet.
The sensor keeps that knowledge in its own metadata, and your host asks for it once. Ouster serves it over HTTP at /api/v1/sensor/metadata/beam_intrinsics. It holds, for each row, a beam altitude angle (how far the beam tilts above or below the horizon) and a beam azimuth angle (a small sideways offset, because the beams do not sit in one perfect vertical line).
So two things are fixed at the factory and read once: the angle table, and a small offset between the point where the sensor measures range from and the middle of the motor. Everything else comes from the packet: which row, which column, how far.
Imagine standing at the origin with a laser pointer. You know three things: how far the dot is, how high you tilted the pointer (the altitude angle φ), and how far you turned around (the azimuth angle θ). Where is the dot?
With no offsets the three lines are all you need. Ouster’s page adds the offsets and the scan direction. Here are its formulas, in the sensor’s Lidar frame.
Read the shape of it. The part with (r − n) is the spherical-to-Cartesian recipe above. The part with n moves the starting point from the motor axis to the beam’s origin, turned to the encoder angle. If n were 0, the formula would shrink to the three lines you just did.
Take column 768 of 1,024, so θenc = 2π (1 − 0.75) = 90°. Take a beam with altitude +10° and azimuth offset 0. Take r = 15,527 mm and n = 0.
Check by length: √(0 + 15,291² + 2,696²) = 15,527. The point is back at the range we started with.
Left: the view from above. Right: the view from the side. The ring is every column at your range and altitude. Drag the column to walk around it, tilt the beam, and stretch the range.
Illustrative: the altitude range of ±22.5° and the offset n are chosen for the demo; a real sensor has one angle per row from its own metadata. The beam azimuth offset is 0. The formulas are the Ouster coordinate-system page’s, with b03 = n and b23 = 0.
Set n to 60 mm and watch what changes. The point moves by only a few millimetres at 15 m. But close to the sensor, at 1 m, the same 60 mm is a large share of the range. That is why the metadata carries the offset at all: it is small, and it matters most for near objects.
Computing sines and cosines for 2.6 million points per second is work. Real drivers do not call sin for every point. They precompute a lookup table (LUT): for every row and column, the three factors that do not depend on range. Then each point costs three multiplies and an add.
c/* built once per sensor mode: rows x cols entries of unit direction * and an offset */ typedef struct { float dx, dy, dz, ox, oy; } lut_t; void build_lut(lut_t *L, int rows, int W, const float *alt_deg, const float *az_deg, float n_mm) { for (int id = 0; id < W; id++) { float enc = 2.f * M_PI * (1.f - (float)id / W); for (int row = 0; row < rows; row++) { float az = -2.f * M_PI * az_deg[row] / 360.f; float phi = 2.f * M_PI * alt_deg[row] / 360.f; lut_t *e = &L[id * rows + row]; e->dx = cosf(enc + az) * cosf(phi); e->dy = sinf(enc + az) * cosf(phi); e->dz = sinf(phi); e->ox = n_mm * cosf(enc); e->oy = n_mm * sinf(enc); } } } /* per point: range 0 means no detection, skip it */ static inline bool to_xyz(const lut_t *e, uint32_t r_mm, float n_mm, float out[3]) { if (r_mm == 0) return false; float d = (float)r_mm - n_mm; out[0] = d * e->dx + e->ox; out[1] = d * e->dy + e->oy; out[2] = d * e->dz; return true; }
Size the table. For 128 rows and 2,048 columns it holds 262,144 entries of five floats, 20 bytes each: 5.2 MB. That fits on a PC, and does not fit in the SRAM of a small microcontroller. This is one reason the sensor sends range and leaves x, y, z to the host.
The symptom: a dense ball of points sits exactly at the sensor, and the real scene looks thinned out. The measurement: count points within a few centimetres of the origin. Hundreds of thousands means the host converted points with range 0. The packet said “no detection” and the code turned it into a point at the origin. The fix is the single if (r_mm == 0) above. A second symptom is a scene that looks tilted or mirrored. Swap the sign of the azimuth term, or mix degrees with radians, and you get exactly that. Test with a flat wall at a known distance.
On real hardware. With a Nucleo and a small servo on a pan-and-tilt bracket carrying a single-point ranger, step through 20 pan and 5 tilt angles over a flat wall 500 mm away. Convert each reading with the three lines of the spherical recipe. The cloud should be a flat sheet at y = 500 mm. Any curve you see is an angle or unit mistake.
Chapter 5
Wrap 16 columns in a header and a footer, and compute the byte count before you send anything
You now have points and column headers. One column of 128 points is 12 + 128 × 12 = 1,548 bytes. Do you send it alone? A UDP packet has its own costs: headers added by the network stack, a system call to send it, an interrupt to receive it. Sending 20,480 tiny packets per second would waste most of the effort on envelopes.
So the sensor groups columns. By default Ouster puts 16 columns in one packet (the OS1-MAX, which has 256 rows, uses 8). The group gets one header in front and one footer behind.
The packet header is 256 bits, eight 32-bit words. In the standard layout, these fields carry the facts the host needs before it reads one point:
| Field | Where | What the host does with it |
|---|---|---|
| Packet type | word 0, [15:0] | 0x01 means lidar. Anything else is not a lidar packet. |
| Frame ID | word 0, [31:16] | Low 16 bits of the scan index. It rises at each zero-azimuth crossing. Packets with the same ID belong to the same turn. |
| Init ID | word 1, [55:32] | Changes at every reinit or reboot. A change tells the host to fetch fresh metadata. |
| Serial number | 40 bits over words 1 and 2 | Tells apart several sensors on one network. |
| Alert flags | word 3, [103:96] | Alert cursors, a cursor-overflow bit and an alerts-active bit. |
| Countdowns and levels | word 4 | Thermal shutdown and shot limiting. Each countdown reads 30 when the event is imminent and 0 otherwise. |
Why spend 32 bytes on this? Each field answers one question a receiver cannot guess. Is this my packet type? Which turn does it belong to? Did the sensor restart so that my angle table is stale? Which of my three sensors sent it? The shot-limiting and thermal fields tie back to the eye-safety lesson: the sensor tells the host when it is limiting its laser shots or heading for a thermal shutdown.
There is also a second layout, FUSA (functional safety), with a 32-bit frame ID and an extra safe-state byte. This lesson uses the default STANDARD layout. The packet-type byte sits in the same place, but the other fields move, so check header_type before parsing.
The footer is also eight words. In the standard layout words 0 to 5 are reserved, and words 6 and 7 hold a 64-bit CRC, a cyclic redundancy check. A CRC is a short number computed from every byte before it. The receiver computes it again. If one bit flipped on the way, the two numbers disagree. Chapter 6 computes it for you.
Now put the pieces together. For n rows (pixels_per_column) and a channel block of s bytes, with 16 columns:
Check it against the manual’s own example. For the 32-row sensor with s = 12, the inside is 12 + 32 × 12 = 396. Sixteen columns make 6,336. Add 64 bytes of header and footer: 6,400. The manual lists 6,400.
Try the 64-row sensor, standard. The inside is 12 + 64 × 12 = 780. Sixteen columns make 12,480. Add 64: 12,544. The manual lists 12,544. Try the OS1-MAX, which uses 8 columns and 256 rows: 32 + 8 × (12 + 256 × 12) + 32 = 24,736. The manual lists that too.
Three rulers, each a zoom of the one above: the packet, one column, one channel block. Change the rows and the profile, and compare the size with the number in Ouster’s table.
Sizes come from the Ouster formula, and the manual’s table is built in for the check: 32 rows 6,400 / 8,448 / 2,304 / 4,352; 64 rows 12,544 / 16,640 / 4,352 / 8,448; 128 rows 24,832 / 33,024 / 8,448 / 16,640 (standard, dual, low rate, low rate dual). Rulers are to scale within each level.
All twelve numbers in the manual’s table fit the formula. That is the point of a formula: you can compute the size of a format you have never seen, and notice when a packet on the wire disagrees.
The symptom: your parser works on the 32-row sensor and prints garbage on a 64-row one. The measurement: print the UDP payload length and compare it with the formula. 12,544 bytes arrive and your code assumed 6,400. The cause is a size written into the code as a constant. The fix: read the row count, columns per packet and profile from the sensor’s metadata once, compute the expected size, and drop any packet that does not match.
On real hardware. Use an STM32 Nucleo with Ethernet (for example a NUCLEO-F429ZI) or any laptop with Wireshark. Capture ten seconds of any UDP stream. Compare the payload length of every packet with what the sender’s format says. One packet of the wrong length is the first sign of trouble.
Chapter 6
Walk the bytes with offsets, check the CRC, and write a packet that a parser accepts
A packet arrives: 6,400 bytes in a buffer. You want the range of row 3 in column 5. Where is it? You do not search. You compute. A fixed layout lets you jump straight to any byte, because every size is known in advance.
Here are the offsets for the 32-row, standard-profile packet. The header takes bytes 0 to 31. Each column is 12 + 32 × 12 = 396 bytes long, so column k starts at 32 + 396k. Inside a column, the channel blocks begin after its 12-byte header, and row j starts 12 + 12j bytes in.
For column 5, row 3: 32 + 5 × 396 = 2,012 is the column start. Add 12 for its header and 3 × 12 = 36 for the rows: byte 2,060. The first word there, read little-endian and masked to 19 bits, is the range. The device below does this arithmetic on real bytes.
A parser that trusts its input is a bug waiting for a stray packet. The network may deliver a packet from another device, a cut-off packet, or a damaged one. Check in this order:
The CRC deserves one more word. A CRC treats the packet as one huge number and divides it by a fixed polynomial. The remainder is the check value. Ouster’s parameters are: width 64, polynomial 0x42F0E1EBA9EA3693, initial value all ones, input and result reflected, final XOR all ones. It covers the payload without its final 64 bits, and it is stored little-endian, so you reverse the last eight bytes before comparing, or compare as a little-endian integer. We checked our code against the standard test string “123456789”, which must give 0x995DC9BBDF1939FA for these parameters.
Pick a sample packet or build your own wall. Choose a column and a row. The hex shows the header, the column header, the channel block you chose, and the footer. Press Flip one bit and watch the CRC catch it.
The sample is not a capture from a real sensor. This page built it with the same code you see below: a 32-row, 16-column, standard-profile packet of a wall at 8 m with a nearer pillar and a floor, and a made-up serial number. The layout and the CRC follow the Ouster manual. The hex shows 12 bytes of the chosen block; the bit flip is bit 18 of its range, worth 262.1 m.
Flip a bit and look at the state. The parse of every field still looks fine. Only the CRC says the packet is bad. Without it, a flipped bit in a range byte would move one point by up to 262 m and no one would know.
The builder is the parser run backwards. Write the header, then 16 columns, then compute the CRC over everything and write it last. The order matters: the CRC covers the footer’s reserved words, so you fill those first and the CRC last. On a sensor, this code runs on the firmware side. On the host it runs in your tests, where it lets you make known-good and known-bad packets without any sensor.
c/* CRC-64 with the Ouster parameters: poly 0x42F0E1EBA9EA3693, init and xorout all ones, reflected */ static uint64_t crc_tab[256]; void crc64_init(void) { for (int i = 0; i < 256; i++) { uint64_t c = i; for (int k = 0; k < 8; k++) c = (c & 1) ? (c >> 1) ^ 0xC96C5795D7870F42ULL : c >> 1; /* reflected poly */ crc_tab[i] = c; } } uint64_t crc64(const uint8_t *p, size_t n) { uint64_t c = ~0ULL; while (n--) c = crc_tab[(c ^ *p++) & 0xFF] ^ (c >> 8); return ~c; } /* parse one lidar packet; returns 0 on success */ int parse_packet(const uint8_t *b, size_t len, int rows, int s, pkt_t *out) { const size_t col_sz = 12 + (size_t)rows * s; if (len != 64 + 16 * col_sz) return -1; /* 1. length */ uint32_t w0 = rd32(b); /* little-endian read */ if ((w0 & 0xFFFF) != 0x01) return -2; /* 2. type */ if (crc64(b, len - 8) != rd64(b + len - 8)) return -3; /* 3. CRC */ out->frame_id = w0 >> 16; out->init_id = rd32(b + 4) & 0xFFFFFF; /* 4. init ID: [55:32] */ for (int k = 0; k < 16; k++) { const uint8_t *col = b + 32 + k * col_sz; out->ts[k] = rd64(col); /* ns, 64 bit */ out->id[k] = rd32(col + 8) & 0xFFFF; out->valid[k] = (rd32(col + 8) >> 16) & 1; /* 5. STA */ if (out->valid[k]) unpack_blocks(col + 12, rows, &out->pts[k]); } return 0; }
The symptom: the parser rejects about one packet in a thousand, and the cloud shows thin missing slices. The measurement: log the reason code of each rejection. If most are −3 (CRC), the network corrupts or truncates packets. If most are −1 (length), a switch or a driver is cutting packets, often a sign of a path that cannot carry them whole (Chapter 7). The fix depends on the cause, but only the log can tell you which one it is.
On real hardware. Run the builder and CRC code on an STM32 Nucleo. Print the CRC of “123456789” to a serial terminal. It must read 995DC9BBDF1939FA. Then build the sample packet, send it to the PC over UART, and have a Python script run the parser. If both sides agree on every field, your layout is right.
Chapter 7
Count megabits per second from rows, columns and profile, then see what the network adds
Your lidar works on the bench. You plug it into a 100 Mbps port on an old switch, and the point cloud stutters. Nothing is broken. The cable simply cannot carry the stream. A firmware engineer must be able to say, before anyone plugs anything in, how many bits per second a mode needs.
Bandwidth is how many bits a link carries each second. The unit is the megabit per second, Mbps. Three numbers give it.
For the 128-row sensor in the standard profile, the packet is 24,832 bytes. So 24,832 × 1,280 × 8 = 254.3 million bits per second. Ouster’s table lists 254.32 Mbps for this case. Our figure is a hair lower, 0.02%. We take the manual’s number as the reference and our sum as the check.
The same sum works for every case in the manual. The rate table shows that 512×10 gives 320 packets per second, and 1024×10 or 512×20 give 640. The reason is simple: the packet rate depends only on columns per second, never on rows. Rows change the size of each packet, not how many there are.
The packet sizes above are the UDP payload. The network wraps it. UDP adds 8 bytes. IPv4 adds a 20-byte header. Ethernet adds a 14-byte header, a 4-byte check, and, on the wire, an 8-byte preamble and a 12-byte quiet gap: 38 bytes per frame in all.
Now the larger problem. An Ethernet frame normally carries at most 1,500 bytes of IP data. That limit is the MTU, the maximum transmission unit. Our packet is 24,832 bytes. It cannot fit. So the IP layer cuts it into fragments. Each fragment except the last carries a multiple of 8 bytes of data: 1,480 at MTU 1,500. Each fragment gets its own IP header and its own Ethernet frame.
Work it. The UDP datagram is 24,832 + 8 = 24,840 bytes. Divide by 1,480: 16.8, so 17 fragments. Overhead is 17 × (20 + 38) = 986 bytes, and the wire carries 25,826 bytes per packet. At 1,280 packets per second that is 264.5 Mbps, 4.0% above the payload rate. On a 1 Gbps link this uses 26% of capacity. On a 100 Mbps link it is 2.6 times too much.
The top strip shows one packet cut into fragments. The bars show the data rate and the rate on the wire, against 100 Mbps and 1 Gbps links. Drag the rows and the azimuth columns.
Payload rate = packet bytes × packets per second × 8 (the manual’s table is up to 0.1% higher). Wire rate adds UDP 8 B, and per fragment an IPv4 header of 20 B and 38 B of Ethernet framing (14 header, 4 check, 8 preamble, 12 gap). Jumbo frames only help if every device on the path supports them. Dual return is valid only in 1024×20 and 2048×10.
Set the MTU to 9,000. The 128-row packet now needs 3 fragments, not 17, and the wire rate drops from 264.5 to 256.1 Mbps. The gain is small, 3%. The larger gain is elsewhere: fewer frames means fewer interrupts and fewer chances for a fragment to go missing (Chapter 8).
Bandwidth is only half of the load. The packet rate sets the schedule. At 1,280 packets per second, one packet leaves the sensor every 0.78 ms. The firmware that feeds the Ethernet MAC (the hardware block that sends frames) has 0.78 ms to build each packet. For an FPGA or a microcontroller with DMA, that budget is generous. For a receiving computer, it means about 1,280 packet events per second to handle, and with fragments at MTU 1,500, 21,760 frames per second.
The symptom: on a 100 Mbps port, the cloud stutters and up to about 60% of the data never arrives. The measurement: ask the network card for its speed (ethtool eth0 on Linux reports it) and compare it with the wire rate from this chapter. If the wire rate is near the link speed or above it, you are already in trouble. The fix: use a gigabit port, or drop to a smaller profile, fewer rows or fewer columns. All three are firmware choices.
On real hardware. Use an STM32 Nucleo with Ethernet or an RP2040 board with an Ethernet module. Send fixed-size UDP datagrams of 1,400 bytes at a chosen rate to a laptop. Run iperf3 -u -b on the laptop for the receiving side. Raise the rate until the laptop reports loss. That rate, converted to Mbps, is the limit of the chain from your firmware to the application.
Chapter 8
Detect a gap from the counters in the packet, and see why one lost fragment costs a whole packet
A UDP sender does not wait to be asked and does not look back. If a packet is lost, no one says so. Your robot simply sees a wedge of the world vanish for one frame. A well-built system notices, counts it, and carries on. This chapter shows how.
You already met the counters. Each packet holds 16 columns with consecutive measurement IDs. So if one packet starts at column 768, the next should start at 784. In a 1,024-column mode the IDs wrap: after 1,008 comes 0. A single test finds a gap:
c/* W = scan width (power of two); call once per good packet, with the ID of its first column */ static int prev_first = -1; int packets_missed(int first_id, int W) { if (prev_first < 0) { prev_first = first_id; return 0; } int step = (first_id - prev_first) & (W - 1); /* wraps correctly */ prev_first = first_id; return step / 16 - 1; /* 0 when nothing is missing */ } /* assemble a frame: columns land at their measurement ID; holes stay at range 0 */ void on_packet(const pkt_t *p, frame_t *f) { if (p->frame_id != f->frame_id) { emit(f); frame_reset(f, p->frame_id); } for (int k = 0; k < 16; k++) { if (!p->valid[k]) continue; /* STA = 0: dropped or masked */ copy_column(f, p->id[k], &p->pts[k]); f->filled++; } }
At the end of a frame, f->filled says how many of the W columns arrived. A healthy frame has all of them. A missing packet shows up as 16 columns short, a wedge of 16/2,048 × 360° = 2.8° in the 2,048-column mode. The frame ID wraps at 65,536 turns, which at 10 turns per second takes 109 minutes, so compare it only to its neighbour.
Two other signals help. The column STA bit tells you that the sensor dropped a column or masked it on purpose, which is different from the network losing it. And a change in init ID tells you the sensor rebooted, so the frame count restarted.
Chapter 7 showed that one 24,832-byte packet travels as 17 Ethernet frames. Now ask what happens when one of them is lost. The receiving IP layer collects the fragments and rebuilds the datagram. With one fragment gone, it cannot. It waits, gives up, and throws away the other 16. The whole 16 columns are gone.
The math is a small piece of probability. If each frame is lost with chance p, the datagram survives only if all F fragments survive. That has chance (1 − p)F. So the datagram is lost with chance 1 − (1 − p)F. Take p = 0.1%:
The loss rate of the link is the same. The loss rate of packets is 17 times higher. This is one reason a sensor with big packets can lose more data than the link loss alone suggests, and why smaller packets or jumbo frames help. RFC 791 also says there are no retransmissions, so the sender never learns of the loss.
The other big source is not the cable but the computer. Packets arrive on a schedule you cannot pause. They wait in the operating system’s receive buffer until your program reads them. If your program stalls, for a garbage-collection pause, a busy disk, or a thread that was not scheduled, the buffer fills and new packets are dropped. The rings, queues and drops of a host buffer are the topic of a separate lesson in the real-time series; here is the sum that matters.
A common Linux default for the socket receive buffer is 212,992 bytes. One 24,832-byte packet is about a ninth of that, so the buffer holds roughly 8 packets. At 1,280 packets per second, 8 packets last 6.25 ms. A stall longer than that loses data. The same logic applies to a ring buffer inside a microcontroller that receives the data: its depth, divided by the packet rate, is how long your code may go away.
Each row below is one frame (one turn). Each cell is one packet. Red cells are lost. Once a second the host program stalls. Make the buffer deeper, the stall shorter, or the link cleaner, and watch the holes close.
A model: 128 rows, 2048×10 standard profile, 1,280 packets per second, 128 packets per frame, 17 Ethernet frames per packet. The host reads a packet in 0.2 ms except during a stall that starts at 0.5 s of each second. Frame losses are random draws with a fixed seed, so the same settings give the same picture.
Set the loss per frame to zero and the stall to 10 ms with a buffer of 8. Each second still loses about 5 packets: during a 10 ms stall about 13 packets arrive and the buffer holds 8. Now raise the buffer to 16. The stall disappears from the picture. A buffer costs memory. A stall costs data. The two numbers have to match the real worst-case pause of your program, which you must measure, not guess.
The symptom: wedge-shaped holes in the point cloud, always at the same moment of each second. The measurement: log packets_missed() with the time. If the gaps repeat every second at the same offset, a periodic task on the host (a logger, a garbage collector, a timer) is stalling the reader. If they are random, look at the link, and at fragments. The fix for the first: a dedicated receiving thread at real-time priority that does nothing but empty the socket (see the lesson on real-time Linux) and a deeper buffer. The fix for the second: fewer fragments.
On real hardware. On a Nucleo with Ethernet, send numbered UDP packets at 1,280 per second to a laptop. In the laptop program, add a 10 ms sleep once per second. Count the gaps in the numbers. They will be about 13 per second until you enlarge the socket buffer, then fall to zero. For the host side of real-time scheduling, see also robot real-time performance.
Chapter 9
Keep the numbers, the checks and the code, and know where to go next
One point travels a long road. Photons pile into histogram bins. A peak finder turns the bins into a range with sub-bin detail. The firmware packs range, reflectivity, signal and ambient light into 12 bytes. It stamps the column with a 64-bit time and a column number. Sixteen columns go into a packet with a header and a CRC. UDP sends 1,280 such packets every second. The host checks, unpacks, and turns range into x, y and z.
| What | Value | Source or sum |
|---|---|---|
| Range per ns of round trip | 149.9 mm | c × 1 ns / 2 |
| Range field, standard profile | 19 bits, 1 mm, max 524 m | Ouster Lidar Data |
| Range field, low data rate | 15 bits, 8 mm, max 262 m | Ouster Lidar Data |
| Channel block | 4, 8, 12 or 16 bytes | Ouster Lidar Data |
| Column header | 12 bytes | 64-bit ns timestamp, 16-bit ID, STA bit |
| Packet header and footer | 32 + 32 bytes | CRC-64 in the last 8 bytes of the footer |
| Columns per packet | 16 (OS1-MAX: 8) | Ouster Lidar Data |
| Packet size | 32 + 16 × (12 + n × s) + 32 | 128 rows, 12 B: 24,832 bytes |
| Packet rate, 2048×10 | 1,280 per second | 20,480 columns per second / 16 |
| Data rate, 128 rows, standard | 254.3 Mbps | manual: 254.32 |
| Fragments at MTU 1500 | 17 per packet | 24,840 / 1,480, rounded up |
| Wire rate with framing | 264.5 Mbps | 25,826 B × 1,280 × 8 |
| Time per column, 2048×10 | 48.8 µs | 1 s / 20,480 |
| Default UDP port | 7502 | Ouster Lidar Data |
c/* the whole chapter in the fewest lines: size, rate, and a sanity check */ static inline uint32_t pkt_bytes(int rows, int s) { return 32 + 16 * (12 + rows * s) + 32; } static inline double pkts_per_sec(int W, int hz) { return (double)W * hz / 16.0; } static inline double mbps(int rows, int s, int W, int hz) { return pkt_bytes(rows, s) * pkts_per_sec(W, hz) * 8.0 / 1e6; } /* unit tests, no hardware needed */ assert(pkt_bytes(32, 12) == 6400); assert(pkt_bytes(64, 12) == 12544); assert(pkt_bytes(128, 12) == 24832); assert(pkt_bytes(128, 4) == 8448); assert(mbps(128, 12, 2048, 10) > 254.2 && mbps(128, 12, 2048, 10) < 254.4);
Every device here is a model that runs in your browser. No sensor, no real Ethernet and no firmware runs on your computer. The bit layouts, sizes, formulas and CRC parameters come from the Ouster manual. The photon histogram, the sample packet, the scene, the serial number and the host stall are made up to teach, and the device notes say so. Other lidar makers use other layouts. The questions you ask of them are the same.
Now press Teach and explain from memory how one range number gets from a histogram to a point in space: the peak, the 19 bits, the column header, the 24,832 bytes, the 1,280 packets and the 17 fragments. Then go back to the sizing dial at the top and predict the megabits per second before you touch it.