Lab 2: Steering to an Angle (PID)

Goal: type an angle on the dashboard and watch the module turn to it. Tune the PID live and feel what kP and kD do.

Why: PID and continuous input

The controller looks at the error (target − current angle) and outputs a voltage:

volts = kP × error  +  kD × (how fast the error is changing)
  • kP (volts per radian): bigger error → push harder. Too low: sluggish, never quite gets there. Too high: overshoots and oscillates.
  • kD: brakes as you approach the target. Reduces overshoot.
  • kI: we won't need it for steering. Leave it at 0.

Continuous input. An angle of 179° and −179° are only 2° apart. But plain subtraction says the error is 358°, so the module would spin almost a full turn the long way. enableContinuousInput(-π, π) tells the PID that the angle wraps, so it takes the short way.

        0°
        |
 90° ---+--- -90°        target −170°, current +170°
        |                plain error:      −340°  (long way)
     ±180°               continuous error:  +20°  (short way)

Code

We run the PID in our robot code with WPILib's PIDController, using the absolute encoder as feedback. (On a real robot, teams often run it on the SPARK MAX instead, which is faster. In our own code you can see every step, so we start here.)

In SwerveModule:

// imports: edu.wpi.first.math.controller.PIDController,
//          edu.wpi.first.math.geometry.Rotation2d, edu.wpi.first.math.MathUtil
private final PIDController steerPid = new PIDController(0, 0, 0);

/** Module angle, radians. Lab 3 adds the offset so 0 = straight forward. */
public Rotation2d getAngle() {
  return Rotation2d.fromRadians(getRawAngleRadians());
}

/** Turn the module toward targetAngle. Call every loop. */
public void setSteerTarget(Rotation2d targetAngle) {
  // Read the knobs every loop so changes on the dashboard take effect immediately.
  steerPid.setP(Tunable.number("Steer/kP", 0.5));   // volts per radian of error
  steerPid.setD(Tunable.number("Steer/kD", 0.0));
  if (Tunable.toggle("Steer/ContinuousInput", true)) {
    steerPid.enableContinuousInput(-Math.PI, Math.PI);
  } else {
    steerPid.disableContinuousInput();
  }

  double volts = steerPid.calculate(getAngle().getRadians(), targetAngle.getRadians());
  double maxVolts = Tunable.number("Steer/MaxVolts", 4.0);
  io.setSteerVoltage(MathUtil.clamp(volts, -maxVolts, maxVolts));

  SmartDashboard.putNumber("Swerve/" + name + "/SteerTargetDeg", targetAngle.getDegrees());
  SmartDashboard.putNumber("Swerve/" + name + "/SteerErrorDeg", Math.toDegrees(steerPid.getError()));
}

Log AngleDeg (from getAngle().getDegrees()) in log() too, since it's in (−180°, 180°] instead of 0–360.

In RobotContainer, replace the Lab 1 default command (keep it in a comment; you may want it back):

swerve.setDefaultCommand(Commands.run(() -> {
  int index = (int) Tunable.number("Lab2/ModuleIndex", 0);
  Rotation2d target = Rotation2d.fromDegrees(Tunable.number("Lab2/TargetDeg", 0));
  for (int i = 0; i < 4; i++) {
    if (i == index) {
      swerve.getModule(i).setSteerTarget(target);
    } else {
      swerve.getModule(i).stop();
    }
  }
}, swerve));

Try it

  1. In AdvantageScope, graph SteerTargetDeg and AngleDeg on the same line graph.
  2. Enable Teleoperated. Set Lab2/TargetDeg to 90, then 0, then −90.
  3. Tune: raise Steer/kP until it gets there quickly with a small overshoot, then add a little Steer/kD to remove the overshoot.

Experiments

Change Predict What you'll see
Steer/kP = 0.1 Fast or slow? Reaches the target? Slow, and stops short: the voltage near the target is too small to overcome friction
Steer/kP = 10 ? Overshoot and oscillation. On a real robot you'd hear it buzz.
Find the kP where it just starts to oscillate. Use about half. A common tuning rule of thumb
Add Steer/kD 0.05, 0.1, 0.2 Overshoot goes... Down. Too much kD makes it jittery (noise in the encoder gets amplified)
Target 170°, then −170° with ContinuousInput on Turns 20° or 340°? 20°
Same, with ContinuousInput off 340°, the long way around. This is the bug continuous input fixes.
Steer/MaxVolts = 1 Slow, steady turn. The PID is "saturated": it wants more voltage than allowed.
Sim/SteerFrictionVolts = 0.6 (stickier module) with your tuned kP It stops a few degrees short. Raise kP, or add a small kS-style boost.
Sim/Faults/FL/EncoderReversed on, with ABS_ENCODER_INVERTED still false The PID pushes the wrong way and the module spins forever. On a real robot: disable!
Push the wheel with the sim "hand" (Sim/Hand/SteerVolts = 1) while it holds an angle How far does it get pushed? A little; it pushes back harder the further it's pushed (that's kP). Raise kP: pushed less.

Copy your best kP/kD into Constants when you're done.

Checkpoint

Summary: A position PID with continuous input turns the module to any angle the short way.

Quiz

  1. What are the units of Steer/kP in our code?
  2. What does kD do, and why can too much of it cause jitter?
  3. Why does −170° to +170° need continuous input?
  4. If the encoder reads backwards, why does the module spin forever instead of just going to the wrong angle?
  5. Why does a low kP stop short of the target?

What could go wrong in the real world: encoder direction backwards (the module spins forever: disable!); a loose encoder magnet giving a noisy angle; kP tuned on blocks that's too aggressive with carpet friction.