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.
Quick Specs
Section titled “Quick Specs”| Parameter | Recommended Value | Engineering Purpose |
|---|---|---|
| Continuous Input | -Math.PI to +Math.PI radians | Wraps error across the 180/-180 boundary to take shortest path |
| Heading Tolerance | 1.5 to 2.5 degrees | Prevents aggressive motor hunting when aligned |
| Driver Override Deadband | 0.10 to 0.15 stick input | Automatically yields control when driver moves rotation stick |
| Output Saturation | +/- 4.0 rad/s to +/- 8.0 rad/s | Prevents module wheel saturation during combined translation |
Production Implementation
Section titled “Production Implementation”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); }}Key Failure Modes and Common Traps
Section titled “Key Failure Modes and Common Traps”- 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.discretizeand WPILib’sSwerveDriveKinematics.desaturateWheelSpeeds. - Gyro Field Frame Inversion: Red vs Blue alliance orientation offsets (180 degree flip) must be integrated into
targetAngleSupplierso 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.
Bench Verification Checklist
Section titled “Bench Verification Checklist”- 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.
- 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.
- 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.
- 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
- WPILib PIDController Class Guidedocs.wpilib.orgWPILib Standard
- WPILib Holonomic Drive Controllerdocs.wpilib.orgWPILib Standard