Wheel encoders
What you’ll learn
- How optical and magnetic encoders count rotation
- How to turn counts into distance and speed
- Why interrupts are needed, and what quadrature means
Counting turns
An encoder produces pulses as a wheel or motor shaft turns.
- Optical: a slotted disc spins between an IR LED and a sensor; each slot makes a pulse. Common in kits with 20 slots.
- Magnetic (Hall effect): a magnet on the motor shaft passes Hall sensors. Common on gear motors, often with hundreds of counts per wheel turn because they sit before the gearbox.
Counts to distance
distance = (counts ÷ counts per revolution) × wheel circumference
With a 20-slot disc and 65 mm wheels (204 mm circumference), each count is about 10 mm.
Interrupts
Pulses can arrive faster than loop() checks the pin, so encoders use interrupts: the Arduino pauses and runs a tiny function the instant the pin changes. On an UNO, pins 2 and 3 support attachInterrupt().
Quadrature
A single channel counts but can’t tell direction. Quadrature encoders have two channels (A and B) a quarter-step apart; which one changes first tells you the direction.
Why robots need them
- Drive an exact distance
- Turn an exact angle
- Drive straight: if the left wheel counts faster, slow it down
Example: counting with an interrupt
volatile long count = 0; // volatile: changed inside an interrupt
void onPulse() { count++; }
void setup() { pinMode(2, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(2), onPulse, RISING); Serial.begin(9600);}
void loop() { noInterrupts(); long c = count; // copy safely interrupts(); Serial.print("Distance (mm): "); Serial.println(c * 204.0 / 20.0); delay(200);}Example: driving straight
long diff = leftCount - rightCount;int leftSpeed = 150 - diff * 2; // left ahead? slow itint rightSpeed = 150 + diff * 2;This is a simple proportional correction, the “P” in PID.
How far?Easy
A 20-slot encoder counts 150 pulses on a 65 mm wheel. How far did the robot go? 150 ÷ 20 = 7.5 turns × 204 mm ≈ 1,530 mm ≈ 1.5 m.
How fast?Medium
The same encoder counts 40 pulses in 0.5 s. What’s the speed in m/s? 40 ÷ 20 = 2 turns × 0.204 m = 0.408 m in 0.5 s, so 0.82 m/s.
Turn 90°Hard
The wheels are 13 cm apart. When spinning on the spot, how far does each wheel travel for a 90° turn, and how many counts is that? Each wheel moves along a circle whose diameter is the distance between the wheels. Circle circumference = π × 130 ≈ 408 mm; a quarter is 102 mm. 102 ÷ 10.2 mm per count ≈ 10 counts per wheel.
Quick check
Finished this lesson?