A robot cannot navigate autonomously using wheel odometry alone; wheel slip and defense will cause estimated position to drift meters off target. Conversely, using vision alone is too sluggish and noisy for high-speed closed-loop driving.
The solution is an Extended Kalman Filter (EKF). WPILib’s SwerveDrivePoseEstimator fuses high-frequency wheel odometry (250 Hz) with latency-compensated optical vision measurements (20 to 50 Hz).
1. Complementary Strengths
Section titled “1. Complementary Strengths”| Sensor | Update Rate | Latency | Short-Term Accuracy | Long-Term Accuracy |
|---|---|---|---|---|
| Wheel Odometry + Pigeon 2.0 | 250 Hz (CAN FD) | < 4 ms | Sub-millimeter, smooth | Drifts over time |
| AprilTag Camera (Limelight) | 20-50 Hz | 20-40 ms | Noisy at distance | Zero cumulative drift |
The Kalman filter uses wheel odometry to track instantaneous movement smoothly between camera frames, and uses AprilTags to correct drift without causing sudden jumps.
2. Ingesting Vision Updates in Java
Section titled “2. Ingesting Vision Updates in Java”Below is the production vision fusion loop implemented in your swerve subsystem:
package frc.robot.subsystems;
import edu.wpi.first.math.VecBuilder;import edu.wpi.first.math.estimator.SwerveDrivePoseEstimator;import edu.wpi.first.math.geometry.Pose2d;import edu.wpi.first.wpilibj.Timer;import frc.robot.LimelightHelpers;
public class CommandSwerveDrivetrain extends SubsystemBase { private final SwerveDrivePoseEstimator m_poseEstimator;
public void updateVisionOdometry() { // Fetch MegaTag2 estimate from Limelight LimelightHelpers.PoseEstimate estimate = LimelightHelpers.getBotPoseEstimate_wpiBlue("limelight");
// Validate estimate if (estimate == null || estimate.tagCount == 0) { return; // No tags visible }
// Reject observations when spinning too fast (> 720 deg/s causes optical blur) if (Math.abs(m_pigeon2.getAngularVelocityZWorld().getValueAsDouble()) > 720.0) { return; }
// Calculate dynamic standard deviation based on distance to tags double avgDistance = estimate.avgTagDist; if (avgDistance > 5.0) { return; // Discard tags beyond 5 meters (high pixel noise) }
// Standard deviation scales with distance squared // Close tag (1m) -> stdDev = 0.05m (high confidence) // Distant tag (4m) -> stdDev = 0.80m (low confidence) double xyStdDev = 0.05 * Math.pow(avgDistance, 2);
// Trust the IMU for rotation; trust vision for translation m_poseEstimator.setVisionMeasurementStdDevs( VecBuilder.fill(xyStdDev, xyStdDev, 9999999) );
// Ingest measurement with timestamp latency compensation m_poseEstimator.addVisionMeasurement( estimate.pose, estimate.timestampSeconds ); }
@Override public void periodic() { // Update wheel odometry at 50 Hz or via 250 Hz background thread m_poseEstimator.update(m_pigeon2.getRotation2d(), getModulePositions());
// Ingest vision updateVisionOdometry(); }}3. Why Latency Compensation is Critical
Section titled “3. Why Latency Compensation is Critical”When an onboard camera captures a frame, processes the image, and sends the pose over NetworkTables, 25 to 40 milliseconds have elapsed.
If your robot is sprinting at 4.0 m/s, the robot has traveled 16 cm during that processing window! If you apply the measurement as if it occurred now, you inject a 16 cm error into your odometry.
SwerveDrivePoseEstimator solves this by maintaining a rolling history buffer of wheel odometry. When you pass estimate.timestampSeconds, the Kalman filter rewinds its history, applies the vision correction to the exact millisecond the camera shutter opened, and propagates the correction forward to the present.
Always use estimate.timestampSeconds supplied by the vision coprocessor. Using Timer.getFPGATimestamp() ignores camera exposure and network latency, causing pose corruption while driving.
Common Failure Modes
Section titled “Common Failure Modes”1. Vision Teleports the Robot Across Field
Section titled “1. Vision Teleports the Robot Across Field”- Symptom: While driving, the robot odometry suddenly jumps 4 meters across the field.
- Cause: Single-tag ambiguity without gyro constraint, or wrong coordinate origin (
wpiBluevswpiRed). - Fix: Use
LimelightHelpers.getBotPoseEstimate_wpiBlue()and enable MegaTag2 with IMU orientation.
2. Odometry Sinks Over Match Play
Section titled “2. Odometry Sinks Over Match Play”- Symptom: By the end of a match, the robot thinks it is outside the field perimeter.
- Cause: Camera mounting angle in configuration had opposite sign (+Pitch instead of -Pitch).
- Fix: Re-verify pitch sign by tilting the robot up and observing whether calculated Z height increases.
Check Your Work
Section titled “Check Your Work”- Drive the robot aggressively across the field, intentionally spinning wheels against carpet to induce odometry slip.
- Stop in front of an AprilTag.
- Observe the robot pose on the AdvantageScope 2D field view: the estimated pose should snap smoothly to true physical position within 0.1 seconds.
Verified Sources & Standards
- WPILib SwerveDrivePoseEstimator & Kalman Filtersdocs.wpilib.orgWPILib Standard