In our model, a cover glass in front of a time-of-flight sensor makes a wall look 18 mm away. Learn the driver, the crosstalk calibration and the offset fit that fix it.
Write the firmware for three cheap distance sensors: a multizone light sensor, an ultrasonic module and a millimetre-wave radar chip. Learn what each one measures, how to read it, and how to make it tell the truth.
Pick Cover glass and drag the wall away. Ghost zones appear. Then press Calibrated and watch them go. After that we build, piece by piece, everything the chip does inside.
You need a little C and the idea of a driver that talks to a chip over a bus. We build the rest from zero.
Part of the Firmware from Zero to Expertise series. Built from the ST VL53L5CX datasheet and user manual UM2884, the HC-SR04 datasheet and TI’s “The fundamentals of millimeter wave radar sensors”. Full list in the Field Guide.
A model, not a chip. The 8 by 8 zones, the 63 degree field of view and the 88% and 17% target reflectances come from the VL53L5CX datasheet. The signal law, the crosstalk level and the glass distance are illustrative numbers chosen to show the effect.
Chapter 0
See why a distance sensor that works on the bench can lie once you put it in a robot
A small delivery robot rolls down a hallway. On its front bumper sit three cheap parts. One is a multizone time-of-flight sensor, a chip that sends out invisible light and measures how long it takes to come back, in 64 directions at once. One is an ultrasonic module, which sends a click of sound and listens for the echo. One is a millimetre-wave radar chip, which sends radio waves with a frequency that sweeps up and down.
All three answer the same question: how far away is the thing in front of me? Each part costs a few dollars to a few tens of dollars. On the bench, each one works the first time.
Then the mechanical team adds a clear plastic window over the front, to keep dust out. The robot starts to stop for walls that are not there. The light sensor can report an object about 18 mm away in its dim zones (the 18 mm is an illustrative number from our model). Nothing is wrong with the chip. The window is bouncing a little of the sensor’s own light straight back into it.
This lesson is about that gap between a part that works and a part that works in your product. The gap belongs to the firmware. Firmware is the program that runs on the small processor (a microcontroller) inside the robot. It must start each sensor, read it on time, throw away readings that cannot be trusted, and apply the calibration that makes the numbers true.
A driver is the piece of firmware that hides a chip behind a few plain functions. The rest of the program says “give me the latest distances”. It never touches a register. You met the idea in From Register Map to Driver. For a ranging sensor the driver has four jobs:
The instrument at the top of the page is a model of the light sensor. It has 8 by 8 zones, like the real VL53L5CX. The scene is a wall, with a box in front of it. Choose Cover glass now and watch what happens as you drag the wall away. Zones turn red and report 18 mm. That is the glass, not the wall.
Look at which zones fail first. They are at the corners, where the returning light is weakest. A weak wall signal loses to the strong glass signal. This is the whole lesson in small: the sensor reports the strongest thing it sees, and a window is a very strong thing.
We take the sensors from simplest to richest. Sound first, because its physics is one line. Then light, which adds zones and a histogram. Then the radar, which adds a new idea: measuring distance as a frequency. In between, we study the failure that matters most in a product: crosstalk.
Chapter 1
Turn a pulse width into a distance, and see how a cold morning moves the answer
Stand at the mouth of a canyon and clap once. Count the seconds until the echo comes back. Say it takes two seconds. The sound went to the far wall and returned, so the wall is one second of sound away. You never needed a ruler. You needed a clock and the speed of sound.
An ultrasonic ranging module does exactly this with a pulse too high to hear. The popular HC-SR04 has two small metal cans on its face. One is a loudspeaker for 40 kHz sound (40,000 cycles per second). The other is a microphone tuned to the same pitch. A small circuit between them does the timing for you.
The datasheet describes three steps. First, your firmware holds the Trig pin high for at least 10 microseconds. Second, the module sends a burst of eight 40 kHz cycles. Eight cycles at 40 kHz last 200 microseconds. Third, if an echo returns, the module raises the Echo pin and holds it high. The width of that pulse is the time the sound took to go out and come back.
So the part turns a distance into a pulse width. Your job is to measure that width with a timer. The datasheet gives the conversion: the width in microseconds divided by 58 is the distance in centimetres. It also gives the long form: distance = high time × 340 m/s ÷ 2.
0.0116 s × 343 m/s ÷ 2 = 1.99 m (an echo of 11.6 ms at room temperature)
Sound goes 1 cm in about 29 microseconds, so a round trip to a target 1 cm away takes about 58. That fits a speed near 345 m/s. The same datasheet also quotes 340 m/s, which gives 58.8. The two numbers agree to about 1.4%. This is a hint to read a datasheet as a rounded guide, not as a spec.
The bigger point is that the speed of sound changes with temperature. For dry air the standard ideal-gas formula is c = 331.3 × sqrt(1 + T / 273.15) metres per second, with T in degrees Celsius. At 0 °C that gives 331.3 m/s. At 20 °C it gives 343.2 m/s. At 35 °C it gives 351.9 m/s.
Work one case with every step. A wall stands 200 cm away on a freezing morning, 0 °C. The round trip is 4 m. At 331.3 m/s the echo takes 4 ÷ 331.3 = 12.07 ms, or 12,073 microseconds. A driver that divides by 58 reports 12,073 ÷ 58 = 208.2 cm. It is 8.2 cm too far, a 4.1% error. Now take the same wall at 35 °C. The echo takes 4 ÷ 351.9 = 11.37 ms. Dividing by 58 gives 196.0 cm, which is 4.0 cm too near.
The top ruler shows the true distance (blue) and what the driver reports (orange). The strip below shows the Trig pulse, the burst and the Echo pulse. Slide the temperature, then switch the driver to compensated.
A model. The 10 microsecond trigger, the eight 40 kHz cycles, the 2 cm to 400 cm range and the divide-by-58 rule are from the HC-SR04 datasheet. The speed of sound is the ideal-gas formula for dry air. The module’s own timing error is not modelled.
The datasheet gives a range of 2 cm to 4 m and a measuring angle of 15 degrees. At the near edge, the loudspeaker is still ringing when the echo arrives, so the microphone cannot tell them apart. At the far edge, the echo is too weak. The 15 degree cone means anything inside it can answer, so a table edge beside a wall gives you the nearer one.
The datasheet also warns that the target should cover at least 0.5 square metres and be as smooth a plane as possible. This is physics you can predict: a soft jumper absorbs sound, and a surface tilted away sends the echo off to the side. The sensor then times out and reports nothing, or reports a far wall behind it.
Chapter 2
Capture the Echo edges with a timer, run the cycle on a schedule, and stop two sensors from hearing each other
The easiest driver is three lines. Set Trig high, wait for Echo to rise, count until it falls. Many tutorials do exactly this. With a 4 m limit the loop can spin for 23 milliseconds, waiting for one echo. At 168 MHz that is nearly four million cycles in which the processor does nothing else. Your motor control loop, your radio and your watchdog all wait too.
The fix is the pattern from Timers, PWM and Sampling and Drivers and State Machines: let hardware watch the pin, and let the processor sleep or work until hardware says there is news.
A timer is a counter that counts up on every tick of a clock. Input capture is a feature that copies the counter value into a register at the exact moment an edge arrives on a pin. The copy happens in hardware, so the interrupt latency does not matter. You get a timestamp accurate to one tick.
For the HC-SR04 you capture twice. The rising edge of Echo gives t1. The falling edge gives t2. The echo width is t2 - t1. On an STM32 you can also use two channels in PWM input mode and read the width from one register. Here we keep it plain with one channel and a flipping edge setting.
Choose the tick so the numbers make sense. Count at 1 MHz: one tick is 1 microsecond. Sound moves 0.34 mm in that time, and the round trip halves it, so one tick is 0.17 mm of range. A 16-bit counter wraps every 65,536 ticks, which is 65.5 ms. The longest echo is about 23 ms, so a wrap never hides an echo. Unsigned subtraction handles a wrap that happens between the two edges: (uint16_t)(t2 - t1) is still correct.
Sensor A faces a wall 120 cm away. Sensor B faces a wall 260 cm away. They sit 20 cm apart on one bumper. Drag the gap between their triggers. Purple ticks are sound from the other sensor.
A model. The geometry (120 cm, 260 cm, 20 cm apart), the 343.2 m/s speed of sound and the rule that a sensor reports the first sound it hears after its own burst are illustrative. Real modules may filter some of this. The 200 microsecond burst and the 60 ms advice are from the HC-SR04 datasheet.
Crosstalk means one channel leaking into another. Here it is sound. Sensor B cannot tell whose 40 kHz it hears. At a gap of zero, both sensors fire together and each hears the other’s burst about 0.6 ms later. Both report a ghost wall about 10 cm away. Move the gap up and nothing changes for a while: B still hears A’s echo, which comes back at 7 ms, and A still hears B’s burst. Both sensors read true only once the gap passes about 7 ms, the time A needs to hear its own echo.
The simple cure is to fire one sensor at a time and wait out the worst case before the next. For a 4 m limit, the longest echo is 2 × 4 ÷ 343.2 = 23.3 ms. Four sensors in turn need about 4 × 25 ms = 100 ms per sweep, so each sensor updates at 10 Hz. That is the cost of safety. The datasheet also suggests a measurement cycle over 60 ms, to keep one trigger from landing on the previous echo. One sensor alone then updates at most 16.7 times a second.
You can do better with geometry. Sensors on opposite sides of the robot do not hear each other, so fire them together, then fire the pair that remains. This is a schedule: a fixed list of which sensors fire in which slot. The driver owns the schedule, and the caller never knows.
The driver is a small state machine (a program that is always in one named state and moves on events). States: idle, trigger, wait for rising, wait for falling, done. A timer compare event gives up after 30 ms if no echo arrives. In that case the driver returns a timeout, not a distance. A timeout is a fact: no target within range, or a target that did not reflect.
c/* HC-SR04 on STM32 TIM2 CH1, counting at 1 MHz (1 tick = 1 us) */ typedef enum { US_IDLE, US_WAIT_RISE, US_WAIT_FALL, US_DONE, US_TIMEOUT } us_state_t; static volatile us_state_t st = US_IDLE; static volatile uint16_t t_rise, width_us; void us_start(void) { /* called by the schedule, every slot */ st = US_WAIT_RISE; __HAL_TIM_SET_CAPTUREPOLARITY(&htim2, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_RISING); HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_1); HAL_GPIO_WritePin(TRIG_GPIO_Port, TRIG_Pin, GPIO_PIN_SET); delay_us(10); /* datasheet: at least 10 us high */ HAL_GPIO_WritePin(TRIG_GPIO_Port, TRIG_Pin, GPIO_PIN_RESET); __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_2, __HAL_TIM_GET_COUNTER(&htim2) + 30000); } void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *h) { if (st == US_WAIT_RISE) { t_rise = HAL_TIM_ReadCapturedValue(h, TIM_CHANNEL_1); __HAL_TIM_SET_CAPTUREPOLARITY(h, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_FALLING); st = US_WAIT_FALL; } else if (st == US_WAIT_FALL) { uint16_t t_fall = HAL_TIM_ReadCapturedValue(h, TIM_CHANNEL_1); width_us = (uint16_t)(t_fall - t_rise); /* wrap-safe */ st = US_DONE; } } /* distance in mm for a given air temperature, from the width in us */ int us_mm(uint16_t w_us, float temp_c) { float c = 331.3f * sqrtf(1.0f + temp_c / 273.15f); /* m/s */ return (int)(w_us * c / 2000.0f); /* us * m/s / 2 = mm / 1000 */ }
The output compare on channel 2 fires the timeout. Its callback sets st = US_TIMEOUT and returns the sensor to idle. Notice that the code never blocks except for the 10 microsecond trigger, and that the temperature comes from outside the driver. Passing it in keeps the driver pure and easy to test on a PC, as the later lesson on testing firmware shows.
Chapter 3
Read a multizone time-of-flight sensor as a clock, a photon counter and a table of limits
Light is a faster clapper than sound. Light covers 0.3 m in one nanosecond (a billionth of a second). A pulse that travels to a target and back, 15 cm of range per nanosecond of delay, has gone twice as far as the target’s distance. So a target at 1 m returns the pulse after 6.7 nanoseconds. To measure to a millimetre, a chip must resolve about 6.7 picoseconds. That is why the receiver is not a camera pixel. It is a field of SPADs, single-photon avalanche diodes, each able to fire on one photon and tell the chip when. Time-of-Flight Basics and SPAD, TDC and Histograms build this in detail.
The ST VL53L5CX is a module 6.4 × 3.0 × 1.5 mm. The datasheet lists a 940 nm infrared emitter (a VCSEL, a small laser diode that shines out of its top face), a diffractive optical element that spreads the light into a square, a receive lens, a SPAD array, and a low-power microcontroller running the sensor’s own firmware. You never see most of this. You see a driver and a table of numbers.
The sensor reports distance in zones. A zone is one patch of the scene that the chip ranges on its own. You pick 4×4 (16 zones) or 8×8 (64 zones). The diagonal field of view is 63 degrees, which is 45 degrees by 45 degrees of guaranteed detection volume. The lens flips the image. The datasheet warns that zone 0 sits at the bottom left of the SPAD array, yet it is lit by a target at the top right of the scene. Your driver must flip the grid before it shows a picture or before a robot decides which side to turn to.
Each zone collects many photons over many pulses. The chip sorts them into a histogram: a row of time bins, each counting the photons that arrived in that slice of time. Photons from the sensor’s own pulse bounce off the target and pile up in one bin. Photons from sunlight arrive at random and form a flat floor. The peak above the floor is the target, and its position is the distance.
This explains the datasheet’s ambient light column. Sunlight raises the floor. A faint peak, from a distant or dark target, sinks into the floor and disappears. The datasheet tests at 5 klux, which it says matches a target irradiance of 2 W/m2 at 940 nm. A bright office window can match that. Full sun is many times brighter. (A klux is a thousand lux, a unit of how bright daylight is.)
It also explains why the chip can report several targets in one zone. Two peaks in a histogram are two objects. Chapter 4 shows how to ask for them.
Choose a resolution, a target, the light and the zone. The bar shows the datasheet range: solid up to the minimum, lighter up to the typical value. Drag the distance of your target along it.
Values are the VL53L5CX datasheet (DS13754 Rev 2) Tables 17 and 18: maximum ranging distance at a 90% detection rate, no cover glass, default settings, target filling the whole field of view. The 8×8 grey figures were measured at 13% in the infrared.
Look at the device above with the grey target and sunlight on. At 8×8 and 15 Hz, an inner zone reaches 800 mm typical and 600 mm minimum. A corner zone reaches only 650 mm typical and 400 mm minimum. Typical is what most parts do. Minimum is what the datasheet promises. Plan with the minimum. A robot that must see a dark chair leg at 1 m cannot rely on this mode in sunlight.
The corners are weaker because less light reaches them. That is the same effect as the signal law in the hero: dimmer zones lose first. It is also why the ghost zones in the first device appeared at the corners.
Accuracy has two regimes. From 20 to 200 mm, the datasheet allows ±15 mm. From 201 to 4000 mm, it allows ±4% to ±5% in the dark, and 7% to 11% in 5 klux. These figures are 2.7 sigma, so 99.3% of readings fall inside. The datasheet states all of them were tested without cover glass. Chapter 5 is about what a window adds.
The datasheet calls a second region the collector exclusion zone. It is 55.5 by 61 degrees. The cover window opening must be at least this wide. As a rough check, a window 2 mm above the module needs an opening of at least 2 × 2 × tan(30.5°) = 2.4 mm in the tall direction and 2 × 2 × tan(27.75°) = 2.1 mm in the wide direction. That is our geometry from the angles. The mechanical drawings in the datasheet are the source for your real part.
Chapter 4
Follow the order of calls the manual requires, then read each frame without wasting the bus
You have wired the sensor and the first call to the driver hangs. This is the usual first day with a smart sensor. The VL53L5CX is not a bare chip that you poke with register writes. It has its own small processor, and that processor has no program until you give it one. The first thing a driver does is download the program.
The user manual UM2884 lists the steps. Power the supplies (AVDD for the analog part and the laser, IOVDD for the pins). Drive the LPn pin high (it enables I2C when the device is in low power). Hold I2C_RST low. Then call vl53l5cx_init(). That call copies about 84 kilobytes of sensor firmware to the module over I2C and runs a boot routine.
How long does that take? Each I2C byte needs nine clock cycles: eight data bits and one acknowledge bit. 84,000 bytes × 9 = 756,000 clocks. At 1 MHz that is at least 0.76 s. At 400 kHz it is at least 1.9 s. Real transfers are slower because they come in chunks with addressing between them. This is our estimate from the byte count, not a figure from ST. It tells you the boot time is a design fact: a robot that must see at power-on should start the init early, or in a task that does not block the rest.
There is a second point. The firmware is held in RAM, so it is lost when the power goes. A reset of only the I2C_RST pin resets the I2C block, but not the sensor itself. To reset the sensor you must cycle the supplies and LPn low, wait 10 ms, and bring them back.
By default the sensor is 4×4, ranging at 1 Hz, in Autonomous mode with a 5 ms integration time. In Continuous mode the laser is on all the time. That gives the best range and ambient immunity, at higher power. In Autonomous mode the laser is on for the integration time only, and the power falls with the frame rate. The datasheet gives 216 to 313 mW for continuous ranging, depending on supply. It gives 2.8 mW to 4.5 mW for 4×4 at 1 Hz with a 5 ms integration time.
The maximum ranging frequency depends on the resolution: 60 Hz for 4×4 and only 15 Hz for 8×8. So the manual says to set the resolution first and the frequency second. If you do it the other way, the limit you just checked belongs to the old resolution. Check every return code. A driver that ignores them will run at the wrong rate and never tell you.
The sensor runs by itself. There is no “start a measurement” command per frame. You start ranging once, and it produces a frame every period. You can learn that a frame is ready two ways. In polling, you call vl53l5cx_check_data_ready() in a loop. In interrupt mode, you wait for the INT pin (pin A3, GPIO1), which the sensor clears itself after about 100 microseconds. Polling costs processor time and bus traffic on every poll. The interrupt costs one pin and almost nothing else. The pattern from Interrupts and DMA applies: the interrupt handler sets a flag and the main loop does the I2C read, because an I2C read inside an interrupt handler holds up everything else.
Each coloured block is one output field of the result struct. Choose a resolution, clock and rate, and drop the fields you do not use. The gauge shows how much of each frame the bus is busy.
Field sizes are the RAM bytes in UM2884 Table 3 for 64 zones, scaled by zone count for 4×4 (our assumption). The bus time counts 9 clocks per byte and ignores addressing, chunking and clock stretching, so it is a lower bound. The 1 to 60 Hz and 1 to 15 Hz limits are UM2884 Table 2.
A frame comes back as a struct. For 64 zones with one target each, the manual gives these sizes: ambient 256 bytes, number of SPADs 256, signal per SPAD 256, range sigma 128, distance 128, target status 64, reflectance 64, number of targets detected 64 and a motion block of 140. The sum is 1,356 bytes. The manual says you may switch fields off in the platform header, and then the RAM and the I2C traffic shrink together. It also says to keep the target count and the target status on, because they are how you judge a measurement.
Judging is the job. Each zone has a target status. Status 5 means a valid range, and the manual calls it 100% confidence. Status 6 (wrap-around not performed, typical for the first range) and 9 (valid, but possibly a merged target) count as about 50%. Status 255 means no target. The other values mean the signal was too low, the noise estimate too high or the data inconsistent. A distance with the wrong status is a false friend. Never pass a bare distance on to the planner.
c/* ST ULD driver, 8x8 at 15 Hz, interrupt driven */ static VL53L5CX_Configuration dev; static VL53L5CX_ResultsData res; volatile uint8_t frame_ready; void HAL_GPIO_EXTI_Callback(uint16_t pin) { if (pin == TOF_INT_Pin) frame_ready = 1; } int tof_start(void) { if (vl53l5cx_init(&dev)) return -1; /* ~84 kB over I2C */ if (vl53l5cx_set_resolution(&dev, VL53L5CX_RESOLUTION_8X8)) return -2; /* first */ if (vl53l5cx_set_ranging_frequency_hz(&dev, 15)) return -3; /* 8x8 max is 15 */ if (vl53l5cx_set_ranging_mode(&dev, VL53L5CX_RANGING_MODE_CONTINUOUS)) return -4; return vl53l5cx_start_ranging(&dev); } void tof_poll(uint16_t out_mm[64]) { /* called from the main loop */ if (!frame_ready) return; frame_ready = 0; vl53l5cx_get_ranging_data(&dev, &res); for (int z = 0; z < 64; z++) { int i = 63 - z; /* lens flips the image: rotate 180 degrees */ uint8_t s = res.target_status[z]; int ok = res.nb_target_detected[z] > 0 && (s == 5 || s == 9); out_mm[i] = ok ? res.distance_mm[z] : 0; /* 0 = unknown, never a distance */ } }
The last line of the loop is the key habit. Report unknown as a value that cannot be a distance. A planner that sees 0 mm will treat it as touching. So the next layer must test for unknown, and your interface should make that impossible to forget. Many teams use a separate validity mask for this reason.
vl53l5cx_init() with a GPIO toggle on a logic analyser at 400 kHz and at 1 MHz. Compare with the 1.9 s and 0.76 s lower bounds above. Then probe INT against the frame period at 15 Hz.Chapter 5
Find the glass in the histogram, measure it once, and subtract it from every frame
Look through a shop window at night. You see the street, and you also see your own face, faintly, floating on the glass. The glass reflects a little of the light that hits it. A time-of-flight sensor behind a window has the same problem, but its “face” is the sensor’s own laser pulse. A small part of that pulse bounces off the inside of the window and goes straight back into the receiver, after almost no delay at all.
ST calls this crosstalk, or xtalk: signal on the SPAD array that comes from the VCSEL light reflected inside the protective window. The user manual says the module is self-calibrated and may be used with no extra steps. It then adds that crosstalk calibration may be required if a cover glass protects the module.
Recall the histogram. A real wall makes a peak at its distance. The glass makes another peak at a distance of a few millimetres, because the light only travels a few millimetres. If the wall is far away, the two peaks are far apart and the chip separates them. The manual says the sensor is immune to crosstalk beyond 60 cm thanks to the histogram algorithm.
Below 60 cm the glass peak and the target peak overlap. Then the manual lists two symptoms: “a false target reading” and “targets appear closer than they really are”. Both are in the hero. A dim zone reports the glass. A bright zone reads a little near, because the two peaks merge and the centre moves toward the glass.
Two settings make it worse. The default target order is Strongest, so a glass peak that is stronger than the wall is reported first. The alternative is Closest, and then the glass, being the closest thing in the histogram, is always reported first. You can ask for up to four targets per zone, so the glass can take one of four slots.
This is the histogram of the centre zone. The purple peak is the window. The blue peak is your target. Press Calibrated, then try 1, 4 and 16 samples and the target-order switch.
A model. The calibration settings (target at 600 to 3000 mm, 1 to 99% reflectance, 1 to 16 samples, about 0.5 s + 0.5 s per sample) are UM2884 Table 1. The glass strength of 30, the leftover of 6 / sqrt(samples), the threshold of 5 and the log count axis are illustrative.
The idea is simple. If the glass peak is the same every time, measure it once with nothing else in view, and subtract it. Nothing else in view means: a flat target of known reflectance at a known distance, filling the whole field of view. The manual then gives the numbers:
More samples average out noise, but the time grows in a straight line: about 1 s for 1 sample, 2.5 s for 4, and 8.5 s for 16. The function is vl53l5cx_calibrate_xtalk(). Initialise the sensor first. You can call it at any time.
Work the cost. With ST’s proposal of 4 samples, the line gives 0.5 + 0.5 × 4 = 2.5 s. For 16 samples it is 0.5 + 0.5 × 16 = 8.5 s, which matches the manual. On a factory line with 20 seconds per unit, 4 samples fit and 16 do not.
It must be done with the window on, in the finished housing. A sensor calibrated bare and then covered has learnt nothing about the glass. A target that does not fill the view gives a wrong estimate, because the calibration then mixes the target’s edges with the glass. Both are mistakes about the recipe. They are not faults of the chip.
The manual also says the data can be saved and reused. You can calibrate one unit and load the same data into others, and then use the xtalk margin to raise the detection threshold until the glass is never detected. This trades range for safety. A higher threshold hides the glass on every unit, including the unit whose glass is a little more reflective, but it also hides weak real targets. Choose it from your own measurements of how much the glass varies between units.
c/* End-of-line xtalk calibration. Needs vl53l5cx_plugin_xtalk.c in the build. */ int tof_calibrate_in_housing(VL53L5CX_Configuration *dev) { /* fixture: 3% grey card, 600 mm from the sensor, filling the whole view */ uint8_t status = vl53l5cx_calibrate_xtalk(dev, 3, /* reflectance_percent: ST proposes 3 */ 4, /* nb_samples: ~2.5 s */ 600); /* distance_mm: minimum allowed is 600 */ if (status) return -1; /* Read the calibration blob out through the plugin, store it with a version and CRC in flash, and write it back before start_ranging() at every boot. See the plugin header for the exact calls. */ return 0; }
Storing the blob is a firmware job as well. Treat it as a record: add a version number for the driver, a serial number for the unit and a CRC (a check number that reveals damaged data). On boot, check them. If the check fails, fall back to a ranging mode that does not trust short ranges, and tell the user. That is the same pattern as in Non-Volatile Storage.
vl53l5cx_calibrate_xtalk(). Count the zones whose status is not 5. Then move the card to 150 mm.Chapter 6
Give identical chips their own addresses at boot, and check that the bus can carry them
One front-facing sensor sees a cone of 63 degrees. A robot that must see around itself wants four of them, one on each side. The mechanical drawing is easy. The electronics hold a surprise: every VL53L5CX leaves the factory with the same I2C address, 0x52. Put four on one bus and every message reaches all four. Their answers overlap on the data line, and the master reads garbage.
An I2C address is the name a chip answers to on the bus. The master starts each message with an address byte, and only the chip with that name replies. The datasheet gives the address as 0x52. That is the 8-bit form: the last bit says write or read, so a read goes to 0x53 (our reading of the I2C rule, not a datasheet line). The 7-bit form that many libraries use is 0x29. Check which form your HAL expects, or your first call will go to the wrong place.
The sensor lets you change its address with vl53l5cx_set_i2c_address(). The problem is that, until you do, all four answer at 0x52, so the command reaches all of them and they all move together. The answer is a pin. Each sensor has an LPn input (low power). When LPn is low the sensor’s I2C is disabled and the sensor ignores the bus. The manual gives this recipe:
set_i2c_address() to give it a new address.Repeat for each sensor but the last. It can keep 0x52. This needs one GPIO per sensor for LPn, which is a hardware decision made at the schematic stage. If you forget, you can fall back on a small I2C multiplexer chip, but that is a different design.
All three start at 0x52 with LPn high. Switch LPn off for the sensors you want to hide, pick an address, and send the change. Aim for three different addresses on a bus that answers.
A model of the procedure in UM2884, section 2. The write goes to address 0x52 and changes every sensor that is enabled and still listening there. The manual gives 0x52 as the default; that a power cycle restores it is our reading of how the firmware is loaded at each start.
Look at what the recipe costs. Each sensor needs its own 84 kilobyte firmware download. Chapter 4 put the lower bound at 0.76 s at 1 MHz and 1.9 s at 400 kHz. Four sensors in turn need 3.0 s to 7.6 s. A robot that wants its sensors at power-on should plan for this. Some designs put two sensors on each of two I2C buses and download in parallel.
Then count the load at run time. In chapter 4, one 8×8 frame of 1,356 bytes takes at least 30.5 ms at 400 kHz. At 15 Hz the frame period is 66.7 ms. Four sensors read in turn need 4 × 30.5 = 122 ms, which is more than one frame period. The bus cannot keep up. Cut the fields down to distance, status and target count (256 bytes), and each read takes 5.8 ms. Four sensors then need 23 ms, which is 35% of the period. That single line in the platform header turns an impossible design into a comfortable one.
Light sensors can disturb each other as ultrasonic ones do. Two modules pointed at the same spot may see each other’s 940 nm pulses. The manual we read does not give a rule for this, so it is a risk to test, not a fact to quote. If the modules face different directions, as on a four-sided ring, the risk is small. If they overlap, stagger the frames and compare against a run with one sensor on.
Sooner or later one of the four does not appear. Do not guess. Work down a short list, and take one measurement at each step. Is the supply present at the sensor? Is LPn high at its pin, measured with a meter or scope? Does an I2C scan find 0x29 (the 7-bit form of 0x52) when only that sensor is enabled? Did vl53l5cx_init() return an error code? Each answer cuts the search in half. A sensor that answers alone but vanishes when its neighbours wake has an address clash, which is a bug in your recipe and not in the part.
Chapter 7
Fit an offset and a gain from two measurements, store them safely and apply them in integers
A delivery robot must stop 100 mm from its charging dock. A sensor in the bumper says it is 100 mm away, and the robot stops with its contacts 12 mm short. The sensor is not broken. It measures from its own face, and nobody told the firmware that the bumper’s front plate is 12 mm further out. Every distance carries the same extra 12 mm.
That kind of error is an offset: a constant that is added to every reading. A second kind is a gain error: the reading is off by a percentage, so it grows with distance. An ultrasonic module that assumes the wrong speed of sound has a pure gain error (Chapter 1). A light sensor behind a window can have both: the reference plane gives the offset, and a slightly wrong scale gives the gain.
Write what the sensor reports as m and the true distance as d. For a small, well-behaved error, one straight line describes it: m = g · d + o. Here g is the gain (1.000 for a perfect sensor) and o is the offset in millimetres. Two unknowns need two measurements. Place a target at two known distances, d1 and d2, and record the readings m1 and m2.
(619 − 112) / (600 − 100) = 1.014, 112 − 1.014 × 100 = 10.6 mm, a reading of 416.2 gives (416.2 − 10.6) / 1.014 = 400.0 mm
The worked line shows the steps. At 100 mm the sensor reads 112, and at 600 mm it reads 619. The gain is 507 ÷ 500 = 1.014: the sensor stretches the scale by 1.4%. The offset is 10.6 mm. Later it reads 416.2 mm for a target. Subtract the offset and divide by the gain, and you get 400.0 mm.
The orange line is the error of a sensor in its housing. Set its hidden offset and gain with the first two sliders. Then choose two calibration distances and an averaging count. The green line is what is left after the fit.
A model. The sensor noise of 3 mm per reading and the two fixed noise draws are illustrative. The error is judged over 0 to 1000 mm. A fit is only as good as the range it was taken over.
Try the device with 100 and 300 mm. The fit looks fine near the calibration points. At 1000 mm the error is far larger than with 100 and 600 mm, because a small error in the slope grows with the distance. The rule is to calibrate across the range you use, and to place the points at both ends. For a docking sensor, one point near 100 mm and the other near the top of its useful range is better than two close points.
Noise matters too. Each reading carries random noise. Averaging N readings cuts the noise by the square root of N. If one reading has 3 mm of noise, 16 readings have 0.75 mm. A calibration station can afford 16. The running robot cannot always, so keep the fit a one-off job.
Light is slower in glass. A flat window of thickness t and refractive index n (how much slower light moves in the glass than in air), perpendicular to the beam, adds 2(n−1)t to the round-trip optical path. For t = 1 mm and n = 1.5, that is 1 mm. This is our geometry, not an ST figure. It is small beside the reference-plane offset that comes from where the sensor sits behind the front of the product. A tape measure and the CAD model give you the big number. The calibration confirms it and finds the rest.
Whether your part needs the fit is a measurement question. Log the error against the true distance across the range in the finished housing. If the line is flat and near zero, add nothing. For the multizone sensor, ST describes the module as self-calibrated, and the host-side calibration its manual offers is the crosstalk step from Chapter 5. We did not open ST’s application note on cover-glass design, so check it for your window material.
A calibration is data that outlives a reboot, so it needs the care from Non-Volatile Storage: a version, a unit serial, the values and a CRC. A small microcontroller often has no floating-point unit, or you may wish to keep the interrupt path lean. Store the gain as a fixed-point number: 1.014 × 65,536 = 66,454 in a 16.16 format. Store the offset in sixteenths of a millimetre: 10.6 × 16 = 170.
ctypedef struct { uint16_t version; /* bump when the model changes */ uint32_t serial; /* this unit */ int32_t gain_q16; /* 1.0 = 65536 */ int32_t offset_x16; /* sixteenths of a mm */ uint32_t crc32; /* over all the fields above */ } range_cal_t; /* fit from two (true, measured) pairs, all in mm */ void cal_fit(range_cal_t *c, int d1, int m1, int d2, int m2) { c->gain_q16 = (int32_t)(((int64_t)(m2 - m1) << 16) / (d2 - d1)); c->offset_x16 = (m1 << 4) - (int32_t)(((int64_t)c->gain_q16 * d1) >> 12); } /* apply to a raw reading in mm; round to nearest */ int cal_apply(const range_cal_t *c, int m_mm) { int64_t num = ((int64_t)m_mm << 4) - c->offset_x16; /* x16 */ return (int)(((num << 12) + (c->gain_q16 >> 1)) / c->gain_q16); }
Check the shifts with the worked example. gain_q16 is 66,454. The product gain × d1 is 6,645,400 in 16.16, and shifting right by 12 turns it into sixteenths of a millimetre: 1,622. The offset is 1,792 − 1,622 = 170, which is 10.6 mm. The same arithmetic can be tested on a laptop with a fake sensor, as Test Firmware Without the Board shows.
Chapter 8
Turn a sweeping radio tone into a range, and see why bandwidth sets what you can tell apart
Listen to a siren that slides up in pitch. Someone else plays the same slide, but a moment later. At any instant the two pitches differ by a fixed amount, because one is a bit behind the other. If you could hear the difference between the two, you would hear a steady tone. The later the second siren, the higher that steady tone.
That is how an FMCW radar measures distance. FMCW stands for frequency-modulated continuous wave. The chip sends a chirp: a radio wave whose frequency rises in a straight line, for example from 77 GHz up by 4 GHz. The wave hits a target and returns. The returned chirp is a delayed copy of the one being sent. A mixer multiplies the two, and what comes out is a steady tone whose pitch tells the distance. TI calls this tone the IF (intermediate frequency) signal. We will call it the beat.
A chirp has a bandwidth B (how far the frequency sweeps, in hertz) and a duration Tc (how long the sweep lasts). Its slope is S = B / Tc, in hertz per second. A target at distance d delays the return by 2d/c. During that delay, the sent chirp has moved on by S × 2d/c in frequency. That gap is the beat:
B = 4 GHz, Tc = 40 µs: S = 1014 Hz/s. A target at 5 m: 2 × 1014 × 5 / (3 × 108) = 3.33 MHz. dres = 3 × 108 / (8 × 109) = 3.75 cm
The 4 GHz and the 3.75 cm come from TI’s paper, which uses them as its example. The 40 microsecond duration is ours, to make the beat a number. Notice the scale: a target 5 m away produces a 3.33 MHz tone. The ADC must sample at over twice that, at least 6.7 megasamples per second.
Two targets at slightly different distances produce two slightly different beat tones. The chip looks at the tones for the length of one chirp, Tc. Two tones can only be told apart if they differ by more than about 1/Tc. The difference between the tones is 2SΔd/c, so the smallest separable Δd is c / (2S Tc) = c / (2B). A longer chirp at the same slope does not help, because it also sweeps more bandwidth. The only way to see smaller gaps is to sweep a wider range of frequencies.
Two targets stand near 2 m. Make the gap small and the peaks merge. Then widen the bandwidth. The second slider moves the near target and shows its beat tone.
A model. The resolution rule c / 2B and the 3.75 cm at 4 GHz are from TI’s SPYY005A. The peak shape (a squared sinc), the 40 microsecond chirp and the equal target strengths are illustrative. Two targets are called resolved when their gap is at least dres.
Radar chips differ widely, so we describe the pattern, not one part. The host sends a profile over SPI: start frequency, bandwidth, chirp time, number of chirps per frame and ADC rate. It then starts a frame. The chip transmits, samples and, on many parts, runs the range transform itself. When a frame is done it raises an interrupt line. The host reads the frame in one burst over SPI, ideally by DMA, and checks a frame counter to detect a skipped frame. The shape is the same as Chapter 4: configure once, wait on the interrupt, read, validate.
Some work is in the range transform. Take N samples of the beat, apply a window, and run an FFT (a fast way to find which pitches a signal holds). Bin k is at distance k × c / (2B) when N covers the whole sweep. A later step finds peaks and rejects the static clutter of the housing, just as Chapter 5 removes the glass. The radar’s own cover (a radome) reflects some of the signal too, so the same idea applies: measure the empty scene once, and subtract it.
What do you gain over light and sound? Radio waves pass through many plastics, so a radar can sit hidden behind the product’s casing. Sunlight does not matter to it and air temperature barely changes its speed. What do you pay? The resolution is coarser than a zone of light, the field of view is wide, and a flat surface can give a strong reflection from an angle you did not expect. Check the casing material’s loss in the chip vendor’s guide.
Chapter 9
Match each scene to a physics, put all three behind one interface and debug from a symptom to a measurement
A product team asks which of the three sensors to use. The answer is a question back: where will it stand, and what will it face? Each sensor wins in some scenes and fails in others, and the failures come from the physics, not from the part number. Here is what we learned in the last eight chapters, laid side by side.
Choose a scene. Each bar is our judgement of how well that sensor copes, from 0 (fails) to 3 (works well). The sentence below gives the reason and its source.
The 0 to 3 scores are a judgement for teaching, not a measurement. Each reason below rests on a figure from an earlier chapter. Radar scores assume a typical FMCW chip; always read your part’s datasheet.
Your navigation code should not know which sensor made a number. Give every driver the same output: a small frame with a timestamp, the number of zones, a distance for each zone, and a validity mask. The ultrasonic sensor makes a frame with one zone. The light sensor makes 16 or 64. The radar makes one or more peaks. When you add a fourth sensor, only a new driver is written.
ctypedef struct { uint32_t t_us; /* timestamp of the measurement, not of the read */ uint8_t n_zones; /* 1, 16 or 64 */ uint16_t mm[64]; /* calibrated distance per zone */ uint64_t valid; /* bit z set = zone z is a real measurement */ uint8_t conf[64]; /* 0..100; 100 = status 5, 50 = status 6 or 9 */ } range_frame_t; typedef struct { int (*start)(void *self); int (*poll)(void *self, range_frame_t *out); /* 1 = new frame */ void *self; } range_driver_t;
The timestamp is the weak point. The moment you read the frame is later than the moment the sensor measured. The gap is the bus time plus the wait in your task queue, and it varies. On a moving robot, an old timestamp makes a wall look bent or a target look closer than it is. Timestamp from the interrupt edge, as in Timers, PWM and Sampling, and read about the wider problem in Timestamp at the Pin.
When a ranging sensor misbehaves, resist the urge to change code. Take one measurement that splits the possible causes in two. The table lists the failures of this lesson, each with the quickest measurement.
| Symptom | Measurement | Fix |
|---|---|---|
| Ghost 10 cm walls with two ultrasonic sensors | Trigger both pins on one logic analyser. Do the Echo pulses start together? | Schedule the sensors in separate slots, 25 ms apart or more. |
| Ultrasonic reads 8 cm long in winter | Log the Echo width at a fixed 200 cm card at 0 °C and 20 °C. | Use c = 331.3 × sqrt(1 + T / 273.15) with a real temperature. |
| Light sensor reports 18 mm in the corners | Histogram or status of the corner zones with the window on and off. | Run xtalk calibration in the housing; raise the xtalk margin if needed. |
| No data after a restart | Probe LPn, I2C_RST and INT. Time vl53l5cx_init(). | Repeat the whole power-up and address recipe every boot. |
| Bus saturated, frames drop | Count bytes per frame and bus time per read. | Disable unused fields; use interrupt mode; split the buses. |
| Radar merges two people | Compare their gap with c / 2B for the configured bandwidth. | Sweep wider, or use angle to separate them. |
Once the three drivers share a frame type, you can record frames to a file and play them back through the same code on a laptop. This gives you a regression test that needs no sensor. Record a good run, a run with the window dirty and a run in sunlight. A change to the filter, the status logic or the calibration must give the same distances on the first run, and a reasonable answer on the other two. This is the habit that Test Firmware Without the Board teaches in full, and it turns a field failure into a file you can keep.
Chapter 10
Keep the numbers, the checklist and the core code in one place, then choose where to go next
Three cheap sensors turn time into distance. Sound turns an echo width into a distance and needs the air temperature. Light turns a photon histogram into 64 distances and needs a calibrated window. Radio turns a beat tone into a range and needs bandwidth. In every case the firmware owns the same four jobs: start the part in the right order, wait without wasting time, judge each number by its status, and correct it with a stored calibration.
| Item | Value | Source |
|---|---|---|
| HC-SR04 trigger and burst | 10 µs high on Trig; eight 40 kHz cycles (200 µs) | HC-SR04 datasheet |
| HC-SR04 conversion | width in µs / 58 = cm; 2 cm to 4 m; 15° angle; cycle over 60 ms | HC-SR04 datasheet |
| Speed of sound | 331.3 × sqrt(1 + T / 273.15) m/s: 331.3 at 0 °C, 343.2 at 20 °C, 351.9 at 35 °C | Ideal-gas formula for dry air |
| VL53L5CX zones and rate | 4×4 at 1 to 60 Hz; 8×8 at 1 to 15 Hz; defaults 4×4, 1 Hz, Autonomous, 5 ms | UM2884 Table 2 and section 4 |
| VL53L5CX field of view | 63° diagonal; detection 45° × 45°; window opening at least 55.5° × 61° | DS13754 Table 2 |
| VL53L5CX address and bus | 0x52 (8-bit), 400 kHz to 1 MHz; firmware of about 84 kB loaded at init | DS13754; UM2884 |
| Range, 8×8, 5 klux, grey 17% | inner 800 mm typical, 600 minimum; corner 650 and 400 | DS13754 Table 18 |
| Range, 8×8, dark, white 88% | inner 3500 mm typical, 2600 minimum | DS13754 Table 18 |
| Accuracy | ±15 mm to 200 mm; then ±4% to 5% (dark), 7% to 11% (5 klux); no cover glass | DS13754 Table 19 |
| Crosstalk calibration | target 600 to 3000 mm (ST: 600), 1 to 99% (ST: 3%), 1 to 16 samples (ST: 4); about 1, 2.5, 8.5 s | UM2884 Table 1 |
| Crosstalk immunity | beyond 60 cm by the histogram; below it, ghosts and early readings | UM2884 section 3 |
| Target status | 5 valid (100%), 6 and 9 about 50%, 255 none | UM2884 Table 4 |
| Result struct, 8×8, 1 target | 1,356 bytes: sum of Table 3 fields | UM2884 Table 3 (our sum) |
| FMCW range | fbeat = 2Sd/c; dres = c/2B; 3.75 cm at 4 GHz | TI SPYY005A |
| Term | Plain meaning |
|---|---|
| Zone | One patch of the scene that a multizone sensor ranges on its own. |
| Histogram | Photon counts sorted by arrival time. A peak above the floor is a target. |
| Crosstalk (xtalk) | Signal that reaches the receiver by a path you did not intend, such as the window. |
| Target status | A code that says how far to trust a distance. |
| LPn | The pin that switches the sensor’s I2C on or off. It lets identical parts share a bus. |
| Input capture | A timer feature that copies the counter when a pin edge arrives. |
| Offset and gain | A constant error and a percentage error. Two known distances find both. |
| Chirp and beat | A radio sweep, and the steady tone left when the echo is mixed with it. |
This is the boot recipe for a ring of identical light sensors, using only calls the manual describes. It is the longest part of a real driver to get right.
c/* Boot a ring of N VL53L5CX on one I2C bus. LPn[i] are GPIOs. */ int ring_boot(VL53L5CX_Configuration dev[], int n) { power_off_all(); delay_ms(10); /* supplies and LPn low, wait 10 ms */ power_on_supplies(); for (int i = 0; i < n; i++) lpn_write(i, 0); /* everyone silent */ for (int i = 0; i < n; i++) { lpn_write(i, 1); /* only sensor i answers at 0x52 */ if (i < n - 1) if (vl53l5cx_set_i2c_address(&dev[i], 0x54 + 2 * i)) return -1; if (vl53l5cx_init(&dev[i])) return -2; /* ~84 kB */ if (vl53l5cx_set_resolution(&dev[i], VL53L5CX_RESOLUTION_8X8)) return -3; if (vl53l5cx_set_ranging_frequency_hz(&dev[i], 10)) return -4; cal_load_and_apply_xtalk(&dev[i]); /* stored blob, checked by CRC */ } for (int i = 0; i < n; i++) vl53l5cx_start_ranging(&dev[i]); return 0; }
One detail: the init of sensor i here happens after its address change and while the later sensors are still silent. Each sensor is on its own address from then on, so the later downloads cannot disturb it. We placed the address change before the init; check that order against the multi-sensor example in your driver release.
Every number above comes from one of these. ST, VL53L5CX Time-of-Flight 8x8 multizone ranging sensor with wide field of view, datasheet DS13754 Rev 2 (st.com). ST, A guide to using the VL53L5CX multizone time-of-flight ranging sensor with a wide field of view, Ultra Lite Driver (ULD), user manual UM2884 Rev 2 (st.com). Elecfreaks, Ultrasonic Ranging Module HC-SR04 (datasheet copy). Cesar Iovescu and Sandeep Rao, Texas Instruments, The fundamentals of millimeter wave radar sensors, SPYY005A (ti.com). The speed-of-sound formula and the window-delay estimate are standard physics that we worked ourselves. We did not open ST’s application note on cover-glass design; read it before you choose a window.
Now press Present or Teach and explain one reading from memory: what the sensor measured, why the window made a ghost, how calibration removed it, and what the firmware does with a zone it cannot trust. Then go back to the sensor at the top, choose Cover glass, push the wall to 2,000 mm, and say which zones fail first and why.