Odometry

intermediate95 min

Introduction to Odometry

Odometry estimates pose from wheel motion and heading. Each loop you read how far wheels turned and what the gyro reports, then integrate that into X, Y, and θ. Updates run at robot loop rate (about 20 ms) with no camera required.

Error stacks up: slip, wrong wheel diameter, or bad track width shows up as drift. Most competition stacks still lean on odometry and correct it with vision when tags are visible.

Differential and swerve are both covered below. Examples show the flow; your team template has the full hardware wiring.

WPILib: Odometry Documentation

Odometry Principles

Start from a known pose. Each timestep, add the small change implied by wheel distances and heading—that is dead reckoning.

Convert encoder rotations to meters with wheel radius and gear ratio. WPILib kinematics turn those distances into a field-frame delta.

Required Sensors

Wheel encoders on each driven wheel (or each swerve module drive). Calibrate diameter and counts per revolution.

Gyro for heading (Pigeon, NavX, ADXRS450, or integrated IMU). Turns especially need a stable heading source.

Differential Drive Odometry

Left and right encoder distances plus gyro heading feed DifferentialDriveOdometry. WPILib handles the kinematics.

Reading Encoder Positions

// Read encoder positions (how many rotations)
double leftRevolutions = m_leftEncoder.getPosition();
double rightRevolutions = m_rightEncoder.getPosition();

Converting Rotations to Distance

// Convert rotations to distance in meters
// Distance = rotations × circumference
// Circumference = 2π × radius
private static final double kWheelRadiusMeters = 0.05; // Your wheel radius

double leftDistance = leftRevolutions * 2.0 * Math.PI * kWheelRadiusMeters;
double rightDistance = rightRevolutions * 2.0 * Math.PI * kWheelRadiusMeters;

Getting Heading from Gyroscope

// Get current heading from gyro
Rotation2d heading = Rotation2d.fromDegrees(m_gyro.getAngle());

Updating Odometry

// Update odometry with new measurements
m_odometry.update(heading, leftDistance, rightDistance);

Initializing Differential Drive Odometry

public DifferentialDrivetrain() {
    // 1. Calibrate gyro (takes a few seconds)
    m_gyro.calibrate();
    
    // 2. Reset encoders to zero (establish starting point)
    m_leftEncoder.setPosition(0.0);
    m_rightEncoder.setPosition(0.0);
    
    // 3. Create odometry object with:
    //    - Current heading from gyro
    //    - Current distances (both 0 at start)
    //    - Starting pose (typically 0, 0, 0 degrees)
    m_odometry = new DifferentialDriveOdometry(
        Rotation2d.fromDegrees(m_gyro.getAngle()),
        0.0,  // Left distance
        0.0,  // Right distance
        new Pose2d()  // Starting pose (0, 0, 0 degrees)
    );
}

Retrieving and Resetting Pose

// GET POSE: Retrieve current robot position
public Pose2d getPose() {
    return m_odometry.getPoseMeters();
}

// RESET: Set odometry to a known pose (e.g., at start of autonomous)
public void resetOdometry(Pose2d pose) {
    // Get current encoder positions and heading
    double leftRevolutions = m_leftEncoder.getPosition();
    double rightRevolutions = m_rightEncoder.getPosition();
    double leftDistance = leftRevolutions * 2.0 * Math.PI * kWheelRadiusMeters;
    double rightDistance = rightRevolutions * 2.0 * Math.PI * kWheelRadiusMeters;
    Rotation2d heading = Rotation2d.fromDegrees(m_gyro.getAngle());
    
    // Reset odometry to the specified pose
    m_odometry.resetPosition(heading, leftDistance, rightDistance, pose);
}

Swerve Drive Odometry

Each module reports drive distance and steer angle. SwerveDriveOdometry fuses four modules and the gyro into one field pose.

WPILib: Swerve Drive Odometry

Getting Module Positions

// Get current position from each module
// Each module reports: (distance traveled, steering angle)
for (int i = 0; i < 4; i++) {
    m_modulePositions[i] = m_modules[i].getPosition();
}

Setting Up Kinematics

// Robot dimensions (meters) - measure your actual robot
private static final double kTrackWidth = 0.5;   // Left-right spacing
private static final double kWheelBase = 0.5;    // Front-rear spacing

// Define module positions relative to robot center
// These are the X, Y coordinates of each module
Translation2d frontLeft = new Translation2d(kWheelBase / 2, kTrackWidth / 2);
Translation2d frontRight = new Translation2d(kWheelBase / 2, -kTrackWidth / 2);
Translation2d rearLeft = new Translation2d(-kWheelBase / 2, kTrackWidth / 2);
Translation2d rearRight = new Translation2d(-kWheelBase / 2, -kTrackWidth / 2);

// Create kinematics object with module positions
m_kinematics = new SwerveDriveKinematics(
    frontLeft, frontRight, rearLeft, rearRight
);

Updating Swerve Odometry

// Get current heading from gyro
Rotation2d heading = Rotation2d.fromDegrees(m_gyro.getAngle());

// Update odometry with new measurements
m_odometry.update(heading, m_modulePositions);

Initializing Swerve Odometry

public SwerveDrivetrain() {
    // 1. Calibrate gyro (if needed for your gyro type)
    m_gyro.calibrate();
    
    // 2. Set up kinematics (module positions)
    // ... (see "Setting Up Kinematics" above)
    
    // 3. Get initial positions from all modules
    for (int i = 0; i < 4; i++) {
        m_modulePositions[i] = m_modules[i].getPosition();
    }
    
    // 4. Create odometry object with:
    //    - Kinematics (module layout)
    //    - Current heading from gyro
    //    - Current module positions
    //    - Starting pose (typically 0, 0, 0 degrees)
    m_odometry = new SwerveDriveOdometry(
        m_kinematics,
        Rotation2d.fromDegrees(m_gyro.getAngle()),
        m_modulePositions,
        new Pose2d()  // Starting pose
    );
}

Swerve Module Position

SwerveModulePosition holds drive distance (meters) and steer angle (Rotation2d). Your template’s SwerveModule class usually builds this from the drive encoder and absolute angle sensor.

Reading Drive Distance

// Read drive encoder to get distance traveled
// (Your drivetrain template handles conversion to meters)
double distanceMeters = m_driveMotor.getPosition();  // Already converted to meters

Reading Steering Angle

// Read angle encoder to get steering direction
// (Absolute encoder gives current angle, not relative)
Rotation2d angle = Rotation2d.fromRotations(m_angleEncoder.getPosition());

Creating SwerveModulePosition

// Return both as SwerveModulePosition
public SwerveModulePosition getPosition() {
    double distanceMeters = m_driveMotor.getPosition();
    Rotation2d angle = Rotation2d.fromRotations(m_angleEncoder.getPosition());
    
    return new SwerveModulePosition(distanceMeters, angle);
}

Odometry Limitations

Drift: Small constant errors become large over distance—often on the order of a few percent of travel if calibration is loose.

Slip: Acceleration, defense, and low-friction carpet make encoders lie until vision or a reset fixes pose.

Long runs: A long auto with only odometry can end far from truth; fuse vision or reset pose at known landmarks.

Mitigation: Calibrate wheel diameter and track width; fuse vision (fusion lesson); avoid unnecessary wheel spin.

Swerve-Specific Considerations

Measure module locations to the robot center in meters. Absolute steer encoders (CANcoder, etc.) matter—steer error becomes translation error. Four modules give more constraints than a tank drive, but all four must be calibrated.

Complete Swerve Odometry Flow

package frc.robot.subsystems;

import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.kinematics.SwerveDriveKinematics;
import edu.wpi.first.math.kinematics.SwerveDriveOdometry;
import edu.wpi.first.math.kinematics.SwerveModulePosition;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.SubsystemBase;

public class SwerveDrivetrain extends SubsystemBase {
    // Hardware
    private final Gyro m_gyro;
    private final SwerveModule m_frontLeft;
    private final SwerveModule m_frontRight;
    private final SwerveModule m_rearLeft;
    private final SwerveModule m_rearRight;
    
    // Odometry components
    private final SwerveDriveKinematics m_kinematics;
    private final SwerveDriveOdometry m_odometry;
    private final SwerveModulePosition[] m_modulePositions = new SwerveModulePosition[4];
    
    public SwerveDrivetrain() {
        // 1. Initialize hardware (your template handles this)
        // Initialize modules and gyro...
        
        // 2. Set up kinematics (module positions)
        // Create kinematics with module positions...
        
        // 3. Get initial module positions
        updateModulePositions();
        
        // 4. Initialize odometry
        m_odometry = new SwerveDriveOdometry(
            m_kinematics,
            Rotation2d.fromDegrees(m_gyro.getAngle()),
            m_modulePositions,
            new Pose2d()
        );
    }
    
    // PERIODIC: Called every robot loop (20ms)
    @Override
    public void periodic() {
        // 1. Get current positions from all modules
        updateModulePositions();
        
        // 2. Update odometry with new measurements
        m_odometry.update(
            Rotation2d.fromDegrees(m_gyro.getAngle()),
            m_modulePositions
        );
        
        // 3. (Optional) Display pose on SmartDashboard
        Pose2d pose = m_odometry.getPoseMeters();
        SmartDashboard.putNumber("Robot X", pose.getX());
        SmartDashboard.putNumber("Robot Y", pose.getY());
        SmartDashboard.putNumber("Robot Heading", pose.getRotation().getDegrees());
    }
    
    // HELPER: Update module positions array
    private void updateModulePositions() {
        m_modulePositions[0] = m_frontLeft.getPosition();
        m_modulePositions[1] = m_frontRight.getPosition();
        m_modulePositions[2] = m_rearLeft.getPosition();
        m_modulePositions[3] = m_rearRight.getPosition();
    }
    
    // GET POSE: Called by autonomous/teleop code
    public Pose2d getPose() {
        return m_odometry.getPoseMeters();
    }
    
    // RESET: Called at start of autonomous or after vision correction
    public void resetOdometry(Pose2d pose) {
        updateModulePositions();
        m_odometry.resetPosition(
            Rotation2d.fromDegrees(m_gyro.getAngle()),
            m_modulePositions,
            pose
        );
    }
}

// KEY CONCEPTS:
// 1. Constructor: Initialize once at startup
// 2. Periodic: Update every loop (20ms) - this is critical!
// 3. getPose: Use this to get current position
// 4. resetOdometry: Use this to set a known position

Best Practices for Accurate Odometry

  • Measure wheel diameter, track width, and wheelbase; set gyro and module offsets in code to match.
  • Call odometry update every periodic()—skipped loops mean wrong pose.
  • Reset pose at auto start and when vision gives a trusted fix.
  • Reduce slip with reasonable accel limits and solid encoder mounting.

Resources