Swerve Odometry Lesson

Swerve Odometry: Knowing Where You Are

While a swerve drive's movement is impressive, its real power comes from odometry—the use of sensor data to estimate the robot's precise position and heading on the field. It's how the robot knows where it is at all times.

The Core Concept: Dead Reckoning

The heart of odometry is a process called dead reckoning. By continuously tracking its direction and speed over time, the robot can estimate its current position relative to where it started. Our swerve drive uses three critical sensors for this.

The Sensors for Odometry

  • Steering Encoders: Measure the exact angle of each wheel.
  • Drive Encoders: Measure how far each wheel has traveled.
  • A Gyroscope: Measures the robot's overall heading (rotation).

Every 20 milliseconds, our code takes a snapshot from these sensors to calculate a new estimated position.

The `Pose2d` Object: The Robot's Address

In WPILib, a robot's complete position and orientation on the field are represented by a `Pose2d` object. This object is the "address" of our robot, and a successful swerve drive program spends most of its time keeping this object as accurate as possible.

What's in a `Pose2d`?

A `Pose2d` is a container for three key pieces of information:
  1. An X coordinate for the robot's position along the field's length.
  2. A Y coordinate for the robot's position along the field's width.
  3. A Rotation for the robot's current heading (angle).

WPILib's `SwerveDriveOdometry` Class

We don't have to write the complex odometry math from scratch. WPILib provides a class, `SwerveDriveOdometry`, that does all the heavy lifting for us. Our job as programmers is to properly feed this class the sensor data it needs to do its job. It takes data from our swerve modules and gyroscope, and in return, it calculates and stores a continuously updated `Pose2d` for the robot.

Test Your Knowledge

Question: What three pieces of information are stored in a WPILib `Pose2d` object?