Gray Matter
WorkshopVision
Rough draft: nobody has reviewed this lesson yet, and it may not be how things are done this season.
LESSON 25

Vision

This lesson feeds AprilTag sightings into the pose estimator so the camera pulls odometry back toward the truth.

Branchswerve-vision14 minutes
You’ll need
  • A camera mounted, wired and calibrated in Vision Hardware, and its name written down.
  • Odometry you trust, from Swerve Drive Tuning. Vision corrects drift, not a wrong wheel radius.
  • The swerve project.
  • An AprilTag. A printed one on a wall works.
Watch out

No camera in simulation

None of this runs in the simulator, because there is no camera. Check this page on the real robot.

Install the library

LimelightLib is a vendor dependency, like Phoenix 6. Open the WPILib Vendor Dependencies view from the activity bar on the left. Expand INSTALL FROM URL, paste the URL below, and press Install.

Vendor dependency URL
https://limelightvision.github.io/limelightlib-public/LimelightLib-alpha7.json
Install from URL
The WPILib Vendor Dependencies panel in VS Code, with the INSTALL FROM URL section expanded and the Install button circled
Paste the URL, press Install, and it appears under INSTALLED DEPENDENCIES.

Build once so Gradle downloads it. You now have com.limelightvision.Limelight, one object per camera.

Limelight: LimelightLib

The Vision class

Create src/main/java/frc/robot/subsystems/Vision.java and paste the whole class. It is called Vision and not Limelight because the library owns that name.

src/main/java/frc/robot/subsystems/Vision.java
package frc.robot.subsystems;
 
import com.limelightvision.Limelight;
import com.limelightvision.LimelightResults;
import com.limelightvision.PoseEstimate;
import com.limelightvision.PoseEstimateType;
import java.util.ArrayList;
import java.util.List;
import org.wpilib.command3.Scheduler;
import org.wpilib.math.linalg.VecBuilder;
 
/**
* Feeds AprilTag sightings from every Limelight on the robot into the drivetrain's pose estimator,
* so the camera pulls odometry back toward the truth.
*
* <p>A camera drives nothing, so this is not a {@code Mechanism}. It runs from the scheduler's
* periodic list instead, every loop and in every mode.
*/
public class Vision {
// Trust weighting. A sighting's error bar grows with distance and shrinks with tag count.
private static final double XY_STD_DEV_COEFFICIENT = 0.333;
private static final double ROTATION_STD_DEV_COEFFICIENT = 1.5;
private static final double MAX_TAG_DISTANCE_METERS = 4.0;
// MegaTag2 solved from our own heading, so its heading is not a new measurement.
private static final double IGNORE_VISION_HEADING = 9_999_999;
private static final int MIN_TAGS_FOR_MEGATAG1 = 2;
 
private final DriveMechanism drivetrain;
private final List<Limelight> cameras = new ArrayList<>();
 
/**
* @param drivetrain the drivetrain whose pose estimate the cameras correct
* @param cameraNames each camera's NetworkTables name, exactly as set in its web interface
*/
public Vision(DriveMechanism drivetrain, String... cameraNames) {
this.drivetrain = drivetrain;
for (String name : cameraNames) {
Limelight camera = new Limelight(name);
// Read the heading that update() shares, for MegaTag2.
camera.setUseSharedOrientation(true);
cameras.add(camera);
}
Scheduler.getDefault().addPeriodic(() -> update());
}
 
private void update() {
// One write reaches every camera that reads the shared heading.
Limelight.setSharedRobotOrientation(drivetrain.getPose().getRotation().getDegrees());
 
for (Limelight camera : cameras) {
// Every frame since the last loop, so none is skipped and none is used twice.
for (LimelightResults frame : camera.readResultsQueue()) {
addFrame(camera, frame);
}
}
}
 
private void addFrame(Limelight camera, LimelightResults frame) {
PoseEstimate estimate = camera.getPoseEstimate(frame, PoseEstimateType.MT1_WPIBLUE);
if (estimate.fieldedTagCount < MIN_TAGS_FOR_MEGATAG1) {
estimate = camera.getPoseEstimate(frame, PoseEstimateType.MT2_WPIBLUE);
}
 
// Zero means the library's own gates found nothing wrong with the frame.
if (estimate.rejectionFlags != 0 || estimate.avgTagDistanceMeters > MAX_TAG_DISTANCE_METERS) {
return;
}
 
double distanceFactor = Math.pow(estimate.avgTagDistanceMeters, 1.2);
double tagFactor = estimate.fieldedTagCount * estimate.fieldedTagCount;
double xyStdDev = XY_STD_DEV_COEFFICIENT * distanceFactor / tagFactor;
double headingStdDev =
estimate.isMT2()
? IGNORE_VISION_HEADING
: ROTATION_STD_DEV_COEFFICIENT * distanceFactor / tagFactor;
 
// The picture's own timestamp: the estimator winds back to when it was taken.
drivetrain.addVisionMeasurement(
estimate.pose,
estimate.timestampSeconds,
VecBuilder.fill(xyStdDev, xyStdDev, headingStdDev));
}
}
  • A camera drives nothing, so Vision is not a mechanism. The constructor hands update() to Scheduler.getDefault().addPeriodic, which runs it every loop.
  • setUseSharedOrientation(true) tells each camera to read a shared heading topic, and the static Limelight.setSharedRobotOrientation writes it once per loop for every camera. MegaTag2 needs that heading.
  • readResultsQueue() hands back every frame that arrived since the last call, so no frame is skipped and none is used twice.
  • The camera solves each frame two ways. MegaTag1 solves position and heading from the tags, and needs two or more to do it well. MegaTag2 takes your heading as given and solves only position, so one tag is enough. addFrame asks MegaTag1 first, and under two tags it asks the same frame again as MegaTag2.
  • rejectionFlags is the library's own verdict on the frame, and zero means it found nothing wrong. By default it rejects a single tag past three meters or with ambiguity over 0.7. PoseEstimateConfig.describeRejection(flags) names the reason.
  • addVisionMeasurement takes estimate.timestampSeconds, not the current time, because the picture was taken before your code saw it.
  • Each sighting goes in with a standard deviation, how far off it might be. It grows with distance and shrinks with tag count, and a bigger number means trust it less. A MegaTag2 heading is the one you handed the camera, so it goes in with IGNORE_VISION_HEADING.

Start it in Robot

Add one field to Robot, under the drivetrain. An OpMode is thrown away on every mode switch, and vision has to keep correcting in every mode.

src/main/java/frc/robot/Robot.java
import frc.robot.subsystems.DriveMechanism;
import frc.robot.subsystems.Vision;
 
// ... the other imports, unchanged
 
public class Robot extends OpModeRobot {
public final DriveMechanism drivetrain = new DriveMechanism();
// Every camera on the robot, by its NetworkTables name. A second camera is a second string.
public final Vision vision = new Vision(drivetrain, "limelight");
 
// ... the constructor and robotPeriodic, unchanged
}

The string has to match the camera's NetworkTables name exactly, the one you wrote down in Vision Hardware.

Check your work

Deploy, put the robot on the floor with a tag in view, and watch Telemetry/Drivetrain/Pose in NetworkTables.

  1. Park about two meters from a tag and note the pose. Cover the camera and push the robot a meter sideways. The pose follows the wheels.
  2. Uncover the camera. The pose settles toward where the tag says the robot is.
  3. Back away past four meters, then close in again. Line up on two tags, then on one.
Check

You should see

Corrections stop past four meters and resume when you close in. With one tag in view the position moves and the heading does not.

Check yourself

The camera has exactly one AprilTag in frame. Which solver does Vision.java ask for, and why?

Why does the code walk readResultsQueue() instead of reading the camera's latest result?

What does a rejectionFlags value of zero tell you about a pose estimate?

Why does addVisionMeasurement take estimate.timestampSeconds instead of the current time?

Why does a MegaTag2 estimate go in with a heading standard deviation of 9,999,999?

Why is Vision a field on Robot rather than something an OpMode creates?

Pick an answer for each.