# Differential-drive odometry with wheel encoders on Arduino: design worksheet and code

> A ₹1,540 design worksheet for tracking a two-wheel robot’s position and heading from wheel encoders, with the odometry equations, a calibration method that fixes wheel size and track width, and a sketch.

Canonical: https://roboticsengineering.in/projects/differential-drive-odometry-arduino/ | Published: 2026-11-04 | Updated: 2026-11-04

**A ₹1,540 robot that knows roughly where it is. Slotted sensors count wheel slots, and the sketch turns the counts into a position (x, y) and a heading. The page gives the equations, a worked number set, a calibration method, and an honest account of how fast the error grows, because dead reckoning always drifts.**

**Scope:** intermediate. This is a design worksheet with illustrative costs. It has not been bench-tested by this site. The numbers below were computed and the update equations were run on a simulated drive to confirm they close a circle and give the expected straight-line distance. Real wheels slip and real discs are not perfect, so your own calibration figures will differ. This builds on the [straight-line encoder robot](https://roboticsengineering.in/projects/straight-line-encoder-robot-arduino/); read that page first if the encoder wiring is new to you.

## How it works

Each wheel carries a disc with slots. A sensor counts each slot that passes, so one count is a fixed distance of wheel travel. With a 65 mm wheel and a 20-slot disc, one count is π × 65 / 20 = 10.21 mm. The sketch reads the left and right counts every 50 ms and turns the change in each into a distance, dL and dR.

The robot’s travel is the average of the two, dC = (dL + dR) / 2. Its change of heading is the difference divided by the track width B, the distance between the wheel contact points: dθ = (dR − dL) / B. The position is then advanced along the middle of the small turn: x += dC × cos(θ + dθ/2) and y += dC × sin(θ + dθ/2), and θ += dθ. Using the middle heading is a cheap way to follow a curve more closely than using the heading at the start of the step.

## Bill of materials

| Part | Qty | Unit | Total |
| --- | --- | --- | --- |
| Arduino Uno clone | 1 | ₹550 | ₹550 |
| L298N motor driver | 1 | ₹180 | ₹180 |
| TT gear motor pair with wheels | 1 | ₹260 | ₹260 |
| 2WD chassis | 1 | ₹150 | ₹150 |
| Slotted speed sensor (LM393) | 2 | ₹60 | ₹120 |
| 2×18650 holder with cells | 1 | ₹200 | ₹200 |
| Switch | 1 | ₹30 | ₹30 |
| Jumper wire set | 1 | ₹50 | ₹50 |
| Parts total | ₹1,540 |  |  |

Scroll the table sideways to see every column.

Prices checked Nov 2026. Shipping and tools are not included.

Prices are illustrative figures for Indian sellers in November 2026, before shipping, and have not been checked against current listings. Many TT motor kits include the slotted discs; check yours before buying sensors.

## Numbers worth knowing

| Quantity | Value | How it comes out |
| --- | --- | --- |
| Distance per count | 10.21 mm | π × 65 mm / 20 slots |
| Heading change per count of difference | 4.5° | 10.21 mm / 130 mm track, in degrees |
| Counts per wheel for a 90° spin in place | 10 | Wheels turn opposite ways; arc = π × 130 / 4 |
| Counts per wheel for a full spin | 40 | Four times the 90° figure |
| Straight run of 100 counts each | 1,021 mm | 100 × 10.21 mm, heading unchanged |

*Wheel 65 mm, 20 slots, track 130 mm. Replace with your measured values. A 65 mm wheel is common on TT kits; the track depends on your chassis.*

The second row is the limit of the whole method. One count of difference between the wheels turns the robot by about 4.5 degrees in this layout, so the heading is only known to within a few degrees from a single wheel pulse. Finer discs help; so does adding a gyro, as in the [gyro turn project](https://roboticsengineering.in/projects/gyro-90-degree-turn-robot-arduino/).

## Why it drifts

A circle test in the simulation, with exact counts for a 300 mm radius turn, returns to the start within a tiny fraction of a millimetre, so the equations are fine. The drift comes from the hardware, and the arithmetic below shows how little it takes. If the right wheel is just 1 percent larger than the left and the robot drives about 5 m, the right wheel travels 50 mm further. Over a 130 mm track that is a heading error of about 22 degrees, which by the end of the run puts the robot roughly a metre to one side of where the odometry says. Slip on a smooth floor adds to this and cannot be seen by the encoders at all.

## Power and wiring

| Part | Arduino Uno | Note |
| --- | --- | --- |
| Left sensor output | D2 (INT0) | Interrupt-capable pin |
| Right sensor output | D3 (INT1) | Interrupt-capable pin |
| L298N ENA / IN1 / IN2 | D5 / D7 / D8 | Left motor, ENA is PWM |
| L298N ENB / IN3 / IN4 | D6 / D9 / D4 | Right motor, ENB is PWM |
| Sensor VCC and GND | 5V and GND | Most modules accept 3.3–5 V; check yours |
| Battery | L298N 12V input and Uno VIN | Check your pack voltage against the board’s limits |

*Pin numbers are one working layout, not the only one. Keep the two sensors on the two interrupt pins.*

A single-channel sensor counts slots but cannot tell which way the wheel turns. The sketch therefore assumes each wheel turns the way it was last commanded. That is fine for the test below and wrong whenever a wheel is pushed backwards by hand or slides, which is a limit of the hardware, not the code. Quadrature encoders, with two channels, remove it.

## The sketch

```
// Differential-drive odometry: Uno + L298N + 2 slotted sensors
// Counts slots on D2/D3, updates x, y, heading, prints over Serial.
// Design worksheet: replace the three constants with your measurements.

const float WHEEL_D = 65.0;      // wheel diameter, mm
const float SLOTS = 20.0;        // slots per wheel revolution
const float TRACK = 130.0;       // distance between wheel contact points, mm
const float MM_PER_COUNT = PI * WHEEL_D / SLOTS;

const int L_EN = 5, L_IN1 = 7, L_IN2 = 8;
const int R_EN = 6, R_IN3 = 9, R_IN4 = 4;

volatile long cntL = 0, cntR = 0;
volatile signed char dirL = 1, dirR = 1;   // set by the motor commands

float x = 0, y = 0, th = 0;                // mm, mm, radians
long lastL = 0, lastR = 0;
unsigned long lastUpdate = 0;

void isrL() { cntL += dirL; }
void isrR() { cntR += dirR; }

void setMotors(int left, int right) {      // -255..255 each
  dirL = left >= 0 ? 1 : -1;
  dirR = right >= 0 ? 1 : -1;
  digitalWrite(L_IN1, left >= 0); digitalWrite(L_IN2, left < 0);
  digitalWrite(R_IN3, right >= 0); digitalWrite(R_IN4, right < 0);
  analogWrite(L_EN, abs(left));
  analogWrite(R_EN, abs(right));
}

void updatePose() {
  long l, r;
  noInterrupts(); l = cntL; r = cntR; interrupts();
  float dL = (l - lastL) * MM_PER_COUNT;
  float dR = (r - lastR) * MM_PER_COUNT;
  lastL = l; lastR = r;
  float dC = (dL + dR) / 2.0;
  float dth = (dR - dL) / TRACK;
  x += dC * cos(th + dth / 2.0);
  y += dC * sin(th + dth / 2.0);
  th += dth;
}

void printPose() {
  Serial.print("x="); Serial.print(x, 1);
  Serial.print(" y="); Serial.print(y, 1);
  Serial.print(" heading="); Serial.println(th * RAD_TO_DEG, 1);
}

void setup() {
  Serial.begin(115200);
  pinMode(L_EN, OUTPUT); pinMode(L_IN1, OUTPUT); pinMode(L_IN2, OUTPUT);
  pinMode(R_EN, OUTPUT); pinMode(R_IN3, OUTPUT); pinMode(R_IN4, OUTPUT);
  pinMode(2, INPUT); pinMode(3, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), isrL, RISING);
  attachInterrupt(digitalPinToInterrupt(3), isrR, RISING);
  delay(2000);                              // set the robot down first
  setMotors(150, 150);                      // drive forward, open loop
}

void loop() {
  if (millis() - lastUpdate >= 50) {
    lastUpdate = millis();
    updatePose();
    printPose();
    if (x >= 1000.0) setMotors(0, 0);       // stop after about 1 m
  }
}
```

The motors run open loop at a fixed PWM, so the two wheels will not match and the robot will curve; that is exactly what the odometry should show. A real application would add a speed correction, as in the straight-line encoder project, and a way to turn through a set angle.

## Calibration

Two numbers need your own measurement. First, wheel diameter: mark a start line, drive a long straight run, measure the true distance with a tape, and scale the diameter by true distance divided by reported distance. Second, track width: spin the robot in place, count the real turns, and scale the track by reported angle divided by true angle. If the odometry says 360 degrees and the robot turned only 340 degrees, the track is too small, so multiply it by 360/340. Repeat each test several times and use the average, since slip varies from run to run.

## Test plan

1. **Counts:** turn each wheel by hand through one revolution and confirm the count matches the number of slots. Fix a loose disc or a noisy sensor first.
2. **Straight line:** drive 1 m, measure it with a tape, and compare it with the reported x. Adjust the wheel diameter and repeat.
3. **Spin:** command opposite wheel speeds for ten full turns, compare the reported heading with the real one, and adjust the track width.
4. **Square:** drive a square of about 500 mm per side, using open-loop timing, and note where the robot finishes against where the odometry says it does.
5. **Surface:** repeat the straight test on a smooth floor and a rougher mat. Slip changes the answer.
6. **Battery:** repeat with a fresh and a tired pack. Speed changes, and wheel slip with it.

## What other builders report

This section summarises public material in our own words. None of it is our measurement.

- MathWorks’ documentation on wheel-encoder error sources says that giving the two wheels different radii makes the odometry estimate drift along the whole path, that an overestimated track width exaggerates turning so the drift builds up at turns, and that slip makes the estimate longer than the distance actually covered ([MathWorks](https://www.mathworks.com/help/nav/ug/wheel-encoder-error-sources.html)). Those are modelled errors in a simulation, not hobby measurements.
- The robotics literature describes a standard calibration called UMBmark: drive a square clockwise and counter-clockwise and use where the robot ends up to correct the systematic errors. We could not open the paper we found to confirm details, so use the calibration steps on this page as a starting point.
- We did not find Arduino-specific experience reports with measured track widths or slip on particular floors, so record your own numbers.

What this means for the build: calibrate with a repeatable test, repeat it in both directions, and expect the numbers to change with the floor and the battery.

## What usually goes wrong

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| Counts too high | Sensor noise or a reflective edge | Shield the sensor, add a small capacitor, raise the threshold |
| Counts missed at speed | Slots too fine for the interrupt rate | Use a coarser disc or slow the wheel |
| Heading wanders when going straight | Wheels differ in size or speed | Calibrate each wheel separately |
| Position looks fine, robot is elsewhere | Wheel slip | Slow acceleration, better floor, add a gyro |
| Position jumps backwards | Direction flag wrong after a push | Quadrature encoders, or avoid pushing the robot |
| Reboot at start-up | Motor surge on a weak supply | Soft-start the PWM, check the battery |

## Upgrades

- **Gyro heading:** take heading from an MPU6050 and distance from the wheels, which removes most of the heading drift.
- **Quadrature encoders:** two channels per wheel give direction and four times the resolution.
- **Go to a point:** steer toward a target (x, y) using the pose as feedback.
- **Log and plot:** save the serial output and plot the path to see the drift.

## Cost and parts notes

The ₹1,540 total is an illustration and does not include shipping. Check that the slotted discs fit your wheel shaft before ordering. Use the [cost calculator](https://roboticsengineering.in/robotics-project-cost-calculator/) to compare sellers.

## Common questions

**What is odometry?**

It is estimating where a robot is by adding up its own motion, here from wheel counts. It needs no outside reference, which is why it drifts.

**How accurate will it be?**

Over a few metres on a smooth floor expect errors of centimetres to tens of centimetres, mainly from heading. Calibration helps; a gyro helps more.

**Why not use GPS?**

GPS does not work well indoors and is not precise enough for a small robot at this scale.

**Do I need quadrature encoders?**

Not to start. A single-channel sensor works if the robot only drives the way it was commanded. Add a second channel when you need direction.

Last reviewed: November 2026. This is a design worksheet with illustrative costs. It has not been bench-tested by this site; library names, pins and limits must be checked against your board and the current library versions, and measurements from your build are welcome.
