Skip to content
learnFRC.org
programmingexample

Teleop Heading Lock Swerve Command

Field-oriented swerve snap-to-angle command using WPILib PIDController with continuous input to lock chassis heading to cardinal field orientations.

Heading lock commands allow drivers to translate freely across the field while a closed-loop controller automatically rotates and aligns the chassis to target angles (such as 0 degrees for scoring, 90 degrees for passing, or 180 degrees for human player intake). This pattern utilizes WPILib’s PIDController configured with continuous input wrapping to guarantee shortest-path rotation without gyro wrap discontinuity.

ParameterRecommended ValueEngineering Purpose
Continuous Input-Math.PI to +Math.PI radiansWraps error across the 180/-180 boundary to take shortest path
Heading Tolerance1.5 to 2.5 degreesPrevents aggressive motor hunting when aligned
Driver Override Deadband0.10 to 0.15 stick inputAutomatically yields control when driver moves rotation stick
Output Saturation+/- 4.0 rad/s to +/- 8.0 rad/sPrevents module wheel saturation during combined translation
package frc.robot.commands;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.kinematics.ChassisSpeeds;
import edu.wpi.first.units.measure.AngularVelocity;
import edu.wpi.first.units.measure.LinearVelocity;
import static edu.wpi.first.units.Units.*;
import edu.wpi.first.wpilibj2.command.Command;
import frc.robot.subsystems.CommandSwerveDrivetrain;
import java.util.function.DoubleSupplier;
import java.util.function.Supplier;
public class HeadingLockCommand extends Command {
private final CommandSwerveDrivetrain m_drivetrain;
private final DoubleSupplier m_translationXSupplier;
private final DoubleSupplier m_translationYSupplier;
private final Supplier<Rotation2d> m_targetAngleSupplier;
private final PIDController m_headingController;
private static final double ROTATION_DEADBAND = 0.10;
private static final LinearVelocity MAX_SPEED = MetersPerSecond.of(4.5);
private static final AngularVelocity MAX_ANGULAR_RATE = RadiansPerSecond.of(2.0 * Math.PI);
public HeadingLockCommand(
CommandSwerveDrivetrain drivetrain,
DoubleSupplier translationXSupplier,
DoubleSupplier translationYSupplier,
Supplier<Rotation2d> targetAngleSupplier) {
m_drivetrain = drivetrain;
m_translationXSupplier = translationXSupplier;
m_translationYSupplier = translationYSupplier;
m_targetAngleSupplier = targetAngleSupplier;
// Proportional heading gains in radians
m_headingController = new PIDController(5.0, 0.0, 0.25);
// Enable continuous input between -pi and +pi radians
m_headingController.enableContinuousInput(-Math.PI, Math.PI);
m_headingController.setTolerance(Degrees.of(2.0).in(Radians));
addRequirements(drivetrain);
}
@Override
public void initialize() {
m_headingController.reset();
}
@Override
public void execute() {
// Read driver translation sticks with deadband
double xInput = modifyAxis(m_translationXSupplier.getAsDouble());
double yInput = modifyAxis(m_translationYSupplier.getAsDouble());
LinearVelocity vx = MAX_SPEED.times(xInput);
LinearVelocity vy = MAX_SPEED.times(yInput);
// Current gyro angle in field frame
Rotation2d currentHeading = m_drivetrain.getState().Pose.getRotation();
Rotation2d targetHeading = m_targetAngleSupplier.get();
// Calculate angular velocity correction in radians per second
double omegaRadPerSec = m_headingController.calculate(
currentHeading.getRadians(),
targetHeading.getRadians()
);
// Clamp rotational speed to maximum chassis limit
double maxOmega = MAX_ANGULAR_RATE.in(RadiansPerSecond);
omegaRadPerSec = Math.max(-maxOmega, Math.min(maxOmega, omegaRadPerSec));
// Command swerve drivetrain in field-relative frame
ChassisSpeeds speeds = ChassisSpeeds.fromFieldRelativeSpeeds(
vx.in(MetersPerSecond),
vy.in(MetersPerSecond),
omegaRadPerSec,
currentHeading
);
m_drivetrain.driveFieldOriented(speeds);
}
@Override
public void end(boolean interrupted) {
m_drivetrain.driveFieldOriented(new ChassisSpeeds(0.0, 0.0, 0.0));
}
private static double modifyAxis(double value) {
if (Math.abs(value) < ROTATION_DEADBAND) {
return 0.0;
}
return Math.copySign(Math.pow(value, 2), value);
}
}
  • Missing Continuous Input: Forgetting m_headingController.enableContinuousInput(-Math.PI, Math.PI) causes the chassis to violently rotate 359 degrees in reverse when crossing between +179 degrees and -179 degrees.
  • Unit Mismatch in PID Gains: Using degree setpoints while supplying radian gyro readings scales loop gains by a factor of 57.3, causing immediate rotational oscillation and drive wheel slippage.
  • Wheel Saturation During High Translation: If the driver commands full translation while the rotation controller demands full angular rate, module speeds clip unevenly. Use ChassisSpeeds.discretize and WPILib’s SwerveDriveKinematics.desaturateWheelSpeeds.
  • Gyro Field Frame Inversion: Red vs Blue alliance orientation offsets (180 degree flip) must be integrated into targetAngleSupplier so driver forward remains towards the opposing wall regardless of alliance station.
Alliance-Aware Heading Presets

Use DriverStation.getAlliance() to rotate target presets: on the Blue alliance, 0 degrees points downfield; on the Red alliance, 180 degrees points downfield.

  1. Verify Angle Continuity on Blocks: Place robot on blocks. Set target to 180 degrees and slowly rotate chassis by hand past the 180/-180 boundary. Confirm the commanded motor effort transitions smoothly without sudden reversals.
  2. Confirm Shortest-Path Turning: Command 90 degrees while the robot sits at -90 degrees. Confirm wheels drive the chassis through 180 degrees of travel rather than swinging the long direction.
  3. Validate Driver Translation Independence: Command full forward translation while heading lock is engaged. Confirm the chassis drives straight while actively holding target angle against manual side pushes.
  4. Tolerance Settle Check: Confirm that once the robot settles within the 2.0-degree tolerance window, rotation motor stator current drops below 5A.

Verified Sources & Standards

Evergreen Standard Verified: Oct 1, 2026