Primers
Encoders and odometry
An encoder counts how far a motor’s shaft has turned. Odometry turns those counts into how far the robot has gone. Together they let a robot say “I’ve driven 80 cm” with nothing outside it measuring. They’re also why it slowly gets lost: every small error adds up, and nothing in the counts ever corrects it.
The examples on this page use a small robot with 60 mm wheels and an encoder on each motor, a common setup for desk robots. Pick your level at the top of the page.
High school
Counting turns
Picture a wheel with a sticker on it. Every time the sticker comes round, you add one to a tally. If the wheel is 19 cm round, ten stickers means the robot rolled about 1.9 m. That’s odometry: counting turns, and multiplying by how far one turn goes.
An encoder does the counting for you, very finely. On the back of many small motors is a magnet that spins with the shaft. Two sensors next to it, A and B, flip between on and off as the magnet’s poles go past. Each flip is one count. A wheel turn is thousands of counts, so the robot can tell distance to well under a millimetre.
Which way is it going?
One sensor can tell the shaft is turning, but not which way. Two can, because they’re placed so they don’t flip at the same moment. Going forward, A flips just before B. Going backward, B flips first. It’s like two people clapping in turn: who claps first tells you which way the line is facing.
The gearbox
The motor spins fast, and a gearbox slows it down for the wheel. The encoder sits on the motor’s side, so it sees many motor turns for every wheel turn. That’s good news: more counts per wheel turn means finer measurement.
You don’t need to know the gearbox’s numbers. Turn the wheel exactly once by hand and read the count. That number is called counts per wheel turn.
From counts to distance
One wheel turn moves the robot the wheel’s circumference: π × diameter. A 60 mm wheel goes π × 60 ≈ 188.5 mm a turn.
distance = counts ÷ counts per wheel turn × 188.5 mm
For example, if one wheel turn is 4,300 counts and the encoder has counted 21,500, the wheel turned 5 times, and the robot rolled about 5 × 188.5 ≈ 943 mm.
Why it gets lost
Odometry trusts that every turn of the wheel moved the robot one circumference. Sometimes that isn’t true:
- The wheel is a different size than you think. If the tire is really 58 mm, not 60, every turn goes 3% less far than the robot believes. Over 10 m, that’s 30 cm out.
- The wheel slips. On a smooth desk, or while turning, a wheel can spin without the robot moving as far.
Small errors keep adding up, the way a watch that’s a second fast each day is a minute out after two months. The fix is a landmark: something outside the robot that tells it exactly where it is, like a camera overhead or the edge of the desk. After that, the counts only have to be right since the last landmark.
Turning
Many small robots have four wheels that can’t steer. They turn by running one side faster than the other, so the wheels drag sideways and slip. Counting the wheels gives a poor answer for how far such a robot turned, so it uses a different sensor for turning: a gyroscope, which measures rotation directly. Using each sensor for what it’s best at is a common trick in robots.
Check yourself
- One wheel turn is 4,300 counts. The encoder reads 8,600. How far did the robot roll?
- The robot thinks it drove 1 m, but a tape measure says 1.05 m. Is the real wheel bigger or smaller than the robot thinks?
- Why can’t the robot use wheel counts alone to stay on track all day?
<details><summary>Answers</summary>
- 8,600 ÷ 4,300 = 2 turns, × 188.5 mm ≈ 377 mm.
- Bigger. Each real turn goes further than the robot believes, so it travels more than it counts.
- Small errors from wheel size and slip add up with every turn, and nothing in the counts corrects them. It needs a landmark now and then.
</details>
College
Quadrature
A common small-motor encoder is a magnet disc on the motor’s shaft and two hall sensors, A and B. An optical encoder, with a slotted disc and a light, works the same way. The two channels are placed a quarter of a cycle apart. This is quadrature:
forward: A _|‾‾|__|‾‾|__ backward: A _|‾‾|__|‾‾|__
B __|‾‾|__|‾‾|_ B |‾‾|__|‾‾|___
A rises first B rises first
Which channel moves first gives the direction. Each channel goes up and down once per cycle, so there are four edges per cycle. Counting all four is x4 quadrature: four times the resolution of counting one channel’s rising edges.
The pair (A, B) steps through four states in a fixed order, a Gray code: only one channel changes at a time. A step one way round the order is +1, the other way −1. A jump of two states means a step was missed, because the reader sampled too slowly.
Counts per wheel turn
The encoder sits before the gearbox, so:
counts per wheel turn = pulses per motor turn × 4 × gear ratio
A listing’s numbers are often wrong or missing, so measure it. Turn the wheel once by hand and read the total.
You can also estimate it. Say an encoder gives 7,500 edges a second while the wheel turns at 105 RPM, 1.75 turns a second. Then a wheel turn is about 7,500 ÷ 1.75 ≈ 4,300 counts.
Counts to distance
distance = counts ÷ counts per wheel turn × π × D
With D = 60 mm, a turn is 188.5 mm. At about 4,300 counts a turn, one count is about 0.04 mm. The counts are much finer than anything else in the chain. The error comes from elsewhere.
Direction signs
Whether forward counts up depends on the wiring and on the side of the robot. Left and right motors face opposite ways, so one side usually counts backwards. Each motor gets a sign, +1 or −1, multiplied in so forward always counts up.
Two sides: distance and turn
Each side gives a distance. For a differential drive, with track width b (the distance between the left and right wheels):
forward = (left + right) ÷ 2
turn (radians) = (right − left) ÷ b
With a 12 cm track, the right side going 2 cm further than the left is 2 ÷ 12 ≈ 0.17 rad, about 10°.
This works for two wheels and a caster. Four fixed wheels turn by skid steering: the tires drag sideways in every turn, so the sides’ difference overstates the turn. Such robots usually take their heading from a gyro instead.
Drift
Every odometry error accumulates:
- Diameter. A 58 mm tire set as 60 mm overcounts 3.4% on every turn. After a metre the robot thinks it went 1.034 m. This error is systematic: the same every turn, so it grows in step with distance. Measure the tire with calipers.
- Slip. A wheel spinning, or dragged in a turn, counts distance that wasn’t travelled.
- Squash and wear. A soft tire under load rolls on a slightly smaller diameter than it measures.
The cure is a landmark: an overhead camera, or a desk’s edge, resets the position. Then the count only has to be good since the last one.
Counting in hardware
At thousands of edges a second, counting in software interrupts eats processor time and can miss edges. Many microcontrollers count them in hardware: the ESP32’s pulse counter (PCNT), or an STM32 timer in encoder mode. These counters are often 16 bits, so they wrap round within seconds at full speed. The program reads each counter often, every 10 ms say, and adds the change to a much larger total. As long as fewer than half the counter’s range passes between two readings, the change can’t be misread.
A counter counts any edge, noise included. Most have a glitch filter that ignores pulses too short to be real. Noise comes from motor wiring run beside the encoder’s, and sometimes from the chip itself: Espressif’s errata for the original ESP32 report that reading its analogue inputs can briefly pull two of its pins (36 and 39) low.
Check yourself
- One wheel turn reads 4,312 counts. The left side reads 22,869. How far has it gone?
- Over a measured metre the odometer says 0.97 m. Name two possible causes, and the fix for each.
- Why does a four-wheel skid-steer robot take its heading from a gyro, not the difference between its sides?
- Why would counting only A’s rising edges make it slower to notice that a motor has stalled?
<details><summary>Answers</summary>
- 22,869 ÷ 4,312 ≈ 5.30 turns, × 188.5 mm ≈ 1.0 m.
- The tire is bigger than the code says: caliper it and fix the diameter. Or counts per wheel turn is set too high (the hand turn went past the mark): measure again and average. Slip makes it read high, not low, so it isn’t the cause here.
- Skid-steered wheels slip sideways in every turn, so the sides’ difference overstates the turn. The gyro measures rotation directly.
- It’d see a quarter as many counts, so a slow or stuck motor shows “no movement” for longer before it’s clear. More edges give a faster, surer answer.
</details>
University
Resolution and quantisation
With N counts per wheel turn and wheel radius r, one count is Δs = 2πr ÷ N. For N ≈ 4,300 and r = 30 mm, Δs ≈ 0.044 mm. A position read from a count carries a quantisation error uniform over one count, a standard deviation of Δs ÷ √12, about 0.013 mm. That’s negligible for position. It isn’t negligible for speed.
Estimating speed
There are two ways to get a speed from an encoder:
- Counts in a fixed time (the M method). Read every 10 ms at 7,500 edges a second and that’s about 75 counts per window, so one count is a 1.3% step in speed. At a tenth of that speed it’s 7 or 8 counts, a 13% step. Slow speeds are coarse.
- Time between edges (the T method). Time one edge to the next with a fast clock. It’s fine at low speed and coarse at high speed, where edges come close together.
The M/T method combines them: count the edges in a window, and time the window from the first edge to the last. A speed controller holding a slow speed either uses a longer window, filters the estimate, or times edges.
Differential-drive kinematics
With left and right travel Δsₗ and Δsᵣ over one step, and track width b:
Δs = (Δsᵣ + Δsₗ) ÷ 2, Δθ = (Δsᵣ − Δsₗ) ÷ b
x += Δs cos(θ + Δθ/2), y += Δs sin(θ + Δθ/2), θ += Δθ
Using the heading at the middle of the step (θ + Δθ/2) is a second-order integration. It’s exact for an arc’s chord direction and keeps the error small at 100 Hz.
Skid steering and the effective track
Four fixed wheels can’t all roll without slip in a turn. The instantaneous centre of rotation sits off the axles, and the tires scrub sideways. One model keeps the differential-drive equations but replaces b with an effective track bₑ > b, found by experiment. bₑ depends on the surface, the load and the turn rate, so it isn’t one number. That’s why skid-steer robots usually take θ from a gyro. A common fusion is a complementary filter: the gyro for fast changes, a slow correction from something absolute (a camera, a magnetometer).
Error growth
Errors split into two kinds:
- Systematic: wrong diameter, unequal wheel diameters, wrong track width. These are deterministic, so they grow linearly with distance. Unequal diameters make a straight drive curve, and a wrong b scales every turn.
- Non-systematic: slip, bumps, quantisation. These are random. Treated as independent per-step errors, the along- track variance grows linearly with distance, so the standard deviation grows like √d. A random walk in heading is worse: the cross-track error integrates the heading error, and its standard deviation grows like d^3/2.
Systematic errors are calibrated out. Borenstein and Feng’s UMBmark drives a square several times clockwise and several times anticlockwise. The repeats show how much is random, and where the two directions’ end points cluster separates their two systematic errors: unequal wheel diameters (Type B) and a wrong track width (Type A). Random errors are bounded only by an outside reference, such as an overhead camera or a known edge.
Wrap-around arithmetic
A counter that wraps at ±L is read as c₀, then c₁. The true change is the representative of c₁ − c₀ mod L in [−L/2, L/2). That’s correct only if fewer than L/2 counts pass between reads, so the read period sets a speed limit. With L = 30,000, reads every 10 ms and 7,500 counts a second, 75 counts pass, a margin of 200 times. A 32-bit total at full speed lasts about 3 days of continuous driving.
Check yourself
- A robot holds 15% of a 7,500-edge-a-second full speed with a 10 ms window. How coarse is one count of speed, and what would you change?
- A robot drives a 4 m square once clockwise and once anticlockwise, and ends 12 cm and 2 cm from the start. Can you say yet whether that’s systematic or random error? What would you do next?
- Why does cross-track error from a heading random walk grow faster than along-track error?
- With 32-bit totals at full speed, roughly how long until a total overflows? Does it matter?
<details><summary>Answers</summary>
- About 75 × 0.15 ≈ 11 counts per window, so a count is about 9% of the speed. Lengthen the window, filter the estimate, or time edges (the T or M/T method).
- Not yet. One run each way can’t tell a systematic error from a random one: random slip alone could leave those misses. Repeat each direction several times. Tight clusters away from the start mean systematic error, and UMBmark reads which kind (unequal diameters or track width) from where the clockwise and anticlockwise clusters fall relative to each other. A wide scatter means random error, which only an outside reference bounds.
- Cross-track error is the integral of the heading error over distance. A random walk in heading already grows like √d, and integrating it adds another factor of d.
- 2³¹ ÷ 7,500 ≈ 286,000 s, about 3.3 days. It doesn’t matter for a run, but a long-lived robot should take differences, not absolute totals.
</details>
Try it
Without hardware
You need Python 3. Save this as quadrature.py. It decodes A and B the way a hardware counter does, then shows what
a wrong wheel size does to a metre:
import math
# The four states (A, B) go round in this order when the shaft turns forward: A rises first.
ORDER = [(0, 0), (1, 0), (1, 1), (0, 1)]
POS = {state: i for i, state in enumerate(ORDER)}
def decode(samples):
"""Count every edge (x4): +1 a step forward round ORDER, -1 a step back."""
count = 0
for prev, cur in zip(samples, samples[1:]):
step = (POS[cur] - POS[prev]) % 4
if step == 1:
count += 1
elif step == 3:
count -= 1
elif step == 2:
print(f" {prev} to {cur} skips a state: sampled too slowly")
return count
forward = ORDER * 5 + [ORDER[0]] # five cycles forward
backward = forward[::-1]
print("forward:", decode(forward))
print("backward:", decode(backward))
print("too slow:", decode([(0, 0), (1, 1), (0, 0)]))
# Odometry with the wrong wheel size: the tire is 58 mm, the code says 60 mm.
N = 4300 # counts per wheel turn
true_d, code_d = 0.058, 0.060
counts = round(1.0 / (math.pi * true_d) * N) # what one real metre produces
print("counts for a real metre:", counts)
print("odometer says: %.3f m" % (counts / N * math.pi * code_d))
Run it:
python3 quadrature.py
Five cycles forward are 20 counts (x4), backward −20, and a skipped state can’t be counted either way:
forward: 20
backward: -20
(0, 0) to (1, 1) skips a state: sampled too slowly
(1, 1) to (0, 0) skips a state: sampled too slowly
too slow: 0
counts for a real metre: 23599
odometer says: 1.034 m
Change code_d to 0.058 and the odometer reads 1.000 m.
With a robot
On any robot that prints its encoder totals, with its wheels off the ground and a strip of tape:
- Put a tape flag on one wheel, lined up with a mark on the body.
- Turn that wheel slowly by hand, forward, exactly one full turn back to the mark. Write down the count.
- Do it twice more and average the three. Lining the flag up by hand is good to about a millimetre, which is about 20 counts on a 4,300-count wheel, so the readings will differ by tens of counts, a few tenths of a percent. The average is counts per wheel turn.
- Repeat for every wheel. Identical motors should match.
- Turn each wheel by hand the way it turns when the robot drives forward. A wheel whose count goes down needs its sign flipped.
Then drive a measured metre and compare the odometer with a tape measure.
Learn more
- Wikipedia’s incremental encoder page, for quadrature.
- Wikipedia’s odometry page, for its history and its drift.
- J. Borenstein and L. Feng, “Measurement and Correction of Systematic Odometry Errors in Mobile Robots,” IEEE Transactions on Robotics and Automation, 1996: the UMBmark test.