Wheels and gyros count motion, and their small errors add up with no limit. A laser scan of the walls, matched to a map, pulls the estimate back. In the toy below, a 0.5% wheel error leaves the estimate 0.6 m off after one lap. With scan matching, it stays about 1 cm off.
Pick wheels only or scan matching, set the wheel error, and watch the purple estimate against the teal robot. Then we build each piece: the error model, encoders, the IMU, LiDAR, point clouds, line fitting, ICP and fusion.
You need a little trigonometry and a little Python. We build the rest from zero.
Lesson 7 of 15 in our follow-along of Stanford AA 274A, Principles of Robot Autonomy I. Every idea is re-taught here in our own words and devices. Before: Lesson 6, Trajectory Tracking. Next: Lesson 8, Camera Models.
Illustrative toy: a 10 m by 6 m room and a 17.4 m loop. The robot drives the loop exactly; only its estimate drifts. Odometry assumes the nominal wheel radius and adds 0.4% random slip. Scan matching runs real ICP once a second on 72 beams against a map of the walls.
Chapter 0
Fire a range sensor at a wall and split its error into two parts
A robot points a laser at a wall 2.00 m away. It reads 2.03 m. Then 1.96 m, then 2.11 m. No reading is the truth, and the robot never sees the truth directly.
Every fact the robot holds enters through a sensor: a device that turns a physical quantity into a number. That number carries two kinds of error, and they need different cures.
Call the true distance v and the reading m. A bias, b, is a fixed offset that is the same on every reading. Noise, ε (epsilon), is a random jitter that changes on every reading. Its typical size is the standard deviation σ (sigma).
m equals v plus b plus epsilon, where epsilon is drawn from a normal distribution with mean zero and variance sigma squared.
Start from the true value v. Add the same bias b every time. Add a new random noise epsilon every time. The sum is the reading m.
With made-up numbers: v = 2.00 m, b = +0.05 m, and this time ε = −0.02 m. Then m = 2.00 + 0.05 − 0.02 = 2.03 m.
Press Stream for 30 readings. Raise the noise and the dots spread. Raise the bias and the whole cloud slides away from the pink truth.
Illustrative sensor. The noise is Gaussian; real sensors can have one-sided errors, such as sonar echoes off a slanted wall.
Work the number. Average 100 readings with σ = 0.12 m. The noise left in the average is 0.12 / √100 = 0.012 m. The bias stays at 0.05 m for any number of readings. Averaging beats noise. Only an outside reference beats bias.
| Word | Means | Set by |
|---|---|---|
| Accurate | the average sits on the truth | small bias b |
| Precise | readings cluster tightly | small noise σ |
The symptom is a robot that stops 5 cm short of every wall. To measure it, put a target at a taped distance, take 100 readings and compare their mean with the tape. The fix is to subtract that bias in software, and to check it again when the temperature changes.
Chapter 1
Drop each sensor into a two-by-two grid and read its typical failure
A delivery robot might carry wheel encoders, a gyro, a laser scanner and two cameras. Two questions sort all of them.
Tap a sensor. It lights in its cell, and the read-out says what it measures and how it usually fails.
Teal chips measure the robot; blue chips measure the world. The cell is where most textbooks put the common version of each sensor.
The split predicts the error. A proprioceptive sensor works in a clean, known place, so its errors are mostly bias, and calibration removes them. An exteroceptive sensor faces a messy world, so it needs interpretation (is this blob a wall?) and carries more random error.
One camera fact matters now. A plain camera measures the direction to a point, not its distance: one pixel stands for a whole ray. An RGB-D camera adds a depth value to every pixel with an active trick, a projected pattern or a small time-of-flight ranger. Lesson 8 builds the camera model.
Datasheets add a few more words. Resolution is the smallest change a sensor can tell apart. Bandwidth is how many readings it gives per second. Work the number: a LiDAR at 10 Hz on a robot at 2 m/s gives one scan every 2 / 10 = 0.2 m of travel. The robot is blind between scans.
The symptom is a heading that jumps each time the robot passes a steel shelf. This is cross-sensitivity: the compass also responds to nearby iron. To measure it, log the compass and the gyro heading side by side along the aisle. The fix is to give the compass low weight indoors, or drop it.
Chapter 2
Count wheel turns, add them up, and watch a 1% error bend the path
The cheapest way for a wheeled robot to know where it is: count how far each wheel turned. A wheel encoder does the counting. An optical encoder shines its own small light through slits in a disc on the axle, and a detector counts the flashes. Adding the counts into a pose is odometry, also called dead reckoning.
Say the disc has 2,000 slits. A second detector, offset by a quarter slit, gives the direction of turn and four countable edges per slit. This is quadrature: 8,000 counts per turn. With a wheel of radius 0.05 m, one turn rolls 2π × 0.05 = 0.314 m, so one count is 0.314 / 8,000 = 0.039 mm. A step of 400 counts is 1.57 cm.
A differential-drive robot has two driven wheels on one axle. Call the distance the right wheel rolls in one step ΔsR, the left one ΔsL, and the distance between the wheels L. The robot's forward step is the average of the two. Its turn, Δθ, comes from their difference.
Delta theta equals delta s R minus delta s L, all divided by L.
Take how much farther the right wheel rolled than the left, delta s R minus delta s L. Divide by the wheelbase L. The result is the turn delta theta. Then move the pose forward by the average roll along the heading.
With made-up numbers: ΔsR = 0.0160 m, ΔsL = 0.0154 m, L = 0.30 m. Δθ = 0.0006 / 0.30 = 0.002 rad, or 0.11° to the left. The forward step is 0.0157 m.
The robot steers by its own estimate, so the purple estimate stays on the warm plan. Press Drive and watch where the teal robot truly goes.
Illustrative toy: a 3 m square, wheelbase 0.30 m, steps of 1 cm. The wheel error and the slip apply to the true motion; the estimate assumes perfect wheels.
Why does it bend? Take only the 1% wheel error, L = 0.30 m, and a robot that believes it drives straight. Each metre, the right wheel rolls 1 cm more than the robot thinks, so the true heading turns 0.01 / 0.30 = 0.033 rad, or 1.9°. The heading error feeds the position error, and it compounds:
| Believed distance | Heading error | Sideways error |
|---|---|---|
| 1 m | 1.9° | 0.02 m |
| 3 m | 5.7° | 0.15 m |
| 5 m | 9.5° | 0.42 m |
The symptom is a robot that ends a closed loop far from where it started, sure that it is home. To measure it, drive a taped square both ways and measure the gap at the end. The fix has two parts: calibrate the wheel radii and the wheelbase, then correct the pose with an outside reference, such as a LiDAR scan.
Chapter 3
Leave a still robot with a biased gyro and watch its heading walk away
An inertial measurement unit (IMU) is the chip that knows your phone turned. It holds two kinds of sensor. A gyroscope measures the rate of turn, in degrees per second. An accelerometer measures acceleration. Both are proprioceptive, need nothing outside, and report hundreds of times a second.
A gyro gives a rate, not an angle. To get a heading, the robot adds up rate × time, again and again. That is integration, and it keeps every error.
Picture a robot parked on a table. Its true rate of turn is zero. The gyro has a constant bias b, in degrees per second. Call the starting heading θ0 and the heading estimate after t seconds θ(t).
Theta of t equals theta zero plus b times t.
Each second, the integration adds the bias b to the heading. After t seconds it has added b times t. The error grows in a straight line with time and never stops.
With a made-up b = 0.5°/s: after t = 60 s the error is 0.5 × 60 = 30°. After 360 s it is 180°. The parked robot thinks it faces backwards.
Press Run to let six minutes pass in a few seconds. The purple estimate creeps away from the teal truth at exactly bias × time. Choose Turn to add a real rotation.
Illustrative bias values; a real gyro's bias also wanders slowly and changes with temperature. Simulated time runs 60 times faster than real time.
The accelerometer has its own trap. At rest it reads 9.81 m/s² upward: it feels the table pushing against gravity. To get the robot's motion, the robot must subtract gravity, so it must know its tilt. Tilt comes from the gyro. Work the number: a tilt error of 1° leaves 9.81 × sin 1° = 0.17 m/s² of false acceleration. Integrated twice, that is ½ × 0.17 × 10² = 8.6 m of position error after 10 s.
So gyro error grows in a straight line, and position error from tilt grows with time squared. The IMU and Inertial Navigation lesson builds the full strapdown chain. Here, take the lesson: an IMU is right over short times and wrong over long times.
The symptom is a heading that creeps while the robot sits parked. To measure it, log the gyro for 60 s at rest: the average reading is the bias. The fix is to measure and subtract the bias at every start, then correct the heading with an absolute source (Chapter 9).
Chapter 4
Time a pulse, sweep the beam, and turn ranges and angles into points
The IMU says "I think I turned." A LiDAR (light detection and ranging) says "a wall is 2.00 m away at this angle." It measures the world directly, so its error does not pile up over time.
LiDAR is an active, time-of-flight sensor. It fires a short laser pulse and times the echo. Call the speed of light c and the round-trip time t. The light goes out and back, so the distance d is half the path.
d equals c times t, divided by two.
Multiply the speed of light c by the echo time t to get the whole path. Halve it, because the pulse went out and came back. That is the distance d.
A wall 3 m away: t = 2 × 3 / (3 × 108) = 20 ns. A timing error of 1 ns gives a range error of 0.3 / 2 = 0.15 m. LiDAR must time to a small fraction of a nanosecond.
Sound is much slower. Sonar at 343 m/s needs 17.5 ms for the same 3 m round trip, about 870,000 times longer.
A 2D LiDAR spins and fires beams at equal angle steps. Each beam returns a range ρ (rho) at a bearing θ (theta), measured from the robot's forward axis. A full sweep is a scan: a list of (ρ, θ) pairs. Maps use x and y, so each pair becomes a point (x, y) in the robot's frame.
x equals rho times cos theta, and y equals rho times sine theta.
Walk rho metres along the beam's bearing theta. The forward part of that walk is x; the sideways part is y.
A beam reads ρ = 2.50 m at θ = 30°. x = 2.50 × 0.866 = 2.165 m; y = 2.50 × 0.500 = 1.250 m. The hit is 2.17 m ahead and 1.25 m to the left.
Drag the teal robot. Each beam stops at the first wall it hits. Look for the shadows behind the boxes, then lower the maximum range.
Illustrative 10 m by 6 m room, with no range noise in this view. A real scanner also loses beams on black or glass surfaces.
The symptom is a map with a hole where a glass door stands: the beams pass through or scatter, and no echo returns. To measure it, count the no-return beams at each bearing. The fix is to store a no-return as "unknown", never "free", and to cover glass with another sensor, such as sonar.
Chapter 5
Thin a cloud with a voxel grid, then ask which point is nearest
Convert every beam and you get a point cloud: a list of N points, each an (x, y) pair. In code it is an N × 2 array (N × 3 in 3D). It makes no claims about walls or objects. It is only where echoes came from.
Two facts make clouds hard. They are big: one 3D sweep can hold hundreds of thousands of points. And they are unordered: point 5 in this scan and point 5 in the next scan are different places.
The first fix is downsampling with a voxel grid. Cut space into square cells, called voxels. Replace all the points in a cell with their average. A flat wall then keeps one point per cell.
The second tool is the nearest-neighbour query. Call the query point q and the cloud's points pj, numbered by j. We want the number j* of the closest one.
j star equals the argmin over j of the squared length of q minus p-j.
For each point p-j, take dx and dy to the query q, square them and add. Keep the j with the smallest sum. The square root is not needed, because the order of the sums is the order of the distances.
With made-up points: q = (1, 1).
p1 = (2, 1) gives 1 + 0 = 1. p2 = (1.5, 1.5) gives 0.25 + 0.25 = 0.5. p3 = (0, 3) gives 1 + 4 = 5. So j* = 2.
Turn the grid on and watch the count fall while the shape stays. Tap anywhere to find the nearest point.
Illustrative cloud: walls of the same 10 m by 6 m room sampled every 2.5 cm, with 1 cm of noise.
Why shrink first? With made-up sizes: matching two clouds of 20,000 points by brute force checks 20,000 × 20,000 = 4 × 108 pairs. After a grid leaves 400 points each, it checks 160,000 pairs: 2,500 times fewer. A k-d tree cuts the search further, to about log N steps per query.
The symptom is a thin pillar that vanishes and corners that round off. The voxel is larger than the features. To measure it, overlay the thinned cloud on the raw cloud and look at corners. The fix is a voxel smaller than the smallest thing the robot must see.
Chapter 6
Fit a line, find the worst point, split there, and repeat
A planner wants "a wall runs from here to there", not 300 dots. Rooms are mostly straight edges, so 2D LiDAR perception often fits straight segments to the scan. This is line extraction.
The form y = mx + c fails for a vertical wall: the slope is infinite. Use two other numbers instead. Call the shortest distance from the robot to the line r, and the angle of that shortest path α (alpha). For a scan point (xi, yi), call its signed distance to the line di.
d-i equals x-i cos alpha plus y-i sine alpha, minus r.
Measure how far point i reaches in the direction alpha. Subtract r. The rest is d-i, its distance off the line. The best line picks alpha and r so the sum of all the d-i squared is smallest. This is least squares.
Five made-up points near a wall at x = 2: (2.02, −1), (1.98, −0.5), (2.01, 0), (1.99, 0.5), (2.00, 1). Try α = 0 and r = 2.00: the di are 0.02, −0.02, 0.01, −0.01, 0. Their squares sum to 0.0010 m². The exact best fit tilts α to 0.34° and lowers the sum to 0.00091.
One line fits one wall. A scan sees many walls. Split-and-merge cuts the scan into one group per wall:
Press Step. Each step joins a segment's end points with a dashed line, rings the worst point, then splits or keeps it. Lower the threshold and watch the walls break into more pieces.
Illustrative scan of three walls, 60 points. This is the end-point form of split-and-merge. Kept lines are perpendicular least-squares fits; segments under 5 points are dropped.
The lab below fits one wall with the slope form, on a tilted wall where the slope stays finite. The polar form above handles every angle.
The symptom is a fitted wall that tilts toward one stray return, such as a reflection. Squaring makes a far point count a lot. To measure it, compare the worst point's distance with the typical distance. The fix is to split or drop that point, or to use RANSAC, which fits to the points that agree (Lesson 9).
Chapter 7
Pair the points, centre both clouds, rotate with the SVD, then shift
The robot holds a model cloud: a map, or its last scan. It moves and scans again. Both clouds show the same walls, turned and shifted by a motion that odometry knows only roughly.
Find the rotation R and the shift t that lay the new scan onto the model. That pair is the robot's motion, read from the walls. Iterative closest point (ICP) repeats four steps:
Call the paired scan points pi and model points qi. Call their averages p̄ and q̄ (p-bar, q-bar). The centred points are p′i = pi − p̄ and q′i = qi − q̄. The cross-covariance H adds up how the pairs line up.
H equals the sum over i of p-prime-i times q-prime-i transposed.
For each pair, multiply the column p-prime-i by the row q-prime-i to get a 2 by 2 table. Add the tables for all pairs. The total is H.
For the three pairs in the table below: H11 = −0.111 + 0.222 + 0.222 = 0.333, H12 = 0.667, H21 = −0.667, H22 = −0.333.
The singular value decomposition (SVD) splits any matrix into a rotation, a stretch and a rotation: H = UΣV⊤. The best rotation keeps the two turns and drops the stretch.
R equals V times U transposed, and t equals q-bar minus R times p-bar.
Take the SVD of H. Multiply V by U transposed to get R. If R has determinant minus one, it is a mirror: flip the sign of V's last column and multiply again. Then turn the scan's average p-bar by R and shift it onto the model's average q-bar. The shift is t.
For the H above, R = [[0, −1], [1, 0]], with determinant +1: a turn of +90°. R p̄ = R(1.333, 0.333) = (−0.333, 1.333), which equals q̄, so t = (0, 0).
| Pair | Model q | Scan p | q′ = q − q̄ | p′ = p − p̄ |
|---|---|---|---|---|
| 1 | (0, 1) | (1, 0) | (0.333, −0.333) | (−0.333, −0.333) |
| 2 | (0, 2) | (2, 0) | (0.333, 0.667) | (0.667, −0.333) |
| 3 | (−1, 1) | (1, 1) | (−0.667, −0.333) | (−0.333, 0.667) |
Averages: q̄ = (−0.333, 1.333) and p̄ = (1.333, 0.333). The scan is the model turned by −90°, so ICP must find +90°. In 2D the SVD answer reduces to one angle, and this page's devices use that shortcut:
angle = atan2(Σ(p′xq′y − p′yq′x), Σ(p′xq′x + p′yq′y)) = atan2(1.333, 0) = 90°
Press Next to run the four steps on the three pairs of the table. Watch the blue scan land on the purple model.
Here the table gives the pairs by index; in a real scan, step 1 finds them by nearest neighbour.
The symptom is a scan that lands mirrored. Plain V U⊤ can return a reflection, which no robot makes. To measure it, check det(R): +1 is a rotation, −1 a mirror. The fix is the flip of V's last column.
Chapter 8
Run the loop to convergence, then turn the scan so far that ICP locks on wrong
Now the whole loop, on a real-sized cloud. The purple model is the room corner the robot already has. The blue scan is a fresh sweep, turned and shifted by the motion the robot does not know, with noise. They show the same walls but do not line up.
Press Step: grey lines show each scan point's partner, then the scan moves. Press Run to finish. Then raise the starting turn past about 45° and run again.
Illustrative clouds. The scan samples the walls at other spots than the model, as a real second scan would. Point-to-point ICP with the 2D closed-form rotation.
Watch the rhythm: pair, move, smaller error, repeat. The alignment error is the average distance from each scan point to its partner. Early iterations make big moves; later ones polish. Stop when the error stops falling, or after a set number of iterations.
With the default 35° turn, ICP lands within a degree of the true motion in about 20 iterations. That recovered turn and shift is a measurement of motion that does not drift. Feed it to localization and it pulls odometry back, as in the hero. Stack many such matches and you have a map, which Lesson 11 builds.
A common upgrade is point-to-line ICP. It measures each scan point's distance to the model's wall, not to one model point. Sliding along a wall then costs nothing, which matches the geometry, and it needs fewer iterations in rooms.
The symptom is a confident wrong answer: the error settles low, but the pose is wrong. ICP only finds a local minimum: the best answer near its start. To measure it, compare the result with the odometry guess, and count pairs closer than 5 cm. The fix is to start ICP from the odometry guess, which is why we keep the wheels and the IMU.
Chapter 9
Weight two readings by how sure each sensor is, and blend fast with absolute
A LiDAR says the wall is 5.00 m away. A sonar says 5.40 m. A plain average, 5.20 m, trusts the coarse sonar as much as the sharp LiDAR. Sensor fusion combines readings so the result beats each sensor alone.
The rule: weight each reading by how sure its sensor is. Call the readings m1 and m2, and their noise variances σ12 and σ22 (sigma one squared, sigma two squared). Call the fused estimate m̂ (m-hat).
m-hat equals sigma two squared times m one, plus sigma one squared times m two, all over sigma one squared plus sigma two squared.
Weight each reading by the other sensor's variance, so the surer sensor counts more. Divide by the total weight. The fused variance, the product of the variances over their sum, is smaller than either.
With made-up numbers: m1 = 5.00, σ12 = 0.01; m2 = 5.40, σ22 = 0.09. m̂ = (0.09 × 5.00 + 0.01 × 5.40) / 0.10 = 5.04 m. Fused variance = 0.0009 / 0.10 = 0.009, below both 0.01 and 0.09.
Set how noisy each sensor is. The purple fused bell leans toward the narrower blue one, and it is narrower than both.
Readings fixed at 5.00 m and 5.40 m, made-up. The device treats both sensors as unbiased, with Gaussian noise.
Fast and absolute sensors pair the same way over time. A complementary filter follows the gyro over short times and leans gently on an absolute heading, such as a LiDAR scan match. Call the last estimate θ̂prev, the gyro rate ω (omega), the time step Δt, the absolute heading θabs, and the blend weight a, just under 1.
Theta-hat equals a times, theta-hat previous plus omega delta t, plus one minus a, times theta absolute.
Move the last estimate by the gyro's turn. Keep the share a of that. Take the small share 1 minus a from the absolute heading. Each step pulls the drift back a little.
With made-up numbers: the gyro path says 30.0°, the absolute heading says 28.0°, a = 0.98. θ̂ = 0.98 × 30.0 + 0.02 × 28.0 = 29.96°. At 100 Hz with a 0.5°/s gyro bias, the error settles at 0.25° and stops growing.
The Kalman filter of Lesson 13 replaces the fixed weight a with the best weight at each step. The complementary filters lesson covers the IMU case.
The symptom is a fused estimate that follows a bad sensor whose stated variance is too small. To measure it, compare each sensor with a reference and compute the real spread. The fix is to set each variance from measured data.
Chapter 10
Keep the terms, the numbers, the code and the next steps in one place
Every reading is truth plus bias plus noise. Wheels and gyros integrate, so their errors grow without limit. LiDAR measures the world, and ICP turns two scans into a motion that does not drift. Fusion weights each source by how sure it is.
| Term | Meaning | Number to remember |
|---|---|---|
| Error model | m = v + b + ε | 100 readings: noise 0.12 to 0.012 m, bias unchanged |
| Sensor classes | self or world; listens or shouts | LiDAR: exteroceptive, active |
| Odometry turn | Δθ = (ΔsR − ΔsL) / L | 1% wheel error, L = 0.30 m: 0.42 m off after 5 m |
| Gyro drift | θ(t) = θ0 + b t | 0.5°/s: 30° in a minute |
| Time of flight | d = c t / 2 | 3 m: 20 ns; 1 ns error: 0.15 m |
| Scan to points | x = ρ cos θ, y = ρ sin θ | 2.50 m at 30°: (2.165, 1.250) |
| Line fit | minimise Σ di2 | 5 points near x = 2: sum 0.00091 m² |
| ICP rotation | H = Σ p′q′⊤, R = V U⊤, t = q̄ − R p̄ | 3-point example: +90°, t = 0 |
| Fusion | weight by the other variance | 5.00 and 5.40: 5.04 m, variance 0.009 |
python import numpy as np def best_fit_transform(P, Q): # P, Q: N x 2, paired by row pbar, qbar = P.mean(0), Q.mean(0) # averages H = (P - pbar).T @ (Q - qbar) # 2 x 2 cross-covariance U, S, Vt = np.linalg.svd(H) R = Vt.T @ U.T # R = V U^T if np.linalg.det(R) < 0: # a mirror: flip V's last column Vt[-1] *= -1; R = Vt.T @ U.T return R, qbar - R @ pbar # t = qbar - R pbar def icp(scan, model, iters=20, tol=1e-5): src, last = scan.copy(), np.inf for _ in range(iters): d2 = ((src[:, None, :] - model[None]) ** 2).sum(-1) # all squared distances j = d2.argmin(1) # nearest model point per scan point err = np.sqrt(d2[np.arange(len(src)), j]).mean() if last - err < tol: break # stopped improving R, t = best_fit_transform(src, model[j]) src, last = src @ R.T + t, err return src, err
Based on Stanford AA 274A, Principles of Robot Autonomy I. This page re-teaches the course's sensors lesson in our own words, devices and toy numbers.
Now press Present or Teach. Explain from memory: bias and noise, why wheels and gyros drift, time of flight, one ICP iteration and the fusion weights. Then go back to the laps, switch scan matching on and off, and say why one estimate stays put.