Skip to content
learnFRC.org
programminglesson35 min

Swerve Pose Estimator & Vision Fusion

Fusing wheel odometry with latency-compensated vision measurements in SwerveDrivePoseEstimator with dynamic standard deviations.

What you will learn

  • Understand the sensor fusion model inside SwerveDrivePoseEstimator.
  • Apply latency compensation to optical vision measurements using timestamps.
  • Dynamically scale vision measurement standard deviations based on tag distance and count.

Prerequisites:AprilTag Geometry & MegaTag Algorithms

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).


SensorUpdate RateLatencyShort-Term AccuracyLong-Term Accuracy
Wheel Odometry + Pigeon 2.0250 Hz (CAN FD)< 4 msSub-millimeter, smoothDrifts over time
AprilTag Camera (Limelight)20-50 Hz20-40 msNoisy at distanceZero 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.


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();
}
}

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.

Never Use Timer.getFPGATimestamp() Directly

Always use estimate.timestampSeconds supplied by the vision coprocessor. Using Timer.getFPGATimestamp() ignores camera exposure and network latency, causing pose corruption while driving.


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 (wpiBlue vs wpiRed).
  • Fix: Use LimelightHelpers.getBotPoseEstimate_wpiBlue() and enable MegaTag2 with IMU orientation.
  • 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.

  1. Drive the robot aggressively across the field, intentionally spinning wheels against carpet to induce odometry slip.
  2. Stop in front of an AprilTag.
  3. 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

Evergreen Standard Verified: Sep 25, 2026