Time of Flight Basics

Light travels 15 cm in one nanosecond, so a sensor that times an echo can measure distance. Three ways to time it: a pulse, a phase, and a chirp.

Learn how a ranging chip turns the speed of light into a clock, where each method breaks, and the C that reads each one on a Cortex-M.

Pick a method, then drag the target away. Watch the pulse mode keep counting while the phase mode wraps around. Then we build, piece by piece, how each one works.

You need a feel for a sine wave (a smooth wave that repeats) and a little C. We build the rest from zero.

Part of the Firmware from Zero to Expertise series, ranging track. Built from primary sources: Texas Instruments SLOA190B and SPYY005, the ST VL53L1X product page, and the STM32G474 datasheet. Full list in the Field Guide.

Measure a target

3.0 m

A model, not a real sensor. Speed of light 299,792,458 m/s. Phase method: 20 MHz modulation, so the wrap distance is c / (2 f) = 7.49 m (TI SLOA190B, Eq. 7). Chirp: slope 100 MHz per microsecond, from the TI SPYY005 example (4 GHz in 40 microseconds). Echo sizes are illustrative.

Chapter 0

A Clock Made of Light

See how timing one flash of light gives you a tape measure, and why firmware sits at the center of every such sensor

You stand in a dark hall and clap once. A second later you hear the echo from the far wall. You know sound moves at about 340 metres every second, so you can work out how far away the wall is. You only needed a stopwatch.

A ranging sensor does the same with light. It sends a flash toward a target and starts a clock. The light bounces off, comes back, and the clock stops. The time on the clock is the distance, once you multiply by a constant.

The catch is speed. Light moves at 299,792,458 metres per second, a number so exact that the metre is now defined from it. In one nanosecond (one billionth of a second, written 1 ns) light covers about 30 cm. It must go out and come back, so each nanosecond on the clock is worth only 15 cm of distance. Remember that: 1 ns = 15 cm.

Why firmware gets the hard part

A microcontroller (a small chip with a processor, memory and pins, the kind in a Cortex-M board) counts in clock ticks. A fast chip such as the STM32G474 runs at up to 170 MHz, so one tick lasts 5.9 ns. That is 88 cm of distance per tick. A door is not even one tick wide.

So the chip cannot simply count ticks. Sensor makers use three ideas to get around it, and this lesson teaches all three, one at a time.

  1. Direct time of flight (dToF). Send a short pulse and time it with a very fast stopwatch built from silicon delay gates. Chapters 1 to 4.
  2. Indirect time of flight (iToF). Send a smooth repeating wave. Measure how far the echo wave has slipped behind, an angle called the phase, and convert it to distance. Chapters 5 and 6.
  3. Frequency modulated continuous wave (FMCW). Send a wave whose pitch keeps rising. The delay shows up as a steady beat tone, and a Fourier transform reads the tone. Chapter 7.

Chapter 8 puts the three side by side. Chapter 9 shows the C code that reads them, and Chapter 10 is the Field Guide. Every method hides a firmware job: turning raw counts, sample values or FFT bins into millimetres you can trust.

Two ideas you need first

The first idea is the round trip. The light travels to the target and back, so the one-way distance is half of what the light covers. If the clock reads t seconds, the distance is d = c × t / 2, where c is the speed of light. The factor of 2 is the number people forget.

The second idea is phase. Picture a clock hand that sweeps round once for every wave. A sine wave is what a point on the tip of that hand traces as it turns. If an echo arrives late, its hand points at a different angle than the hand of the wave you sent. That angle gap, measured in degrees from 0 to 360, is the phase lag. A full turn is one period. A wave that repeats 20 million times a second has a frequency of 20 MHz and a period of 50 ns. The lesson Discrete Signals goes deeper on sampling a wave, and we use only the picture here.

Run the clock, read the distance

The warm dot is the pulse going out. The blue dot is the echo coming back. Drag the clock time and see which landmark the light reaches before it turns round.

20 ns

Landmark distances are illustrative. The conversion is exact: distance = c × t / 2 with c = 299,792,458 m/s, so 1 ns is 14.99 cm.

At 20 ns the light has gone 3 m out and 3 m back, so a target 3 m away produces a 20 ns echo time. Slide to 1 ns and the target is closer than your hand. Slide to 100 ns and the target is 15 m away.

The road

  1. The round trip: how fine a clock you need, and what a timer pin on a Cortex-M can do.
  2. Stop the clock: a pulse, a threshold, and why dark targets read far.
  3. How much light comes back: the inverse square law, ambient light, and averaging.
  4. The echo that arrives late: the repetition rate and ghost targets.
  5. Measure phase, not time: four buckets of light and one arctangent.
  6. The wrap and the trade: ambiguity range, noise, and two frequencies.
  7. Turn time into a tone: chirps, the beat, and range resolution.
  8. Choosing a method: the three side by side.
  9. Reading each in firmware: the data flow and the C.
  10. Field guide: numbers, checklist, sources.
A pulse of light leaves a sensor and its echo returns 10 ns later. How far away is the target?

Chapter 1

The Round Trip and the Size of a Tick

Work out how fine a clock a range measurement needs, and compare what a timer, a high resolution timer and a timing chip deliver

You want a robot vacuum to notice a chair leg 5 cm in front of it. How fine must its stopwatch be? That one question sets the hardware for the whole sensor.

Start from the formula. The light goes out and comes back, so the distance is half of what it covers in the measured time t.

d
The one-way distance to the target, in metres.
c
The speed of light, 299,792,458 m/s. Light in air is about 0.03% slower, which we ignore here.
t
The round trip time from the moment the light leaves to the moment the echo arrives, in seconds.

1 ns: 299,792,458 × 0.000 000 001 / 2 = 0.1499 m (about 15 cm)

Flip it round. To resolve 5 cm, the clock must resolve t = 2 × 0.05 / c, which is 0.33 ns, or 333 picoseconds. A picosecond (ps) is a thousandth of a nanosecond. Resolving a centimetre needs about 67 ps.

What a plain timer can do

Take an STM32G474, a Cortex-M4 part. Its datasheet (DS12288) gives a maximum core clock of 170 MHz. A timer is a counter that adds one on every clock tick. One tick lasts 1 / 170 MHz = 5.88 ns. The distance for one tick is 5.88 ns × c / 2 = 88 cm.

Count a 3 m echo as a worked example. The round trip is 2 × 3 / c = 20.0 ns. The timer counts 20.0 / 5.88 = 3.4 ticks. A counter holds only whole numbers, so it reads 3. Three ticks is 3 × 0.88 = 2.64 m. The error is 36 cm, from the counter alone.

That step is called quantization: the true time is rounded down to a multiple of one tick. The size of one step is the least significant bit (LSB) of the measurement. Every timing method in this lesson has an LSB, and it sets a floor on the accuracy.

Finer clocks

The same chip has a high resolution timer (HRTIM). The datasheet lists it as six 16-bit counters with 184 ps resolution. One step is 184 ps × c / 2 = 2.76 cm. That is 32 times finer than the plain timer.

For finer steps still, designers add a time to digital converter (TDC). Inside, a start edge races along a chain of tiny delay gates. The stop edge freezes how far the start edge got. Counting the gates passed gives the time. The ScioSense TDC-GP22 datasheet lists a typical resolution of 90 ps for one channel and 22 ps in its finest mode. That is 1.35 cm and 0.33 cm of range per step. The next lesson, SPAD, TDC and the Histogram, builds one.

Feel the staircase

The faint diagonal is the true distance. The warm staircase is what a counter reports. Pick a clock, then drag the target from 0 to 2 m.

1.20 m

Step sizes come from d = LSB × c / 2. The 170 MHz limit and the 184 ps HRTIM figure are from the STM32G474 datasheet DS12288; 90 ps and 22 ps are typical figures from the ScioSense TDC-GP22 datasheet. The counter floors, as a plain timer does.

With the plain tick, a target at 1.20 m reads 0.88 m, and one at 1.76 m is the next step up. With the 22 ps TDC the staircase is too fine to see: the steps are 3 mm.

Run the same 3 m target through the finer clocks. The round trip is still 20.01 ns. The HRTIM counts 20.01 / 0.184 = 108.7, so it reads 108 steps, which is 19.87 ns and 2.979 m. The error is 2.1 cm. A 90 ps TDC counts 222.3 and reads 222 steps, which is 19.98 ns and 2.995 m. The error is 5 mm. Each tenfold finer clock cuts the staircase error by about ten, and costs more silicon, more power and more calibration.

The part nobody mentions: the start edge

The clock must start at the instant the light leaves, not when the firmware decided to fire. A driver chip, a wire and the laser itself all add delay, often several nanoseconds, which is tens of centimetres. Designers fix this by measuring the sent pulse on the same timing hardware as the echo, or by calibrating a fixed offset once. Firmware stores that offset in the part's calibration data. Forgetting it leaves every reading too long by the same amount.

On real hardware. Board: STM32 Nucleo-G474RE. Toggle one pin with a timer output and capture it on a second pin with a timer input capture at the full timer clock. Wire the two with 0 m, 10 m and 20 m of coax (signals move at roughly two thirds of c in cable, about 5 ns per metre). You should see the capture count rise in steps of one tick, 5.88 ns, which matches the staircase above.
A sensor needs 1.5 cm range resolution. About how fine must the time step be?

Chapter 2

Stop the Clock: Pulses, Thresholds and Walk

Follow one pulse from the laser to the stopwatch, and see why a dark target reads farther away than a bright one at the same distance

Hold a white card and a black card at exactly 1 m from a pulse ranging sensor. The white card returns a bright echo and the black card a faint one. The distance is the same. Yet a simple sensor reads the black card a few centimetres too far. Why?

The reason sits in how the stopwatch stops. Direct time of flight (dToF) means the chip measures the round trip time itself. It sends a short pulse, a burst of light a few nanoseconds long. A photodiode (a part that turns light into current) catches the echo and an amplifier makes the current into a voltage. A circuit called a comparator watches that voltage. When it rises above a fixed threshold, the comparator fires and stops the clock.

Look at the voltage in time. The echo does not jump up. It climbs along a rising edge, because the laser, the diode and the amplifier all have limited speed. A tall echo crosses the threshold early on that edge. A short echo crosses late. The clock stops at a different moment even though the light arrived at the same moment.

Walk error

This effect is called walk: the timing point walks along the pulse as its height changes. Let the pulse be a smooth hump of height A and width w. Its rising edge crosses a threshold th at z widths before the peak, where z = √(2 ln(A / th)) for a hump shaped like a bell curve. A taller A makes z larger, so the crossing moves earlier.

w = 1.5 ns, th = 0.2: A = 0.5 gives z = 1.35, crossing 2.03 ns early. A = 0.9 gives z = 1.73, crossing 2.60 ns early.

The two targets differ by 0.57 ns. At 15 cm per nanosecond that is 8.6 cm of error, just from reflectivity (the fraction of light a surface sends back). The sensor was calibrated for one brightness and is wrong for the rest.

Cross the threshold

The blue hump is the echo. The purple line is the comparator threshold. The yellow tick is where the sensor was calibrated, at a 50% target. Change the target and the threshold. Add noise to see the crossing time jitter.

90%
20%
2%

Illustrative model: a bell shaped echo with width w = 1.5 ns, height as a percent of the brightest return, noise as a percent of the same scale. Walk is measured against the crossing of a 50% echo at the same threshold. Real receivers shape the pulse differently, so the numbers differ; the mechanism does not.

Try the pair from above. Set the height to 50%, note the walk, then set 90%. Then lower the height until the echo drops below the threshold. The sensor sees nothing at all: the target has vanished, although it did not move.

Noise becomes jitter

Noise adds a random wobble to the voltage. Where the edge is steep, a wobble of a given size moves the crossing only a little. Where it is shallow, the same wobble moves it a lot. The crossing time then varies from shot to shot. That variation is jitter.

Jitter in time is the noise divided by the slope of the edge: σt = σnoise / slope. Convert it to range with the round trip formula: σd = c × σt / 2. With 2% noise, a 90% echo and a 20% threshold, the edge slope at the crossing is 0.2 × 1.73 / 1.5 = 0.23 of full scale per nanosecond. So σt = 0.02 / 0.23 = 0.087 ns, which is 1.3 cm. A steeper edge or a taller echo gives a smaller error.

Why not use a sharper pulse and a steeper edge? You can, and the jitter formula says it helps: a steeper slope means less time error for the same noise. But a sharper edge needs a faster laser driver, a faster photodiode and a wider amplifier. A wider amplifier also lets in more noise. So the edge speed is a design trade, and the reasons laser pulses are kept short and low in average power belong to the eye safety lesson, Firing the Laser on Time.

The fixes firmware sees

There are three common fixes. First, measure the echo height too, and subtract a walk correction from a lookup table. Second, put the timing point at a fixed fraction of the height, so tall and short echoes cross at the same place on their own edge. Third, skip the single threshold and fit the whole echo shape from a histogram, which the next lesson covers. Whichever the chip uses, the register map usually exposes a signal level next to the distance. Read both and distrust a distance with a very low signal level.

On real hardware. Board: STM32 Nucleo-G474RE with a VL53L1X breakout on I2C. Put a white card and then a black card at the same measured distance from the ruler. Read the distance and the signal rate from the ST ultra lite driver for each, 50 readings each. Compare the mean of the two. A few centimetres of difference is walk and calibration at work.
Two targets sit at the same distance. One returns a tall echo and one a short echo, and a single threshold timer reads them differently. What is this error called?

Chapter 3

How Much Light Comes Back

Count the light budget of one pulse, see why range collapses outdoors, and trade measurement time for reach by averaging

A small laser in a phone sends out a pulse. The pulse hits a wall 4 m away, scatters in every direction, and a sliver finds its way back to a tiny detector. How big is the sliver? Far smaller than you would guess. Most ranging problems in firmware begin here.

A matte wall acts like a diffuse reflector: it sends light out in all directions, not as a mirror does. The light that left in one narrow beam spreads over a half sphere. The detector catches a fixed small patch of that sphere. The sphere grows with the square of the distance R, so the patch receives a share that falls as 1/R². This holds when the target is wider than the beam. A thin object smaller than the beam loses more, close to 1/R&sup4;, because both the outgoing beam and the returning light spread.

Double the distance and the echo drops to a quarter. A target that returns 10% of the light, like dark fabric, has a tenth of the echo of a white wall.

Counting photons

A photon is one packet of light. A good detector reacts to single photons, so the echo is best counted in photons. Suppose a pulse brings back S photons from the target. The detector also catches ambient light: light from the sun or a lamp, which arrives at random all the time. Call the ambient photons that land in the same short window B.

Photon arrivals are random, like raindrops. In a count of K photons, the natural wobble is about √K. This is shot noise. The total count is S + B, so the noise is √(S + B). The ratio of signal to noise, the signal to noise ratio (SNR), is S / √(S + B).

SNR
How far the echo stands above the noise. A value of 3 is a common, if rough, bar for calling a peak real.
N
The number of pulses averaged into one reading.
S
Echo photons detected per pulse. Falls as reflectivity over distance squared.
S
The same S inside the noise term, because the echo photons are random too.
B
Ambient photons per pulse window. Indoors it is small. In direct sun it can swamp the echo.

The √N factor is the gain from averaging. Add the signal of N pulses: it grows by N. The noise grows only by √N, because random wobbles partly cancel. So the SNR improves by √N. One hundred pulses give 10 times the SNR. Ten thousand give 100 times.

Worked example. Take a 50% target at 4 m in an office. With the illustrative budget below, S = 4 × 0.5 / 4² = 0.125 photons per pulse and B = 0.2. One pulse gives SNR = 0.125 / √0.325 = 0.22. The echo is buried. Reaching SNR 3 needs √N × 0.22 ≥ 3, so N ≥ 188 pulses. At 1 million pulses per second that is 188 microseconds, a refresh rate of about 5,300 readings per second.

Find how far it can see

The warm curve is SNR against distance on a log scale. The purple line marks SNR 3. Where the curve crosses it is the longest range this setup can read. Change the target, the light and the number of pulses.

50%
100

Illustrative numbers, not a datasheet: a white target returns 4 detected photons per pulse at 1 m; ambient is 0.01, 0.2 or 3 photons per pulse window. The shape (1/R² signal, shot noise, √N averaging) is standard. The pulse rate of 1 million per second is assumed to turn pulses into time.

Set a 50% target, office light, and 100 pulses. The range ends near 3.3 m. Raise to 10,000 pulses and it reaches about 12 m, but each reading now takes 10 ms at a 1 MHz pulse rate, a refresh rate of 100 Hz. Switch to bright sun with 100 pulses and the range collapses to about 1.9 m: the ambient photons add noise without adding signal.

What firmware controls

This trade appears in every ranging driver as a timing budget: how long the chip may spend on one reading. A longer budget means more pulses, which means more range and less noise, but a lower update rate. A driver for the ST VL53L1X, for example, offers distance modes and a timing budget, and the product page quotes ranging up to 4 m at up to 50 Hz. You pick the point on the curve your application needs. A robot that avoids walls at 1 m/s needs fast updates. A level sensor in a tank needs range and quiet.

On real hardware. Board: STM32 Nucleo-G474RE with a VL53L1X breakout. Point it at a grey card at 2 m. Read the signal rate and ambient rate that the driver reports (in thousands of counts per second), first in the dark and then next to a bright window. Expect the ambient rate to rise and the maximum range to shrink.
You average 400 pulses instead of 100 for the same target. By what factor does the SNR improve?

Chapter 4

The Echo That Arrives Late

Learn why firing pulses faster limits how far you can see, and how a far wall can show up as a ghost near the sensor

Chapter 3 ended with a bargain: fire more pulses and you see farther. So why not fire a pulse every few nanoseconds and average millions of them? Because the sensor must know which pulse an echo belongs to, and it has no label on the light.

Picture a person shouting down a canyon, once every second. The echo from a far cliff takes 1.5 seconds to return. By then the person has shouted again. When the echo arrives, half a second after the second shout, they think the cliff is near, as if it were half a second away. The echo is real, but it was matched to the wrong shout.

A pulse sensor makes the same mistake. It starts its clock at each pulse and stops it at the next echo. Pulses are sent one every repetition period T. If an echo comes later than T, the clock was already restarted by the next pulse. The sensor measures only the time since the latest pulse.

The ambiguity range

The largest round trip the sensor can read without confusion is one period T. The matching distance is the ambiguity range, also called the unambiguous range.

Rmax
The farthest target that reads correctly, in metres.
c
The speed of light, 299,792,458 m/s.
frep
Pulses sent per second. Its inverse is the repetition period T.

1 MHz: Rmax = 299,792,458 / (2 × 1,000,000) = 149.9 m

At 100 kHz the range is 1.5 km. At 10 MHz it is only 15 m. A target at 200 m seen by a 1 MHz sensor has a round trip of 1.33 microseconds. The next pulse left at 1.00 microsecond, so the clock shows 0.33 microseconds and the sensor reports 200 − 149.9 = 50.1 m. A wall 200 m away appears 50 m away.

Match the echo to the wrong pulse

Warm bars are sent pulses. Blue bars are echoes of the pulses. The purple bracket is what the clock measures: the time from the latest sent pulse to the echo. Pick a repetition rate, then drag the target out past the red line.

60 m

A model of pulse timing only. The wrap rule is exact: reading = true distance modulo c / (2 f_rep). Real sensors may also vary the gap between pulses or code their pulses to tell echoes apart.

Set 1 MHz and 60 m: all is well. Push to 200 m and the chip reports 50.1 m, and the state chip warns you. Now switch to 100 kHz. The same 200 m target reads correctly, but the pulse rate is ten times lower, so the averaging of Chapter 3 is ten times slower.

The firmware view

Three facts matter in code. First, the reading has no flag for "wrapped". The number looks fine. Second, a strong retroreflector (a road sign or a bike reflector) far away can return a loud echo even when its range is past the limit. Third, the order of pulses is under your control. A driver can choose the repetition rate per mode: a short mode for fast near readings, a long mode for far ones. The ST VL53L1X driver offers a short and a long distance mode for this kind of trade, and a timing budget on top.

The signal check deserves numbers. Light from a wall at 200 m returns (200 / 50)² = 16 times less than light from the same wall at 50 m. A ghost reading of 50 m, backed by an echo 16 times too faint, does not fit the 1 / R² law of Chapter 3. Firmware that knows the reflectivity range of its scene can use that mismatch as a flag.

Defences are simple to state. Keep the limit above the farthest real object. Check that the signal level is plausible for the distance: an echo from 150 m would be faint, so a loud echo at a reported 50 m is suspicious. Or change the repetition period from pulse to pulse and keep only echoes whose reading stays the same for every pattern. A wrapped echo shifts when the gap shifts. A true echo does not.

On real hardware. Board: RP2040 or STM32 Nucleo-G474RE. Drive an LED or laser module through a timer at 1 MHz and read the echo from a photodiode board on a comparator input with input capture. A wall beyond 150 m is not practical indoors. Raise the pulse rate to 10 MHz instead and aim at a wall 20 m away. The reading should wrap by 15 m and show 5 m.
A pulse sensor fires at 5 MHz. Its limit is about 30 m. A wall is 40 m away. What does the sensor most likely report?

Chapter 5

Measure Phase, Not Time

Skip the picosecond stopwatch: send a smooth wave, catch its echo in four buckets, and read the distance from one angle

Texas Instruments states the problem plainly in its time of flight paper SLOA190B: to reach 1 mm accuracy by timing a single pulse, you must time 6.6 picoseconds. Check it. A round trip for 1 mm is 2 × 0.001 / c = 6.7 ps. That is nearly impossible for an ordinary pixel in silicon.

Indirect time of flight (iToF) dodges the problem. It never times the light. It sends a wave whose brightness rises and falls smoothly, say 20 million times each second, and asks a different question: how far behind the sent wave is the echo wave?

Four buckets

Imagine a clock face. The sent wave has a hand sweeping round once per period. The echo has the same wave but is late, so its hand points to a different angle. That angle is the phase lag, written φ. A 20 MHz wave has a 50 ns period, so a delay of 12.5 ns is a quarter turn, 90°.

A sensor pixel cannot see the angle directly. It collects light into buckets, small charge stores (electrons from the photodiode). A bucket is open only during a window locked to the sent wave. Bucket 1 listens aligned with the sent wave, bucket 2 half a period later, bucket 3 a quarter period later, bucket 4 three quarters later. TI names the four readings Q1 to Q4 and says each sample is phase stepped by 90 degrees. After many periods each bucket holds a number.

A late echo lands more in some buckets than in others. The pattern of the four numbers carries the angle. TI gives the formulas (SLOA190B, Eq. 2 to 5).

φ
The phase lag of the echo behind the sent wave, in radians. One full turn is 2π.
Q3 − Q4
The difference of two buckets half a period apart. It is large when the echo is a quarter period late. The offset cancels in a difference.
Q1 − Q2
The matching difference for the other axis. Large when the echo is on time.
d
The one-way distance. The factor 4π holds the round trip: 2π for a full turn times 2 for out and back.
f
The modulation frequency, the rate at which the light brightens and dims.

In firmware, use atan2(Q3 - Q4, Q1 - Q2) and not a plain division, so the angle lands in the right quarter of the circle. The same four numbers also give the echo's strength A = √((Q1−Q2)² + (Q3−Q4)²) / 2 and the ambient offset B = (Q1+Q2+Q3+Q4) / 4.

Worked example. Let f = 20 MHz, A = 1000 and B = 1000 electrons. The echo is 90° late. Then Q1 = B + A cos 90° = 1000, Q2 = 1000, Q3 = B + A cos 0° = 2000, Q4 = 0. So Q3 − Q4 = 2000 and Q1 − Q2 = 0, and φ = arctan(2000 / 0) = 90°. Then d = c φ / (4π f) = 299,792,458 × (π/2) / (4π × 20,000,000) = 1.87 m.

Two things cancel for free. The ambient light B appears equally in every bucket, so it drops out of each difference. A change in echo strength, from a darker target or a fouled lens, scales both differences together, so it drops out of the ratio. TI calls out both of these as desirable properties. The pulse method of Chapter 2 had no such luck: its reading moved with echo height.

Read the angle from four buckets

Left: the four bucket values. Right: the point (Q1 − Q2, Q3 − Q4). Its angle is the phase. Drag the distance, then change the echo strength and the ambient light. Press New measurement with noise on to see the spread.

1.87 m
1000
1000

Model: Q = B + A cos(φ − step), steps 0, 180, 90, 270 degrees, with A and B in electrons (illustrative). The equations are TI SLOA190B Eq. 2 to 5 at f = 20 MHz. Noise draws each bucket with a spread of the square root of its count. The expected spread uses Eq. 6 with an assumed modulation contrast of 0.5.

With noise off, the answer is exact for any A and B. Turn noise on with a small A and large B, and press New measurement a few times: the distance dances around the truth. The ambient light cancelled in the average but still adds noise. Chapter 6 puts a formula on that.

There is also a pulsed form of the same idea. TI describes two windows after one short pulse and the distance d = ½ c Δt × Q2 / (Q1 + Q2), where Δt is the pulse length. Charge in the second window shows how much of the echo spilled past the first. It needs no stopwatch either.

On real hardware. Board: STM32 Nucleo-G474RE. Two timer channels make a 1 MHz square wave, one delayed by an adjustable amount. Feed the second one through a 10 m coax. Capture both with input capture, and take the time difference between rising edges. Cable delay is about 50 ns, which is 18 degrees of phase at 1 MHz. Compute φ = 360 × f × delay and compare.
Ambient light adds the same charge to all four buckets. Why does it not shift the phase result?

Chapter 6

The Wrap and the Trade

See why a phase sensor must choose between range and accuracy, and how two frequencies get both

A clock hand returns to 12 every hour. If someone tells you the hand points at 12, you cannot say whether it is 3:00, 4:00 or 5:00. A phase sensor has the same blind spot. The angle φ goes from 0 to 360 degrees and then starts over. An echo that is one full wave period late looks exactly like one that is on time.

The distance at which the angle completes one turn is the ambiguity distance. TI SLOA190B gives it as Eq. 7, and says it is also the maximum measurable distance.

damb
The distance where the phase has wrapped once. Beyond it the reading repeats.
c
The speed of light.
f
The modulation frequency. A faster wave wraps sooner.

20 MHz: 299,792,458 / 40,000,000 = 7.49 m  |  100 MHz: 1.50 m  |  10 MHz: 15.0 m

It is the same rule as in Chapter 4, with the modulation frequency taking the place of the pulse rate. A target at 4 m seen at 100 MHz is 4 − 2 × 1.499 = 1.00 m after two wraps, and the sensor reports 1.00 m.

Why not just use a slow wave?

A slow wave gives a long range, but TI shows a cost in Eq. 6. The spread of the distance reading is

σ
The typical error of one distance reading, in metres.
f
The modulation frequency. It sits in the denominator: faster wave, smaller error.
cd
Modulation contrast, how well the pixel separates and collects the electrons. It falls at high frequency.
A
The echo amplitude. More echo gives less error.
B
The ambient offset. More ambient light gives more error.
A
The same amplitude, again in the denominator of the ratio.

The error shrinks as f grows. So the two goals pull in opposite directions. Lowering f extends the range and worsens the accuracy, and TI says exactly this. The wave cannot rise forever either: contrast cd drops at high frequency because of the silicon itself, which TI names as a practical upper limit on modulation frequency.

The two frequency trick

TI says advanced systems add more modulation frequencies. Here is why that works. Each frequency gives a reading and a list of possible true distances: the reading, plus any whole number of wraps. Two frequencies wrap at different distances. Only one candidate is shared by both lists, up to far beyond either wrap.

Worked example. A target is 4.00 m away. At 100 MHz the wrap is 1.499 m and the reading is 1.002 m, so the candidates are 1.002, 2.501, 4.000, 5.499, 6.998. At 80 MHz the wrap is 1.874 m and the reading is 0.252 m, so the candidates are 0.252, 2.126, 4.000, 5.874, 7.748. They meet at 4.000 m. The pair behaves as if it wrapped at the greatest common divisor of the two frequencies: 20 MHz, which is 7.49 m. You keep the fine accuracy of 100 MHz and the range of 20 MHz.

Unwrap with two frequencies

Each dot is one reading at one true distance. Green dots are within a quarter of the 100 MHz wrap of the truth. Red dots are wrong. Pick a mode, then raise the noise to see where unwrapping breaks.

×1
4.0 m

Illustrative noise: a spread of 5 cm at 20 MHz that scales as 1/f (so 1 cm at 100 MHz), times the knob. Unwrapping picks the pair of candidates, one per frequency, that agree most closely and reports the 100 MHz one. TI SLOA190B describes the multi-frequency idea; the frequency pairs here are illustrative choices, and the numbers are computed live.

Start on 100 + 80 with the noise at ×1. The line is clean out to 7.49 m. Now raise the noise. Dots start jumping by exactly 1.5 m: the unwrapper picked a neighbouring candidate. The error is not small noise, it is a whole-wrap mistake. This is the failure to watch for in a driver. Lower frequencies make larger candidate gaps and survive more noise. The cost is accuracy.

What to read from the chip

Firmware can protect itself with sanity checks. Keep the amplitude A from the same four numbers of Chapter 5, and reject readings with low A. Compare the two frequencies' candidates and reject the reading when they agree only loosely. Report the residual (how far apart the best pair was) next to the distance, so a fusion filter such as the one in Kalman Filter can down-weight a shaky range.

On real hardware. Board: STM32 Nucleo-G474RE (Cortex-M4). Write the unwrap function from Chapter 9 and time it with the DWT cycle counter (DWT->CYCCNT) over 10,000 calls with synthetic phases. This tells you the cost per pixel and whether a 320 × 240 depth map could ever be unwrapped on this core, or must go to a hardware block.
An iToF sensor at 100 MHz reports 0.60 m for a target. Which true distance is possible?

Chapter 7

Turn Time into a Tone

Sweep the pitch of a wave, mix the echo with what you sent, and a delay of nanoseconds becomes a tone a cheap converter can read

Listen to a slide whistle. The pitch rises as you push the slide. Now imagine you play a rising whistle and a friend plays the echo a moment later. At any instant your note is a little higher than the echo you hear, because the echo is a copy from slightly earlier, when the pitch was lower. The gap between the two pitches stays the same all the way up the slide. The bigger the delay, the bigger that gap.

That is frequency modulated continuous wave (FMCW) ranging. TI's paper SPYY005 (Iovescu and Rao) describes it for millimetre wave radar, and the maths is the same for a swept laser. The sensor sends a chirp: a wave whose frequency rises in a straight line. TI's example chirp starts at 77 GHz, sweeps a bandwidth B of 4 GHz, and lasts Tc = 40 µs. Its slope S, the rate at which the frequency climbs, is B / Tc = 100 MHz per microsecond.

Where the beat comes from

A mixer multiplies two waves and produces a wave at their frequency difference. The sensor mixes the echo with a copy of what it is sending now. The echo left a round trip time τ = 2d / c ago. So its frequency is lower by S × τ. The mixer output is a steady tone, the beat or intermediate frequency (IF). TI states it: the IF tone has a constant frequency Sτ.

fb
The beat tone after the mixer, in hertz. Read it with an ADC and a Fourier transform.
S
The chirp slope, bandwidth divided by chirp time. 100 MHz per microsecond is 1014 Hz per second.
d
Distance to the target. The 2 is the round trip again.
c
The speed of light.

d = 3 m: fb = 1014 × 2 × 3 / 299,792,458 = 2.0 MHz  |  each metre adds 0.67 MHz

The trick is that the sensor never times anything. A 3 m target is a 20 ns delay, far too small to time with a plain counter, yet it becomes a 2.0 MHz tone, which an ordinary ADC samples with ease. The hardest part of the timing problem has moved from picoseconds to megahertz.

Resolution: two tones, one window

Two targets make two tones. The ADC records for the length of the chirp, Tc. A Fourier transform over a window of length Tc cannot tell two tones apart unless they differ by more than 1 / Tc (TI uses this condition). Convert that to distance using the beat formula: Δd = c / (2 S Tc). Since S Tc = B, the result is the key law of FMCW.

range resolution = c / (2B) = 299,792,458 / (2 × 4 × 109) = 3.75 cm

The resolution depends only on the bandwidth you sweep. A 1 GHz sweep gives 15 cm. A 4 GHz sweep gives 3.75 cm. Longer chirps do not help resolution, but they help the signal.

Reach is set by the ADC

The ADC samples the beat at Fs samples per second. It can only see tones below Fs / 2, the Nyquist limit (see Discrete Signals). A faster beat folds back and looks like a slower one. With Fs = 10 MHz the top tone is 5 MHz, so the longest range is 5 MHz / 0.667 MHz per metre = 7.5 m. A target at 12 m makes an 8 MHz beat, which folds to 2 MHz and shows up at 3 m. This ghost is the FMCW cousin of the wrap in Chapters 4 and 6.

Read two targets from one tone

The purple curve is the Fourier transform of 40 microseconds of mixer output from two targets. The dashed teal lines are the true distances. Pick a sweep and an ADC rate, then move the targets close together and far apart.

3.00 m
3.50 m

Computed live with a Hann windowed discrete Fourier transform of 40 microseconds of two tones, fb = 2 S d / c with S = B / 40 µs. The 4 GHz, 40 µs chirp is the TI SPYY005 example. Sampling is real valued, so tones above half the ADC rate fold. No noise is added.

Start at 4 GHz, 10 MHz, targets at 3.0 and 3.5 m: two clean peaks. Drag target 2 toward target 1. The window that tames leaks widens each peak to about two bins, so the pair merges below roughly 7 cm. The bare limit is 3.75 cm. Switch to 1 GHz and the pair merges below roughly 25 cm. Now slide a target past 7.5 m with the 10 MHz ADC. Its peak jumps back toward the sensor. Raise the ADC to 20 MHz and the true peak returns.

Velocity for free

If the target moves, its echo is shifted in frequency by the Doppler effect, the same shift that changes an ambulance siren. For a target closing at speed v the shift is fD = 2v / λ, where λ is the wavelength. For a laser at 1550 nm (an illustrative choice), 1 m/s gives 2 / 1.55 µm = 1.29 MHz. Pulse and phase sensors need two frames to guess speed. An FMCW sensor can read it from one chirp pair.

On real hardware. Board: STM32 Nucleo-G474RE. Use the DAC to make a sine at one fifth of the rate your ADC can sample (check the ADC section of DS12288 for the top rate). Capture 512 samples with DMA, apply a window, and run the FFT. The peak should sit near bin 102 (512 / 5). Then raise the tone past half the sample rate and watch the peak fold back to a lower bin, the ghost of this chapter.
A chirp sweeps 2 GHz. What range resolution does FMCW give?

Chapter 8

Choosing a Method

Set a range and an accuracy, and see what each of the three methods demands from its clock, its wave or its converter

A product manager walks in. The robot must see a pallet 20 m away and know its position to 5 cm. Which kind of sensor do you buy? The question hides a second one: what must the chip inside be able to do?

You now hold one formula for each method. Each says what limits it. Put them side by side and the answer becomes a short calculation.

QuestionPulse (dToF)Phase (iToF)Chirp (FMCW)
What the chip measuresA round trip time, in picosecondsFour charges, then an angleA beat frequency
What sets the accuracyTime step and edge noise (Chapters 1, 2)Frequency f and SNR (Eq. 6, Chapter 6)Sweep bandwidth, c / (2B)
What sets the reachPhotons, then pulse rate c / (2 frep)Wrap c / (2f), or two frequenciesADC rate, fold at Fs / 2
Firmware readsA time stamp or a histogramQ1 to Q4 per pixel, then atan2A block of ADC samples, then an FFT
Speed from one shotNoNoYes, from the Doppler shift
Typical failureWalk; ghost past the pulse periodWrap; whole-wrap unwrap errorFolded ghost beyond the ADC reach

Do the sum for a real brief

Work the pallet example. Range R = 20 m, accuracy 5 cm.

  1. Pulse. The time step must be 2 × 0.05 / c = 333 ps. That needs a time to digital converter or an HRTIM-class timer, not a plain 170 MHz tick (5.88 ns). The pulse rate must stay under c / (2 × 20) = 7.5 MHz.
  2. Phase. Use the illustrative rule of the device below: 5 cm needs about 20 MHz (a toy figure, not a datasheet value). To hold 5 cm you need about 20 MHz, but the wrap at 20 MHz is 7.5 m, short of 20 m. So you need two frequencies whose common step is 7.5 MHz or less, with at least one near 20 MHz.
  3. Chirp. The sweep must be at least c / (2 × 0.05) = 3 GHz. With a 40 µs chirp the slope is 75 MHz per microsecond, and the beat at 20 m is 10 MHz, so the ADC must run at 20 MHz or faster.

Now try a smaller brief: a gesture sensor that must see a hand at 3 m to 10 cm. The pulse sensor needs 2 × 0.10 / c = 667 ps, so an HRTIM-class step of 184 ps is plenty. The phase sensor needs about 10 MHz, and its wrap at 10 MHz is 15 m, so one frequency is enough. The chirp sensor needs a 1.5 GHz sweep, and the beat at 3 m is only 2 MHz, so a 1.5 MHz ADC rate would suffice by the rule in the device below, though the sweep hardware is expensive for the job. The smaller the brief, the more the cheap options win.

Three honest answers, three different shopping lists. None is better in general. The brief decides.

Write the shopping list

Each row shows the number a method must reach, as a bar on its own log scale. Markers show real parts and limits. Change the range and the accuracy you need.

20 m
5 cm

Rules used: pulse time step = 2 × accuracy / c, with markers at 5.88 ns (170 MHz timer), 184 ps (STM32G474 HRTIM), 90 ps and 22 ps (TDC-GP22 typical); phase frequency = 20 MHz × 5 cm / accuracy (the model of Chapter 5), tripled in sun, as an illustrative penalty; chirp bandwidth = c / (2 × accuracy) with a 40 µs chirp, ADC rate = 4 B R / (40 µs × c). Sunlight is not modelled for the chirp.

Drag the accuracy to 1 cm at 20 m. The pulse row needs 67 ps, past every part we listed. The phase row needs 100 MHz, far above its single frequency wrap. The chirp row needs 15 GHz. Each method hits its wall in a different place. Now move the range to 3 m and the accuracy to 10 cm: the phase sensor finds the job easy, the chirp is overkill, and a pulse sensor with a small TDC is fine.

The firmware cost is different too

The pulse sensor hands firmware a few numbers per shot, so a small MCU copes. The phase sensor hands over four values for every pixel, up to tens of thousands of pixels, so the data volume is large and the atan2 is often done in hardware. The chirp sensor hands over a block of samples that must be turned into spectra, which is an FFT job for a DSP core or a hardware block. The Cortex-M4 on the Nucleo-G474RE has a single-precision FPU and DSP instructions, enough for the small cases.

A design needs 5 cm accuracy at 20 m. Which statement matches the sums above?

Chapter 9

Reading Each One in Firmware

Follow the raw words from the sensor into your code, decode them into millimetres, and know which failures the chip will never tell you about

Your driver wakes up. A pin says "data ready". You read some bytes. What are they, and what must the code do before it can say "3.00 m" and mean it? The answer differs for each method, but the shape is the same: raw words in, a check on the raw words, a conversion, a distance and a flag out.

MethodRaw data per readingDecode stepWhat the code must check
PulseOne time count, plus a signal levelSubtract the path offset, multiply by the step, halveTimeout code, weak signal, rate limit
PhaseFour bucket values per pixelatan2 of two differences, scale by c / (4πf)Amplitude A, saturation, unwrap residual
ChirpA block of ADC samplesWindow, FFT, find the peak, scale bin to rangePeak height, fold limit, two close peaks

The data usually arrives by one of three routes. A time stamp or a few registers come over I2C or SPI after an interrupt. A block of ADC samples arrives by DMA into a buffer, and a half-transfer interrupt tells you the first half is ready. A whole frame of pixels arrives over a camera bus. See Timers, PWM and Sampling for the first two and Drivers, HAL and State Machines for how to wrap them in a driver.

Pulse: one count in, one distance out

The only arithmetic is a subtraction and a multiplication. Light covers 0.2998 mm in each picosecond, so half of that, 0.1499 mm, is the distance per picosecond of round trip. Note the three early returns: a timeout code, a count below the offset (which would go negative in unsigned maths), and a signal level too low to trust.

c
/* Decode one TDC reading. LSB_PS is the TDC step; off is the fixed path delay in counts. */
#define LSB_PS       90u
#define MM_PER_PS_RT 0.1498962f   /* c / 2 in mm per picosecond */

typedef struct { int32_t mm; uint8_t ok; } range_t;

range_t dtof_decode(uint32_t raw, uint32_t off, uint16_t signal) {
    range_t r = { 0, 0 };
    if (raw == 0xFFFFFFFFu || raw < off || signal < SIGNAL_MIN) return r;
    uint32_t t_ps = (raw - off) * LSB_PS;                  /* round trip in picoseconds */
    r.mm = (int32_t)(t_ps * MM_PER_PS_RT + 0.5f);
    r.ok = 1;
    return r;
}

Phase: four numbers in, an angle out

This is TI's Eq. 2 to 5 in code. The differences are signed, so use signed integers and convert to float only for atan2f. Then add the unwrap for two frequencies from Chapter 6. The residual comes back to the caller, so a fusion filter can weigh the reading.

c
#define TWO_PI   6.2831853f
#define C_MPS    299792458.0f

typedef struct { float m, amp, off; uint8_t ok; } itof_t;

/* Phase distance in metres, wrapped at c/(2f). Q1,Q3 are the aligned buckets. */
itof_t itof_decode(int32_t q1, int32_t q2, int32_t q3, int32_t q4, float f_hz) {
    float i = (float)(q1 - q2), q = (float)(q3 - q4);
    float phi = atan2f(q, i);
    if (phi < 0) phi += TWO_PI;                          /* 0 .. 2pi */
    itof_t r;
    r.m   = C_MPS * phi / (2.0f * TWO_PI * f_hz);              /* c*phi / (4*pi*f) */
    r.amp = 0.5f * sqrtf(i * i + q * q);                      /* A */
    r.off = 0.25f * (float)(q1 + q2 + q3 + q4);               /* B */
    r.ok  = (r.amp >= AMP_MIN) && (r.off + r.amp < SAT_LEVEL);
    return r;
}

/* Two frequencies: try every wrap count, keep the pair that agrees best. */
float unwrap2(float m1, float a1, float m2, float a2, float limit, float *resid) {
    float best = 1e9f, out = m1;
    for (float d1 = m1; d1 <= limit + a1; d1 += a1)
        for (float d2 = m2; d2 <= limit + a2; d2 += a2) {
            float e = fabsf(d1 - d2);
            if (e < best) { best = e; out = d1; }
        }
    *resid = best;                                         /* big residual: do not trust */
    return out;
}

Chirp: a block of samples in, a bin out

The ADC block holds 400 samples (10 MHz for 40 µs). The CMSIS-DSP real FFT needs a power of two, so pad to 512. That makes each bin 10 MHz / 512 = 19.5 kHz wide, which is 2.9 cm of range at the TI slope. The padding gives finer bin spacing, not finer resolution: that stays c / (2B). The packed output of arm_rfft_fast_f32 holds the Nyquist value in slot 1, so zero it before taking magnitudes.

c
#include "arm_math.h"
#define NS     400          /* samples in one chirp */
#define NFFT   512          /* next power of two */
#define FS_HZ  10000000.0f
#define SLOPE  1.0e14f      /* 100 MHz per microsecond, Hz per second */

static arm_rfft_fast_instance_f32 rfft;
static float32_t buf[NFFT], spec[NFFT], mag[NFFT / 2];
extern const float32_t hann[NS];     /* precomputed window */

void fmcw_init(void) { arm_rfft_fast_init_f32(&rfft, NFFT); }

/* Returns range in metres, or a negative number if no clear peak. */
float fmcw_range(const uint16_t *adc) {
    for (int n = 0; n < NFFT; n++)
        buf[n] = (n < NS) ? ((float)adc[n] - 2048.0f) * hann[n] : 0.0f;   /* remove DC, window, zero pad */
    arm_rfft_fast_f32(&rfft, buf, spec, 0);
    spec[1] = 0;                                   /* packed format: slot 1 is Nyquist */
    arm_cmplx_mag_f32(spec, mag, NFFT / 2);
    mag[0] = 0;                                    /* ignore DC */
    float32_t peak; uint32_t k;
    arm_max_f32(mag, NFFT / 2, &peak, &k);
    if (peak < PEAK_MIN) return -1.0f;
    float f_beat = (float)k * FS_HZ / NFFT;
    return 299792458.0f * f_beat / (2.0f * SLOPE);   /* d = c f / (2 S) */
}

Put numbers on the data flow. A pulse reading is a few bytes: one 32-bit count and one 16-bit signal level, 6 bytes. A phase pixel is four values, so a 320 × 240 frame holds 76,800 pixels × 4 values, which is 307,200 numbers per frame. A chirp of 400 samples in 16-bit words is 800 bytes, and if chirps ran back to back every 40 microseconds the stream would be 20 MB/s. Each size decides who does the maths. A few bytes fit in an interrupt handler. Hundreds of kilobytes need DMA and a processing block, and the heavy decode runs in the main loop or a hardware unit, not in the interrupt. Keep the interrupt short: copy or flag, then return.

Decode the raw words

The top row is what your code reads from the sensor, in hexadecimal. The bottom row is what it computes. Pick a method, drag the target out past the limit, and try a weak echo.

3.0 m

A model of the data, not a real part. Pulse: 90 ps step, a path offset of 33 counts, 1 MHz pulse rate. Phase: 20 MHz, A = 1000 and B = 1000 electrons (150 when weak), rejected below 300. Chirp: 10 MHz ADC, 12-bit samples around 2048, 512-point FFT, 100 MHz per microsecond slope. The word widths are illustrative.

Try each. In pulse mode, weak echo gives the timeout word and the decoder refuses. In phase mode, the decoder accepts a target at 9 m and reports 1.5 m with the status OK. In chirp mode, a target at 9 m folds to 6 m. The chip never says "wrapped". Only your code, using what it knows about the setup, can.

The failure, as symptom, measurement and fix

Symptom: a mapped wall jumps back by exactly 7.49 m for a few frames when a robot nears a long corridor. Measurement: log the amplitude and the unwrap residual for those frames. The distance changed by exactly c / (2f), and the amplitude is low. Fix: reject low amplitude, add a second frequency, and carry the residual into the filter.

On real hardware. Board: STM32 Nucleo-G474RE with a VL53L1X breakout. Read ten frames of range and signal rate over I2C into a ring buffer using the ST driver, then plot range against signal rate. Expect scatter to grow as the signal rate falls, the same shape as Chapter 3.
An iToF decoder returns OK with a high amplitude and a distance of 1.5 m, yet the real wall is 9 m away. What is the most likely cause?

Chapter 10

Field Guide

Keep the numbers, the checklist and the core code in one place, then follow the links onward

Light is the fastest clock you can use, and the hardest to read. A pulse sensor times the trip with a fine stopwatch. A phase sensor reads an angle from four buckets. A chirp sensor turns the delay into a tone. Each gets 1 ns = 15 cm right, and each hits a different wall: edge walk and pulse period, the phase wrap, the ADC fold. Firmware is the last line of defence against all three.

The numbers

QuantityValueWhere it comes from
Speed of light c299,792,458 m/sDefines the metre
Range per nanosecond of round trip14.99 cmc × 1 ns / 2
Time step for 1 mm6.7 ps2 × 1 mm / c; TI SLOA190B quotes 6.6 ps
170 MHz timer tick5.88 ns, 88 cmSTM32G474 datasheet DS12288, 170 MHz maximum
STM32G474 HRTIM step184 ps, 2.76 cmDS12288
TDC-GP22 step90 ps typ. (22 ps finest), 1.35 cm (0.33 cm)ScioSense datasheet
Pulse ambiguity rangec / (2 frep): 149.9 m at 1 MHzDerived in Chapter 4
Phaseφ = arctan((Q3 − Q4) / (Q1 − Q2)); d = cφ / (4πf)TI SLOA190B Eq. 2, 3
Phase ambiguityc / (2f): 7.49 m at 20 MHz, 1.50 m at 100 MHzTI SLOA190B Eq. 7
Phase noiseσ falls as 1/f and with more A, less BTI SLOA190B Eq. 6
FMCW beatfb = 2Sd / c; 0.67 MHz per metre at S = 100 MHz/µsTI SPYY005
FMCW resolutionc / (2B): 3.75 cm at 4 GHzDerived from Δf > 1/Tc (TI, Rao training series)
Doppler shift2v / λ: 1.29 MHz per m/s at 1550 nmStandard; wavelength is illustrative
VL53L1XUp to 4 m, up to 50 Hz, 940 nm Class 1 emitterST product page, DS12385

Checklist before you trust a range

  1. Units and the 2. Is the formula d = c t / 2, with t in seconds?
  2. Step size. Is the time step small enough for the accuracy you need? Compute 2 × accuracy / c.
  3. Start edge. Did you subtract the fixed path delay of the driver and the cable?
  4. Limit. What is c / (2 f), for the pulse rate, the modulation frequency or the ADC fold? Is every real target inside it?
  5. Signal. Did you read the amplitude or signal rate and reject weak echoes?
  6. Residual. With two frequencies, did you keep the disagreement and pass it on?
  7. Ambient. Did you test in the light the product will see?

The core as code

c
/* tof_math.h: the three conversions of this lesson, in one place. */
#define C_MPS 299792458.0

/* Pulse: round trip time (seconds) to one-way distance (metres). */
static inline double dtof_m(double t_s)                         { return C_MPS * t_s / 2.0; }
/* Pulse: farthest unambiguous target for a pulse rate. */
static inline double dtof_limit_m(double f_rep_hz)             { return C_MPS / (2.0 * f_rep_hz); }

/* Phase: radians (0..2pi) to metres; same formula gives the wrap distance for phi = 2pi. */
static inline double itof_m(double phi, double f_hz)       { return C_MPS * phi / (4.0 * 3.14159265358979 * f_hz); }

/* Chirp: beat frequency (Hz) to metres, for slope S (Hz per second); resolution from sweep B. */
static inline double fmcw_m(double f_beat_hz, double slope) { return C_MPS * f_beat_hz / (2.0 * slope); }
static inline double fmcw_res_m(double sweep_hz)           { return C_MPS / (2.0 * sweep_hz); }

Where it sits in the field

This is the first lesson of the ranging track. The next one, SPAD, TDC and the Histogram, builds the stopwatch and shows how a histogram fixes the walk of Chapter 2. Then Firing the Laser on Time covers scanning and eye safety, Peak Finding to Point Packets shows what leaves the sensor, PPS, NMEA, PTP and Motion Deskew keeps the timestamps honest, and VL53-Class Multizone ToF, Ultrasonic and mmWave Radar works through small parts.

For lidar as a sensor model inside a robot, see Sensors: Lidar, IMU and ICP and Lidar Inertial Factor Graphs. For fusing a noisy range with other sources, see Kalman Filter. For the timer and interrupt side, see Timers, PWM and Sampling, Embedded Real-Time Systems and From Vector Table to main. The wiring of a sensor into a robot is in Robot Sensor and Actuator Integration, and the sampling ideas are in Discrete Signals.

Sources

  1. Larry Li, Texas Instruments. Time-of-Flight Camera, An Introduction, SLOA190B, January 2014, revised May 2014. Equations 1 to 7 and the multi-frequency note.
  2. Cesar Iovescu and Sandeep Rao, Texas Instruments. The fundamentals of millimeter wave radar sensors, July 2020. Chirp, slope, IF tone Sτ, 77 GHz, 4 GHz, 40 µs example.
  3. Sandeep Rao, Texas Instruments. Introduction to mmWave Sensing: FMCW Radars. Range resolution c / (2B) and the 1 / Tc condition.
  4. STMicroelectronics. VL53L1X product page and datasheet DS12385. Range, rate and emitter.
  5. STMicroelectronics. STM32G474 product page and datasheet DS12288. 170 MHz core and the 184 ps HRTIM.
  6. ScioSense. TDC-GP22 time to digital converter. 90 ps typical and finer modes.
  7. Arm. CMSIS-DSP real FFT. Allowed lengths and the packed output.
The takeaway. A ranging sensor does not measure distance. It measures a time, a phase or a frequency, then multiplies by a constant. Every wall in this lesson comes from the quantity it measures: the step size of the time, the wrap of the angle, the fold of the tone. Know which one you hold, and you know where it will lie.

Now press Present or Teach and explain from memory how a 10 ns echo becomes 1.5 m, why a phase sensor at 20 MHz cannot see a wall at 9 m, and what the chirp sensor does that the other two cannot. Then go back to the target at the top, switch to Phase, drag past 7.49 m, and say out loud which chapter explains the jump.

Time of Flight Basics, Firmware from Zero to Expertise
← Back to microLearning