Mounting and Kinematics Context: Where the Encoder Sits Matters
Encoders measure rotation, but what that rotation means depends on where you mount them in the drivetrain. Before decoding any ticks, define the kinematic chain from the encoder shaft to the robot motion variable you care about (joint angle, wheel angle, or base displacement).
Common mounting locations
- Motor shaft (before gearbox): high speed, high tick rate; requires gear ratio to map to output.
- Gearbox output / joint shaft: directly measures joint/wheel rotation; lower speed; less sensitive to gearbox backlash in the measurement itself.
- Wheel hub: best for wheel odometry (measures wheel rotation directly), but still vulnerable to wheel slip relative to ground.
Gear ratio mapping
Let the encoder be on the motor shaft and the gearbox ratio be G (motor turns per output turn). Then:
theta_out = theta_motor / Gomega_out = omega_motor / G
Be explicit about whether G is defined as motor/output or output/motor and keep it consistent in code and documentation.
From wheel rotation to robot motion (differential drive)
For wheel radius R, left/right wheel angles theta_L, theta_R, and track width B (distance between wheel contact centers):
- Wheel arc lengths:
s_L = R * theta_L,s_R = R * theta_R - Forward increment:
ds = (s_R + s_L)/2 - Heading increment:
dpsi = (s_R - s_L)/B
These formulas make it clear why calibrating R and B is critical for odometry reliability.
- Listen to the audio with the screen off.
- Earn a certificate upon completion.
- Over 5000 courses for you to explore!
Download the app
Incremental vs Absolute Encoders
Incremental encoders
An incremental encoder outputs pulses as it rotates. You count pulses (ticks) to infer relative motion from a starting reference. Key properties:
- Relative position: position is known only up to the initial zeroing procedure.
- High speed capability: often excellent for fast motors.
- Power cycle behavior: position is lost unless you store it and can guarantee no motion while unpowered, or you re-home.
Absolute encoders
An absolute encoder outputs a unique code for each angle (single-turn) and sometimes also counts turns (multi-turn). Key properties:
- True angle after power-up: no homing needed for position within its range.
- Interface: often digital serial (SPI, BiSS, SSI) or fieldbus; update rate and latency matter for control.
- Failure modes: can include communication errors; requires robust time-stamping and error checking.
Trade-off summary
| Aspect | Incremental | Absolute |
|---|---|---|
| Power-up position | Unknown until homed | Known immediately (within range) |
| Speed / count rate | Very high possible | Limited by interface/update rate |
| Wiring | Often A/B (+Z) lines | Often clock/data or bus |
| Typical use | Motor commutation, wheel odometry, relative joints | Robot joints needing absolute angle, safety-critical homing avoidance |
Quadrature Decoding: Direction and Higher Effective Resolution
Most incremental encoders provide two channels, A and B, phase-shifted by 90 electrical degrees (quadrature). The phase relationship indicates direction.
Direction determination
At each transition, read both A and B. The valid state sequence for one direction is:
00 -> 01 -> 11 -> 10 -> 00 (forward)The reverse direction traverses the sequence in the opposite order. If you observe an invalid jump (e.g., 00 -> 11), it suggests missed counts or noise.
X1, X2, X4 decoding
- X1: count one edge per A cycle (lowest resolution, most robust).
- X2: count both rising and falling edges of A.
- X4: count all edges of A and B (highest resolution, highest sensitivity to edge integrity and timing).
When someone says an encoder is “N CPR”, confirm whether that CPR is specified per channel cycle (often “lines”) or already assumes X4 decoding. Always convert to a single internal definition such as ticks_per_rev.
Counts-Per-Revolution (CPR) and Tick-to-Angle Conversion
Define ticks per revolution
Let:
CPR_lines= encoder cycles per revolution per channel (often called “lines”)k= decoding multiplier (1, 2, or 4)ticks_per_rev = CPR_lines * k
Example: a 1024-line quadrature encoder with X4 decoding gives ticks_per_rev = 1024 * 4 = 4096.
Compute angle from ticks
Maintain a signed tick count n (increment/decrement based on direction). Then:
- Angle in radians:
theta = 2*pi * n / ticks_per_rev - Angle in degrees:
theta_deg = 360 * n / ticks_per_rev
If the encoder is on the motor shaft with gear ratio G (motor/output), then output angle is:
theta_out = (2*pi * n / ticks_per_rev) / G
Step-by-step: implement position tracking
- Step 1: Choose decoding mode (X1/X2/X4) and compute
ticks_per_rev. - Step 2: Use an interrupt or hardware timer/counter to update a signed integer
non each valid edge transition. - Step 3: Convert
ntothetausing the formulas above. - Step 4: Apply gear ratio mapping if the encoder is not on the measured joint/wheel.
- Step 5: For wheel odometry, compute
s = R * thetaand then base increments using the differential-drive relations.
Velocity Estimation from Ticks
Velocity estimation is where many odometry reliability issues appear. Two common approaches are (1) differentiate position over a fixed time window and (2) measure time between pulses (period measurement). Each has different noise and latency characteristics.
Method A: differentiate position over a fixed sample period
Sample the tick count at times t_k with fixed period dt. Let n_k be ticks at sample k. Then:
- Tick rate:
dn = n_k - n_{k-1} - Angular velocity:
omega = (2*pi / ticks_per_rev) * (dn / dt)
Pros: simple; works well at medium/high speeds. Cons: at low speed, dn is often 0 or 1, producing quantized velocity estimates.
Practical refinement: compute velocity over a longer window N samples to reduce quantization:
omega = (2*pi / ticks_per_rev) * (n_k - n_{k-N}) / (N*dt)
Method B: time-between-pulses (period) measurement
Measure the elapsed time Delta t between successive tick edges (or between every M ticks). If one tick corresponds to Delta theta = 2*pi / ticks_per_rev, then:
omega = Delta theta / Delta t
Pros: excellent low-speed resolution. Cons: at high speed, Delta t becomes very small and sensitive to time-stamp jitter and interrupt latency; also produces irregular update timing.
Practical refinement: average over M ticks:
omega = (M * 2*pi / ticks_per_rev) / Delta t_M
Choosing between methods
- Use differentiation when speeds are high enough that
dnper sample is comfortably above 1–2 ticks. - Use time-between-pulses when operating near zero speed or when you need smooth low-speed control.
- Hybrid approach: switch methods based on speed (or based on observed
dnandDelta t) to avoid each method’s weak regime.
Error Sources and How They Show Up in Odometry
Quantization
Ticks are discrete. The smallest measurable angle step is:
Delta theta = 2*pi / ticks_per_rev
For a wheel, the smallest arc-length step is Delta s = R * Delta theta. Quantization causes:
- Stair-step position updates.
- Velocity noise at low speed (especially with fixed-period differentiation).
Missed counts
Missed edges occur when the counting hardware/software cannot keep up or when signals are corrupted. Symptoms include:
- Underestimated distance (systematically or sporadically).
- Invalid quadrature transitions (state jumps).
Mitigations: hardware quadrature decoder peripherals, DMA/timer capture, ensure interrupt budget, and validate transitions in software if needed.
Electrical noise and signal integrity
Noise can create false edges or corrupt A/B phase. Common causes: long unshielded cables, poor grounding, motor EMI, and weak pull-ups. Mitigations:
- Differential signaling (e.g., RS-422 line drivers) for long runs.
- Shielded twisted pairs, proper grounding strategy.
- Schmitt-trigger inputs, digital filtering, and careful debounce (without removing real edges at high speed).
Backlash (gears, couplers)
Backlash introduces a dead zone between motor rotation and output rotation. If the encoder is on the motor shaft, the encoder may report motion that does not immediately translate to wheel/joint motion during direction reversals. Symptoms:
- Oscillations or lag in control near zero crossings.
- Odometry errors during frequent direction changes.
Mitigations: mount encoder closer to the output, model backlash, or avoid relying on motor-shaft encoders for precise low-speed output motion.
Wheel slip
Encoders measure wheel rotation, not ground truth displacement. Slip causes odometry to overestimate motion (wheel spins) or misestimate heading (one wheel slips more). Symptoms:
- Straight-line drift on low-friction surfaces.
- Large errors during acceleration, braking, or turning on smooth floors.
Mitigations: limit acceleration, use traction-aware wheels, fuse with other sensors (e.g., IMU), and detect slip via inconsistency checks (e.g., commanded vs measured dynamics).
Eccentricity and runout
If the encoder disk or wheel is not perfectly centered, the effective radius varies with angle. This can create periodic velocity ripple and distance bias. Symptoms:
- Velocity oscillation at a frequency tied to rotation rate.
- Repeatable periodic error in odometry.
Mitigations: mechanical alignment, better bearings, hub-centric mounting, and calibration/compensation if the pattern is stable.
Time-stamp jitter and latency
Velocity from differentiation depends on accurate dt; velocity from period measurement depends on accurate Delta t. Jitter sources include OS scheduling, interrupt latency, and non-monotonic time bases. Symptoms:
- Noisy velocity estimates even with clean encoder signals.
- Bias at high speed if time-stamps are systematically delayed.
Mitigations: use hardware timers for capture, time-stamp in ISR close to the edge event, prefer monotonic clocks, and keep the measurement pipeline deterministic.
Calibration Practices for Reliable Odometry
Effective wheel radius calibration
The nominal wheel radius rarely matches the effective rolling radius under load. Calibrate R_eff by driving a known distance on the target surface.
Step-by-step procedure:
- Step 1: Mark a start line and measure a straight distance
D(e.g., 5–20 m to reduce relative error). - Step 2: Drive straight at moderate speed to reduce slip; record total wheel angle change (or total ticks) for both wheels.
- Step 3: Compute average wheel rotation:
theta_avg = (theta_R + theta_L)/2. - Step 4: Estimate
R_eff = D / theta_avg. - Step 5: Repeat multiple runs and average; check for dependence on payload and tire pressure.
Track width (wheelbase) calibration
Track width B strongly affects heading. Calibrate by commanding a turn-in-place and measuring the actual yaw change.
Step-by-step procedure:
- Step 1: Command a turn-in-place with equal and opposite wheel motions; record
theta_Landtheta_R. - Step 2: Measure actual yaw change
Delta psi_meas(e.g., using a protractor setup, motion capture, or a well-calibrated yaw reference). - Step 3: Compute wheel arc difference:
Delta s = R_eff * (theta_R - theta_L). - Step 4: Estimate
B_eff = Delta s / Delta psi_meas. - Step 5: Repeat in both directions to detect asymmetries.
Gear ratio verification
Catalog gear ratios can differ from effective ratios due to additional stages, belt reductions, or assembly changes. Verify G empirically.
- Rotate the output shaft by a known angle (e.g., one full turn) and record motor encoder ticks.
- Compute
G = theta_motor / theta_out. - Check for consistency across multiple turns; inconsistency can indicate slip in belts/couplers.
Validation Tests: Detecting Bias and Drift Early
Straight-line drift test
Purpose: detect left/right scale mismatch (wheel radius mismatch, unequal gains, systematic slip).
- Drive forward a long straight path with constant command.
- Measure lateral deviation and final heading error.
- If the robot consistently veers, compare left/right tick-to-distance scaling and check mechanical differences (tire wear, inflation, alignment).
Turn-in-place bias test
Purpose: detect track width error, asymmetric friction, or backlash effects.
- Command several full rotations in place (both CW and CCW).
- Compare expected yaw from encoder odometry to measured yaw.
- Look for direction-dependent error (often backlash or asymmetric slip).
High-speed count integrity test
Purpose: ensure no missed counts at maximum speed.
- Run the drivetrain at maximum expected speed.
- Monitor for invalid quadrature transitions and compare measured speed against an independent reference (e.g., tachometer or motor controller estimate).
- If errors appear only at high speed, reduce decoding multiplier, improve signal conditioning, or move counting to hardware peripherals.
Selection Criteria for Encoders in Robot Motion
Resolution needs (position and odometry)
Start from the smallest motion you need to resolve.
- Wheel distance per tick:
Delta s = 2*pi*R / ticks_per_rev - Joint angle per tick (with gearbox):
Delta theta_out = 2*pi / (ticks_per_rev * G)
Choose ticks_per_rev so that Delta s or Delta theta_out is comfortably smaller than your control/estimation tolerance, keeping in mind that higher resolution increases count rate and sensitivity to noise.
Maximum speed and count rate
Ensure the system can count edges at peak speed without loss. If the maximum shaft speed is f_rev revolutions per second, then the tick rate is:
f_ticks = f_rev * ticks_per_rev
For quadrature X4, edge rate can be effectively four times the line frequency. Verify:
- Encoder output frequency limits.
- Input capture/counter maximum frequency.
- CPU interrupt budget if decoding in software.
Environmental robustness
- Dust/oil: sealed magnetic encoders often tolerate contamination better than optical disks.
- Vibration/shock: prefer robust bearings and secure mounting; avoid flexible couplers that introduce torsional windup unless necessary.
- EMI: differential outputs and proper cabling become important near motors and high-current switching.
Absolute vs incremental trade-offs in practice
- Choose absolute when you need known joint position immediately at power-up (e.g., arms that must avoid collisions without homing) or when homing is impractical.
- Choose incremental when you need very high speed feedback, simple interfaces, or cost-effective wheel odometry—provided you can manage homing and count integrity.
- For safety and reliability, consider redundancy: an absolute joint encoder for position plus incremental motor encoder for commutation/velocity, each validated against the other.