Lab 6: Closed-Loop Drive Speed (Feedforward + PID)

Goal: when we ask a wheel for 1.0 m/s, it actually goes 1.0 m/s, even with friction, and even when the robot is heavier or the floor is stickier than we planned for.

Why: predict first, correct second

Until now, the drive was open loop: "give the motor 12 V × (speed / top speed)" and hope. Graph DriveVelocityMps against the desired speed and you'll see they don't match, especially at low speed, because friction eats part of the voltage.

A DC motor's voltage is almost a straight line of its speed:

volts = kS × sign(v)  +  kV × v       (+ kA × acceleration, ignore for now)
          │                 └ volts per (m/s): the slope
          └ volts just to overcome friction and start moving

That's feedforward: we predict the voltage we need. It does ~90% of the work. Then a small PID fixes the leftover error:

volts = kS × sign(v) + kV × v_target  +  kP × (v_target − v_measured)

Why not PID alone? A PID only pushes when there's error. To hold 2 m/s it would need a constant error to keep pushing. Feedforward doesn't wait for error.

First guess for kV: 12 V should give about the theoretical top speed, so kV ≈ 12 / maxTheoreticalSpeed. kS: the voltage where the wheel just started moving in Lab 1.

Cosine scaling. While a module is still turning toward its target, the wheel points partly sideways and pushes the robot the wrong way. Scale the speed by how well it's aligned:

speed × cos(angle error)      0° error → full speed; 90° error → zero

Do it after optimization, so the error is always under 90° and the cosine is never negative.

Code

In SwerveModule, replace the open-loop drive voltage in setDesiredState with:

private final PIDController drivePid = new PIDController(0, 0, 0);

private void setDriveVelocity(double targetMetersPerSecond) {
  double kS = Tunable.number("Drive/kS", 0.1);    // volts
  double kV = Tunable.number("Drive/kV", 12.0 / Constants.Swerve.MAX_THEORETICAL_SPEED_METERS_PER_SECOND);  // volts per m/s
  drivePid.setP(Tunable.number("Drive/kP", 0.0)); // volts per m/s of error

  // TODO (students): feedforward = kS × sign(target) + kV × target.
  // What should kS do when the target is exactly 0?
  double feedforwardVolts = 0;

  double feedbackVolts = Tunable.toggle("Drive/UsePID", true)
      ? drivePid.calculate(getDriveVelocityMetersPerSecond(), targetMetersPerSecond)
      : 0;
  io.setDriveVoltage(driveSign() * (feedforwardVolts + feedbackVolts));

  SmartDashboard.putNumber("Swerve/" + name + "/DriveTargetMps", targetMetersPerSecond);
}

And add cosine scaling (students write it) before calling it:

double speed = desired.speedMetersPerSecond;
if (Tunable.toggle("Drive/UseCosineScaling", true)) {
  // TODO (students): multiply speed by cos(desired angle − current angle).
}
setDriveVelocity(speed);

WPILib has SwerveModuleState.cosineScale(currentAngle). Add a unit test comparing yours to it.

NEO velocity lag. On a real robot, the SPARK MAX averages the NEO's velocity over a long window, so the reading lags ~100 ms behind reality. That makes a large kP oscillate. The simulator can fake it: Sim/VelocityFilterTaps averages the last N readings (1 = no lag; 5 ≈ a real NEO). REVLib lets you shorten the window on real hardware (see Lab 11).

Try it

  1. Graph DriveTargetMps and DriveVelocityMps for one module.
  2. Drive/UsePID off. Adjust kS and kV until the actual speed nearly matches at 0.25, 0.5, and 1.0 m/s.
  3. Drive/UsePID on. Raise Drive/kP slowly until the remaining error disappears without oscillation.
  4. Make the floor stickier: Sim/DriveFrictionVolts 0.25 → 0.6. Check again: kS needs to go up.

Experiments

Change Predict What you'll see
kS = 0, kV only, target 0.1 m/s Does it move? Barely or not at all: friction eats the small voltage
kV 20% too low, no PID Always slower than target, by a % that stays the same
kV 20% too low, with PID Closer, but PID alone never quite closes the gap
kP only (kS = kV = 0), large kP Slow to respond, then oscillates. This is why feedforward matters.
Sim/DriveFrictionVolts = 0.6 with closed loop vs. with the old open-loop code Closed loop holds the speed; open loop gets slower
Sim/VelocityFilterTaps = 5 with your kP Oscillation or overshoot: the PID reacts to old data. Lower kP.
Snap the stick from forward to left, cosine scaling off The robot lurches sideways for a moment
Same, on Wheels turn first, then accelerate. Smoother.

Checkpoint

Summary: Feedforward predicts the voltage; PID trims the error. Cosine scaling stops wheels pushing sideways while they turn.

Quiz

  1. What does kV mean physically? What's ours?
  2. Why does PID alone need error to keep pushing?
  3. What's kS for, and what happens at target speed 0?
  4. Why apply cosine scaling after optimization?
  5. Why does a laggy velocity reading limit kP?

What could go wrong in the real world: kS tuned with the wheels in the air being too low on carpet; a wheel slipping (encoder says it's moving, robot isn't); voltage sag at full speed (the battery can't give 12 V, so top speed is lower than calculated).