Counting wheel turns
Most robots that work among people roll. A robot vacuum crosses a living room in Seoul; warehouse robots carry shelves to pickers in Poland and Brazil; a hospital cart robot delivers medicines along corridors; a Mars rover picks its way between rocks. Wheels are efficient, simple, quiet and stable, and on a reasonable floor they beat legs on almost every measure except the ability to climb stairs.
Every one of these robots answers two questions many times a second. Forward: if I spin my wheels at these speeds, how will I move? Backward: my wheels have turned this much since I last checked, so where am I now? The second question, answered by adding up wheel motion, is odometry, the robotic version of the dead reckoning that ship navigators used for centuries: known speed, known heading, known time, therefore known position. Like dead reckoning, it is wonderfully simple and slowly, inevitably wrong.
This lesson builds the kinematic models of the common drive types, from the two-wheeled differential drive to cars and omnidirectional platforms, uses them to compute odometry from encoder ticks, and then measures how its errors grow. Poses are the transforms of Frames and rigid transforms: a position and a heading , with the body frame's axis pointing forward and to the left.
The differential drive
A differential-drive robot has two driven wheels on a common axle, one on each side, plus one or more passive casters for balance. It steers by driving the wheels at different speeds, as a tank or a wheelchair does. Most robot vacuums, many warehouse robots and nearly all educational robots work this way.
Let each wheel have radius , let the distance between the wheels' contact points (the track width) be , and let the wheels turn at angular speeds and , so that their rims move over the floor at and .
When the two speeds differ, the robot turns about a point on the line of the axle, the instantaneous centre of rotation (ICR). Every point of a rigid body turning at rate about a point moves with speed times its distance from that point. If the ICR is a distance to the left of the axle's midpoint, the wheels are at distances and , so and . Adding and subtracting:
Three special cases tell you everything about driving one. Equal speeds: , a straight line. Equal and opposite speeds: , the robot spins on the spot (). One wheel stopped: the robot pivots about that wheel ().
Definition— Unicycle model
The unicycle model describes a planar robot by its pose and two inputs, the forward speed and the turn rate :
A differential drive is a unicycle whose inputs are set by the wheel speeds through the formulas above.
The program computes and the turning radius for a small robot ( mm, mm) and then integrates the model for five seconds, once exactly and three times with Euler's method.
import numpy as np
r, b = 0.033, 0.160 # wheel radius and track width (distance between the wheels), metres
def body_velocity(wL, wR):
"""Wheel angular speeds (rad/s) -> forward speed v (m/s) and turn rate omega (rad/s)."""
v = r * (wR + wL) / 2
omega = r * (wR - wL) / b
return v, omega
print(" wL wR | v (m/s) omega (rad/s) turning radius v/omega")
for wL, wR in [(10, 10), (10, 12), (0, 10), (-10, 10), (12, 10)]:
v, w = body_velocity(wL, wR)
radius = "straight line" if w == 0 else f"{v / w:+.3f} m"
print(f"{wL:4} {wR:6} | {v:7.3f} {w:10.4f} {radius}")
def step_exact(x, y, th, v, w, dt):
"""Constant v and omega for dt: the robot follows a circular arc (or a line if omega = 0)."""
if abs(w) < 1e-12:
return x + v * dt * np.cos(th), y + v * dt * np.sin(th), th
R = v / w
return (x + R * (np.sin(th + w * dt) - np.sin(th)),
y - R * (np.cos(th + w * dt) - np.cos(th)),
th + w * dt)
def step_euler(x, y, th, v, w, dt):
return x + v * dt * np.cos(th), y + v * dt * np.sin(th), th + w * dt
v, w = body_velocity(10, 12)
T = 5.0
exact = step_exact(0.0, 0.0, 0.0, v, w, T)
print(f"\nafter {T} s on the arc: x = {exact[0]:.4f}, y = {exact[1]:.4f}, heading = {np.degrees(exact[2]):.2f} deg")
for dt in [0.5, 0.1, 0.01]:
p = (0.0, 0.0, 0.0)
for _ in range(round(T / dt)):
p = step_euler(*p, v, w, dt)
err = np.hypot(p[0] - exact[0], p[1] - exact[1])
print(f"Euler steps of {dt:4} s: position error {err * 1000:7.2f} mm")For constant and the robot follows a circular arc, and the arc has a closed form, and similarly for . In the language of the first lesson, the arc is the exponential of a constant body velocity, , composed on the right because the velocity is expressed in the robot's own frame. Euler's method, which assumes the heading stays fixed during each step, drifts off the arc: 156 mm in 5 s with half-second steps, and still 3 mm with 10 ms steps. The error is proportional to the step size, as a first-order method's should be (Lumenary Math's Numerical methods explains why). Odometry code therefore either uses the exact arc or, as below, the heading at the middle of each step, which is far more accurate for the same cost.
Nonholonomic constraints: why a car can't drive sideways
A wheel that rolls without slipping cannot move along its own axle. For a differential drive, the axle midpoint can move only along the robot's heading, so its velocity has no sideways component:
This is a constraint on velocities. The robot has three degrees of freedom of position (, , ) but only two of velocity (, ).
Definition— Holonomic and nonholonomic constraints
A velocity constraint is holonomic if it is equivalent to a constraint on positions, , which confines the robot to a surface in its configuration space (a train on a track is the classic example). A velocity constraint that cannot be written that way is nonholonomic.
Theorem— The rolling constraint is nonholonomic
The differential drive, subject to , can travel from any pose to any other pose on an unobstructed plane. Hence the constraint is not equivalent to any position constraint with non-constant.
Proof
Turn on the spot until the robot faces the point ; drive straight to it; turn on the spot to heading . Each step satisfies the constraint. If the constraint implied , then would be constant along every motion, so would take the same value at every pose, since every pose is reachable from every other. A constant constrains nothing.
∎
Cars cannot turn on the spot, but the same conclusion holds for them: they can reach every pose, just less directly. Parallel parking is the proof in everyday life. A few back-and-forth arcs, each obeying "no sideways motion", combine into a net sideways shift.
The constraint has consequences far beyond parking. A planner for a wheeled robot cannot simply draw a straight line to the goal with the right final heading; a controller cannot correct a sideways error directly, only by turning first. Both are why planners and trajectory trackers for wheeled robots carry the vehicle's model inside them.
Odometry from encoder ticks
An incremental encoder on each wheel produces a fixed number of ticks per revolution; counting them gives how far each wheel has turned. (Lumenary EE's sensors and data conversion explains how encoders and other sensors become numbers.) Every few milliseconds the odometry code reads the tick counts, converts them to the distances and that the wheels rolled, and updates the pose:
Using the heading halfway through the step makes each update nearly exact: on a circular arc the true displacement is a chord at exactly that angle, and the only error is that the chord is slightly shorter than the arc.
Odometry is only as good as the numbers it uses for and , and those are never exactly right. Tyres wear and compress under load; a wide tyre touches the floor over a patch, not at a point, so the effective track width is uncertain by millimetres. These are systematic errors: they push the estimate the same way every time. Borenstein and Feng's UMBmark test exposes them by driving a 4 m square clockwise and then anticlockwise and measuring where the robot really stops. The program simulates that test for a robot whose left tyre is 0.45% larger than the software believes and whose track is 1% wider. The motor controller drives each wheel by exactly the commanded number of ticks, so the odometry sees a perfect square while the real robot drives something else.
import numpy as np
TICKS_PER_REV = 4096 # encoder counts per wheel revolution (after the gearbox)
r_nom, b_nom = 0.033, 0.160 # what the robot's software believes
r_left, r_right, b_true = 0.03315, 0.033, 0.1616 # the real robot: worn tyre, track 1% wider
def odometry_step(pose, dticks_left, dticks_right, r=r_nom, b=b_nom):
"""Update (x, y, theta) from encoder tick increments, using the midpoint heading."""
x, y, th = pose
dL = 2 * np.pi * r * dticks_left / TICKS_PER_REV
dR = 2 * np.pi * r * dticks_right / TICKS_PER_REV
d, dth = (dR + dL) / 2, (dR - dL) / b
return (x + d * np.cos(th + dth / 2), y + d * np.sin(th + dth / 2), th + dth)
def square_commands(side, turn_sign):
"""Encoder tick targets for a square: straight, turn 90 degrees in place, four times."""
straight = round(side / (2 * np.pi * r_nom) * TICKS_PER_REV)
turn = round((b_nom / 2) * (np.pi / 2) / (2 * np.pi * r_nom) * TICKS_PER_REV)
return [(straight, straight), (-turn_sign * turn, turn_sign * turn)] * 4
def drive(commands, chunks=200):
"""The motor controller makes each wheel turn exactly the commanded ticks.
Odometry integrates those ticks; the true pose integrates what the wheels really did."""
odo = true = (0.0, 0.0, 0.0)
for tl, tr in commands:
for _ in range(chunks): # integrate each segment in small pieces
odo = odometry_step(odo, tl / chunks, tr / chunks)
true = odometry_step(true, tl / chunks * r_left / r_nom, tr / chunks * r_right / r_nom, b=b_true)
return odo, true
cmds = square_commands(4.0, +1)
print("first two commands (left ticks, right ticks):", cmds[:2])
print("one tick moves a wheel by", round(2 * np.pi * r_nom / TICKS_PER_REV * 1e6, 1), "micrometres")
for name, sign in [("anticlockwise", +1), ("clockwise", -1)]:
odo, true = drive(square_commands(4.0, sign))
print(f"{name:13}: odometry ends at ({odo[0]:+.3f}, {odo[1]:+.3f}) m;"
f" really at ({true[0]:+.3f}, {true[1]:+.3f}) m, heading {np.degrees(np.arctan2(np.sin(true[2]), np.cos(true[2]))):+.1f} deg")A 4 m side is 79,018 ticks, and a 90° turn on the spot is 2,482 ticks of each wheel in opposite directions. Odometry ends within 3 mm of the start, the error of rounding to whole ticks, and so believes that it has driven perfect squares. The real robot ends 1.5 m from the start after the anticlockwise square and 1.1 m after the clockwise one, about off in heading both times. The two directions disagree because the two error sources add in one direction and partly cancel in the other: the oversized left wheel makes every straight curve to the right, while the wider track makes every turn fall short. UMBmark uses exactly that asymmetry to estimate both errors separately and correct them.
How odometry error grows
Even a perfectly calibrated robot slips a little, at random: on a seam in the floor, a patch of dust, a slight bump. Model that as a small random error in each wheel's distance, independent from step to step, with a standard deviation that grows like the square root of the distance rolled. The program drives 500 simulated robots 40 m down a straight corridor with this noise (seeded, so it prints the same every time) and compares their true positions with what odometry believes.
import numpy as np
rng = np.random.default_rng(2026) # fixed seed: the same "random" runs every time
b = 0.160 # track width, m
step = 0.01 # each wheel's encoder says it moved 1 cm per step
sigma = 0.001 # slip noise: 1 mm per wheel after 1 m (grows like sqrt(distance))
runs, steps = 500, 4000 # 500 robots, each driving 40 m along a corridor
x = np.zeros(runs); y = np.zeros(runs); th = np.zeros(runs)
report = {500: None, 1000: None, 2000: None, 4000: None}
for k in range(1, steps + 1):
# What the wheels really did: the encoder reading plus a small random slip.
dL = step + rng.normal(0.0, sigma * np.sqrt(step), runs)
dR = step + rng.normal(0.0, sigma * np.sqrt(step), runs)
d, dth = (dL + dR) / 2, (dR - dL) / b
x += d * np.cos(th + dth / 2)
y += d * np.sin(th + dth / 2)
th += dth
if k in report: # odometry believes the robot is at (k * step, 0), heading 0
report[k] = (np.sqrt(np.mean((x - k * step) ** 2)), np.sqrt(np.mean(y ** 2)),
np.degrees(np.sqrt(np.mean(th ** 2))))
print("distance RMS along-track RMS cross-track RMS heading")
for k, (ex, ey, eth) in report.items():
print(f"{k * step:6.0f} m {ex * 1000:11.1f} mm {ey * 1000:12.1f} mm {eth:8.2f} deg")
slope = np.log(report[4000][1] / report[1000][1]) / np.log(4)
print(f"cross-track error grows like distance^{slope:.2f} between 10 m and 40 m")The heading error grows like the square root of the distance, as a random walk should: at 10 m and at 40 m, about double for four times the distance. The position error grows much faster. Along the corridor the errors stay at centimetres, but across the corridor they grow from 16 cm at 10 m to 1.25 m at 40 m, nearly eight times larger for four times the distance: the fitted exponent is . That is the signature of heading noise. The sideways error is the integral of the heading error over distance, and integrating something that grows like gives something that grows like . Systematic heading errors are worse still: a constant curvature error gives sideways error growing like .
The conclusion is the most important fact about odometry: its error is unbounded. It is excellent over short distances and useless on its own over long ones. Every serious mobile robot therefore corrects it with something that measures position against the world, such as a lidar matched to a map, cameras, GNSS outdoors, or beacons, through the estimators of Kalman filters, particle filters and SLAM. That is also the reason for the separate odom and map frames you met in the first lesson.
Car-like robots and Ackermann steering
A car steers its front wheels and drives without slipping only if all four wheels roll around the same ICR. The ICR must lie on the line of the rear axle (the rear wheels cannot steer), so the two front wheels must point at different angles: the inner wheel turns more sharply than the outer. This is Ackermann steering geometry, named after Rudolph Ackermann, a German-born publisher and inventor in London who patented it for carriages in 1818 on behalf of its inventor, the Munich carriage builder Georg Lankensperger. With wheelbase , track and turning radius measured to the middle of the rear axle,
For planning and control, a car is usually reduced to the bicycle model: merge each axle's two wheels into one wheel at the axle's middle, steered by a single angle . Measured at the rear axle,
It is the unicycle with one more restriction: , so the car cannot turn without moving and has a minimum turning radius . The program computes the steering angles for a car turning on a 6 m radius, and then parallel-parks it with two reversing arcs on full lock, the way a driver in Nairobi or Mumbai would park against a kerb on the left. It then lays out the kinematics of a mecanum platform, the subject of the next section.
import numpy as np
# --- A car: Ackermann steering and the bicycle model -----------------------------
L, w = 2.7, 1.6 # wheelbase and track of a mid-sized car, metres
R = 6.0 # desired turning radius, measured to the middle of the rear axle
inner = np.degrees(np.arctan(L / (R - w / 2)))
outer = np.degrees(np.arctan(L / (R + w / 2)))
bicycle = np.degrees(np.arctan(L / R))
print(f"turning radius {R} m: inner wheel {inner:.2f} deg, outer wheel {outer:.2f} deg, bicycle-model wheel {bicycle:.2f} deg")
print("Ackermann condition cot(outer) - cot(inner) = w / L:",
np.isclose(1 / np.tan(np.radians(outer)) - 1 / np.tan(np.radians(inner)), w / L))
delta_max = np.radians(35)
R_min = L / np.tan(delta_max)
print(f"with 35 degrees of steering lock the tightest turn has radius {R_min:.2f} m")
def bicycle_drive(pose, v, delta, T, dt=0.001):
"""Integrate x' = v cos(th), y' = v sin(th), th' = v tan(delta) / L."""
x, y, th = pose
for _ in range(round(T / dt)):
x, y, th = x + v * np.cos(th) * dt, y + v * np.sin(th) * dt, th + v * np.tan(delta) / L * dt
return x, y, th
# Parallel parking into a space on the left: reverse with the wheels on full left lock,
# then on full right lock, through the same arc angle each time.
phi = np.radians(25) # arc angle of each half of the manoeuvre
T = R_min * phi / 1.0 # time to cover that arc at 1 m/s
pose = bicycle_drive((0.0, 0.0, 0.0), -1.0, +delta_max, T)
pose = bicycle_drive(pose, -1.0, -delta_max, T)
print(f"after the manoeuvre: moved {pose[0]:+.3f} m along and {pose[1]:+.3f} m sideways, heading {round(np.degrees(pose[2]), 2) + 0.0:+.2f} deg")
print(f"circle geometry predicts {-2 * R_min * np.sin(phi):+.3f} m and {2 * R_min * (1 - np.cos(phi)):+.3f} m")
# --- A mecanum platform ---------------------------------------------------------------
r, lx, ly = 0.05, 0.20, 0.15 # wheel radius, half wheelbase, half track
J = np.array([[1, -1, -(lx + ly)], # front left wheel speed = J @ (vx, vy, omega) / r
[1, 1, (lx + ly)], # front right
[1, 1, -(lx + ly)], # rear left
[1, -1, (lx + ly)]]) / r # rear right
print("\nmotion (vx, vy, omega) wheel speeds FL, FR, RL, RR in rad/s")
for name, cmd in [("forward 0.5 m/s", (0.5, 0, 0)), ("left 0.5 m/s", (0, 0.5, 0)),
("spin 1 rad/s", (0, 0, 1.0)), ("diagonal", (0.5, 0.5, 0))]:
print(f"{name:26} {np.round(J @ np.array(cmd), 2) + 0.0}")
wheels = np.array([10.0, 12.0, 9.0, 11.0])
print("FL + FR - RL - RR must be 0 for wheels that agree; for", wheels, "it is", wheels @ [1, 1, -1, -1])
print("best-fit body motion (least squares):", np.round(np.linalg.lstsq(J, wheels, rcond=None)[0], 4))For a 6 m turn the inner wheel must steer and the outer , nearly six degrees apart; the bicycle model's single wheel sits between them at . With of lock the tightest turn has a 3.86 m radius. The parking manoeuvre, two reversing arcs of each, moves the car 0.72 m sideways at the cost of 3.26 m of travel along the street, and the simulation agrees with the circle geometry to a millimetre. To shift sideways by more, a driver needs more length, or more back-and-forth. The shortest such paths for a car that can reverse were worked out by Reeds and Shepp (1990), extending Dubins's 1957 result for a car that only goes forward; planners for autonomous vehicles still use them.
Omnidirectional and mecanum wheels
Some robots must move sideways: forklifts in narrow aisles, mobile manipulators lining up with a shelf, robots at the RoboCup competitions. Two wheel designs remove the rolling constraint.
An omni wheel carries small free rollers around its rim, their axles tangent to the rim, so the wheel drives in its own direction but slides freely along its axle. Three omni wheels at spacing (a "kiwi drive") give full planar motion. A mecanum wheel, invented by Bengt Ilon at the Swedish company Mecanum AB in the early 1970s, has rollers mounted at to its axle. Four of them on a rectangular chassis can produce any combination of forward, sideways and turning motion. In the arrangement used here, the rollers in contact with the floor under the front-left and rear-right wheels roll freely along the forward-left diagonal, and those under the other two along the forward-right diagonal. With half-wheelbase and half-track , each wheel's speed is
The last part of the previous program uses this matrix. All four wheels forward drives straight; front-left and rear-right backwards with the others forwards slides the platform sideways; driving only two diagonal wheels moves it diagonally. Four wheels for three degrees of freedom means the wheel speeds must satisfy one consistency condition, ; if they do not, the wheels fight each other and some rollers slip, and odometry must make a best (least-squares) guess.
Holonomic drives pay for their freedom. Rollers make the ride bumpy, need hard, flat, clean floors, and give less traction and efficiency than plain wheels; their odometry is noticeably worse because the rollers slip. Many industrial platforms that need sideways motion use swerve (independently steered) wheels instead, which keep a plain wheel's traction but need a steering motor per wheel. Tracked and skid-steer vehicles, at the other extreme, steer like a differential drive by deliberately dragging their tracks sideways; they climb well, and their odometry is poor.
Note
Trying it safely. A small differential-drive kit robot, battery-powered and slow (well under 1 m/s), is an excellent way to test odometry on a real floor: drive the UMBmark squares with tape marks on the floor and measure where it really stops. Test new code with the wheels lifted off the table first, keep a hand near the power switch, and keep fingers and hair away from wheels and gears. Larger mobile robots and anything carrying loads belong behind the safety measures of industrial practice; the lesson on embedded control and safety explains them.
The professional view
In ROS 2, wheel odometry is usually computed by diff_drive_controller (or a sibling for other drive types) from the ros2_control framework. It takes velocity commands in, sends wheel speed commands to the motor drivers, reads the encoders, integrates the pose with a midpoint or exact-arc update, and publishes a nav_msgs/Odometry message together with the odom → base_link transform. The message carries a covariance, an estimate of how uncertain the pose and velocity are, because the next stage needs it: a filter such as the robot_localization package fuses wheel odometry with an IMU's gyroscope (much better at heading than wheels), and the localisation stack then corrects the drift against a map. Calibrating and , by UMBmark-style tests or automatically from those corrections, is routine commissioning work.
When wheels cannot be trusted at all, robots measure motion another way. NASA's Mars Exploration Rovers, Spirit and Opportunity, could slip so much on sandy slopes that their wheel odometry badly overestimated how far they had gone; from 2004 they used visual odometry, tracking features between successive camera images, to measure their true motion, and later rovers rely on it routinely (see Maimone and colleagues in the references). Lidar odometry, which matches successive scans, and visual-inertial odometry, which fuses a camera with an IMU, are now standard on drones, phones and autonomous cars; the lessons on cameras and SLAM come back to them.
Common misconceptions
Misconception
"Nonholonomic means the robot cannot get there." It means the robot cannot get there directly. The theorem above shows that a differential drive, and with more manoeuvring a car, can reach every pose in the plane. The constraint shapes the path, not the set of destinations.
Misconception
"Random odometry errors average out." They accumulate. The random walk in heading grows like , and the position error it causes grows like , as the simulation measured. Only an external reference bounds it.
Misconception
"The track width is the distance between the wheels' centre lines, so I can measure it with a ruler." The effective track width is where the tyres actually grip, which depends on tyre shape, load and floor, and errors of a few millimetres in give errors of a few percent in every turn. Calibrate it by driving.
Misconception
"A mecanum robot is a differential drive that can also go sideways for free." Sideways motion with mecanum wheels relies on rollers slipping in a controlled way; it is slower, less efficient and less accurate than driving forwards, and it fails on soft or uneven ground.
Exercises
1. Wheeled robots and odometry
Warm-upHumanA differential-drive robot has wheels of circumference 200 mm, encoders giving 2000 ticks per wheel revolution, and a track width of 250 mm. During one update the left encoder counts 15,000 ticks and the right 16,000. How far, in millimetres, did the midpoint of the axle travel?
2. Wheeled robots and odometry
CoreHumanA differential-drive robot with track width m drives its left wheel at m/s and its right wheel at m/s (rim speeds). What is the radius, in millimetres, of the circle followed by the midpoint of its axle?
3. Wheeled robots and odometry
CoreHumanWhich statement about a differential-drive robot on an open, flat floor is correct?
4. Wheeled robots and odometry
Warm-upHumanWhich of these drive types can move sideways at any instant, without first turning? Select all that apply.
5. Wheeled robots and odometry
CoreHumanA robot's odometry has a constant heading error of (it believes it faces to the left of where it really faces) and it drives 10 m in what it believes is a straight line. Roughly how far sideways, in millimetres, is its true end point from where it believes it is? Round to the nearest millimetre.
6. Wheeled robots and odometry
CoreComputationalWrite odometry_update(pose, dticks_left, dticks_right, ticks_per_rev=4096, r=0.033, b=0.160), which returns the new pose (x, y, theta) of a differential-drive robot after its wheels turned by the given tick increments. Convert ticks to wheel distances, compute the distance and heading change , and update the position using the heading halfway through the step, . Tick increments may be negative, and need not be integers.
7. Wheeled robots and odometry
StretchComputationalThe lesson gave the mecanum inverse kinematics: wheel speeds from a desired body velocity . Write the forward kinematics mecanum_body_velocity(w_fl, w_fr, w_rl, w_rr, r=0.05, lx=0.20, ly=0.15), returning (vx, vy, omega) from the four wheel speeds. The starter gets right; find and the same way. Your function must exactly undo the lesson's matrix for any wheel speeds that come from it.
Further reading and resources
- Measurement and correction of systematic odometry errors in mobile robots · Johann Borenstein and Liqiang Feng · 1996The UMBmark test, driving squares clockwise and anticlockwise to separate wheel-size and track-width errors.
- Two years of visual odometry on the Mars Exploration Rovers · Mark Maimone, Yang Cheng and Larry Matthies · 2007Why Spirit and Opportunity could not trust their wheels on slopes, and what they used instead.
- ros2_control: diff_drive_controllerThe standard ROS 2 controller that turns velocity commands into wheel speeds and wheel encoders into odometry.
- robot_localizationAn open-source ROS package that fuses wheel odometry with IMUs, GNSS and other sensors in a Kalman filter.
- Modern Robotics: Mechanics, Planning, and Control · Kevin M. Lynch and Frank C. Park · 2017Chapter 13 covers wheeled mobile robots, nonholonomic constraints and controllability.