Fused Pose Estimation

advanced70 min

Introduction to Sensor Fusion

Fusion keeps odometry running fast and pulls pose toward vision when a measurement is trustworthy. This lesson uses WPILib SwerveDrivePoseEstimator; tank templates use DifferentialDrivePoseEstimator the same way.

Examples show structure only—your drivetrain template fills in hardware.

WPILib: Pose Estimator Documentation

Why Fuse?

Odometry updates every loop but drifts. Vision is absolute when tags are in view but can drop out behind robots or glare. A pose estimator blends both instead of snapping or ignoring either source.

How Fusion Works

Each loop: update() with gyro and wheel/module data. When vision returns a pose and timestamp, addVisionMeasurement(). Standard deviations (stateStdDevs, visionStdDevs, and per-measurement overrides) tell the filter how much to trust each source.

Setting Up the Pose Estimator

You need swerve (or diff) kinematics, initial module positions and heading, starting pose, and std dev vectors for state and vision.

Defining Kinematics

import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.kinematics.SwerveDriveKinematics;

// Robot dimensions (measured from your robot, in meters)
private static final double kTrackWidth = 0.5;
private static final double kWheelBase = 0.5;

// Calculate module positions from robot center
Translation2d frontLeft = new Translation2d(kWheelBase / 2.0, kTrackWidth / 2.0);
Translation2d frontRight = new Translation2d(kWheelBase / 2.0, -kTrackWidth / 2.0);
Translation2d rearLeft = new Translation2d(-kWheelBase / 2.0, kTrackWidth / 2.0);
Translation2d rearRight = new Translation2d(-kWheelBase / 2.0, -kTrackWidth / 2.0);

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

Configuring Standard Deviations

import edu.wpi.first.math.VecBuilder;

// State uncertainty: how much odometry might drift
// Tune based on your encoder and gyro accuracy
var stateStdDevs = VecBuilder.fill(0.1, 0.1, 0.1);

// Vision uncertainty: how accurate vision measurements are
// Tune based on camera quality and tag detection accuracy
var visionStdDevs = VecBuilder.fill(0.5, 0.5, 0.5);

Creating the Pose Estimator

import edu.wpi.first.math.estimator.SwerveDrivePoseEstimator;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.kinematics.SwerveModulePosition;

// Get initial sensor readings from hardware
Rotation2d initialHeading = m_gyro.getRotation2d();
SwerveModulePosition[] initialModulePositions = getModulePositions();
Pose2d initialPose = new Pose2d();

// Create pose estimator with all required parameters
m_poseEstimator = new SwerveDrivePoseEstimator(
    m_kinematics,
    initialHeading,
    initialModulePositions,
    initialPose,
    stateStdDevs,
    visionStdDevs
);

Updating with Odometry

Call update in periodic() with fresh gyro heading and module positions.

Getting Module Positions

import edu.wpi.first.math.kinematics.SwerveModulePosition;

public void updateOdometry() {
    // Read position from each swerve module
    m_modulePositions[0] = m_modules[0].getPosition();
    m_modulePositions[1] = m_modules[1].getPosition();
    m_modulePositions[2] = m_modules[2].getPosition();
    m_modulePositions[3] = m_modules[3].getPosition();
}

Updating the Estimator

import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.kinematics.SwerveModulePosition;

public void updateOdometry() {
    // Get current sensor readings
    Rotation2d heading = m_gyro.getRotation2d();
    
    // Get module positions
    SwerveModulePosition[] modulePositions = getModulePositions();
    
    // Update pose estimator
    m_poseEstimator.update(heading, modulePositions);
}

Adding Vision Measurements

Vision arrives when the pipeline sees tags—not necessarily every loop. Validate before addVisionMeasurement: skip high ambiguity, single tags at long range, or zero-tag estimates.

Integrating Vision with Pose Estimator

import edu.wpi.first.math.VecBuilder;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.estimator.SwerveDrivePoseEstimator;
import frc.robot.LimelightHelpers.PoseEstimate;
import java.util.Optional;

public void updateVision() {
    // Get pose estimate from vision subsystem
    Optional<PoseEstimate> visionPoseEstimate = m_vision.getAprilTagPoseEstimate();
    
    if (visionPoseEstimate.isPresent()) {
        PoseEstimate estimate = visionPoseEstimate.get();
        
        // Validate measurement quality
        boolean shouldReject = false;
        
        // Reject single-tag measurements with high ambiguity
        if (estimate.tagCount == 1 && estimate.rawFiducials.length == 1) {
            if (estimate.rawFiducials[0].ambiguity > 0.7) {
                shouldReject = true;
            }
        }
        
        // Reject tags that are too far away
        if (estimate.tagCount == 1 && estimate.rawFiducials.length == 1) {
            if (estimate.rawFiducials[0].distToCamera > 3.0) {
                shouldReject = true;
            }
        }
        
        // Reject if no tags detected
        if (estimate.tagCount == 0) {
            shouldReject = true;
        }
        
        if (!shouldReject) {
            // Adjust uncertainty based on tag count
            // More tags = more accurate = lower uncertainty
            if (estimate.tagCount >= 2) {
                m_poseEstimator.setVisionMeasurementStdDevs(
                    VecBuilder.fill(0.3, 0.3, 9999999)
                );
            } else {
                m_poseEstimator.setVisionMeasurementStdDevs(
                    VecBuilder.fill(0.5, 0.5, 9999999)
                );
            }
            
            // Add vision measurement with timestamp
            m_poseEstimator.addVisionMeasurement(
                estimate.pose,
                estimate.timestampSeconds
            );
        }
    }
}

Putting It All Together

In periodic(), update odometry, then vision if present. Read fused pose from getEstimatedPosition().

Complete Periodic Update

import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

@Override
public void periodic() {
    // Update odometry continuously (always available)
    updateOdometry();
    
    // Update vision when available (asynchronous)
    updateVision();
    
    // Get the fused pose estimate
    Pose2d currentPose = m_poseEstimator.getEstimatedPosition();
    
    // Optional: Display on SmartDashboard for debugging
    SmartDashboard.putNumber("Fused X", currentPose.getX());
    SmartDashboard.putNumber("Fused Y", currentPose.getY());
    SmartDashboard.putNumber("Fused Heading", 
        currentPose.getRotation().getDegrees());
}

Resources