PID Control
Mediumdifficulty
You'll use PID for arm position, flywheel speed, heading hold, and lift height, probably more than any other controller. The name makes it sound complicated, but each of the three terms answers a simple question about the error.
Proportional control stops short
In Control & Feedback you met the proportional rule, . Put it on an arm that has to hold itself out horizontally.
Say the arm needs 0.2 power to hold against gravity, and power per degree. A proportional controller only produces 0.2 power when the error is . So the arm settles 20° low and stays there. Doubling halves the droop to 10°, but it also makes the arm more likely to overshoot and oscillate, and the droop never reaches zero. A heavier game element or a sagging battery makes it worse.
Proportional control only looks at the error right now. To do better, the controller also needs to look at how the error has behaved over time and how fast it's changing.
Three questions about the error
Follow one arm through a few loops. The target is 90°, and each loop is 0.02 s.
| Loop | Measured angle | Error | Error added up, | Change in angle per second |
|---|---|---|---|---|
| 1 | 70° | 20° | 0.40 °·s | — |
| 2 | 72° | 18° | 0.76 °·s | +100 °/s |
| 3 | 73.5° | 16.5° | 1.09 °·s | +75 °/s |
Each column answers a different question.
How far off is it now? That's the error, 16.5° on loop 3. The P term pushes in proportion to it: .
How long has it been off? Add up each loop's error times the loop time. That running total keeps growing as long as the arm stays low, so a term built from it, , keeps pushing harder until the error is actually gone. That's the I term, and it's what removes the 20° droop from the example above. In calculus this running total is the integral, .
How fast is it moving? The angle went from 72° to 73.5° in 0.02 s, which is 75 °/s. If the arm is closing in fast, you want to ease off before it overshoots. The D term pushes against that motion: . In calculus the rate of change is the derivative.
Put together:
where is the measurement. You'll also see the D term written as , the rate of change of the error. For a target that isn't moving, the two are the same thing, since the error only changes when the measurement does. They differ when the target jumps, which comes up below.
- P is a spring. It pulls toward the target harder the farther away you are. A spring with no damping would bounce back and forth forever.
- D is a shock absorber. It pushes against motion, harder the faster you move, which is why it's often called velocity feedback. With suitable gains it lets the arm arrive and settle instead of bouncing. For an ideal mass the boundary between overshooting and not is . Less damping than that overshoots. More settles without overshoot, just more slowly.
- I moves where the spring rests. It slowly builds up whatever constant push the job needs, like holding an arm against gravity, so the spring doesn't have to stay stretched to provide it.
In the demo, the drone has to hover at the dashed line while gravity pulls it down, which is the same droop problem as the arm. Drag the target, change the gains, and watch each term's contribution.
- P only. The drone settles below the target. Without an integral term, it can only produce the thrust to fight gravity by staying low.
- PID (tuned). The integral builds up exactly the extra thrust gravity needs, and the drone settles on the target. Watch the yellow I bar climb.
- Too much kP, then a wind gust. It overshoots and oscillates. Adding kD calms it down.
Tuning
A procedure that works for most mechanisms: raise until the mechanism just starts to oscillate, then back off a bit. Add to damp the overshoot. Add last, and only if there's still a steady error you can't fix with feedforward. Log each term and the final output while you do it.
| Symptom | Likely cause | Try |
|---|---|---|
| Slow to respond | kP too low | raise kP |
| Overshoots and oscillates | kP too high or kD too low | lower kP, raise kD |
| Stops short of the target | no kI, or missing feedforward | add feedforward, then a little kI |
| Slow, wide oscillation | kI too high | lower kI |
| Big overshoot after a long move at full power | integral windup | add anti-windup (next lesson) |
| Jittery, twitchy | kD too high for the noise | lower kD, filter the velocity |
PID in a loop
On the robot, the running total is a sum with one rectangle per loop, and the rate of change is the difference between two readings divided by the measured , as in From Math to a Loop:
private double integral, lastMeasurement;
private boolean firstLoop = true;
// target and measurement in encoder ticks; dt is the measured loop time.
double update(double target, double measurement, double dt) {
if (!Double.isFinite(dt) || dt <= 0) return 0;
double error = target - measurement;
integral += error * dt;
double rate = firstLoop ? 0 : (measurement - lastMeasurement) / dt;
lastMeasurement = measurement;
firstLoop = false;
double power = kP * error + kI * integral - kD * rate;
return clamp(power, -1, +1);
}
The motor for this arm runs in RUN_WITHOUT_ENCODER, because this method is the controller and its
output is a motor power. Keep kP, kI, and kD somewhere you can change them live, like FTC
Dashboard, so tuning doesn't mean redeploying.
Two details in that block matter on real hardware.
The derivative uses the measurement, not the error. Suppose the target jumps from 0 to 500 ticks in one 20 ms loop. The error jumps by 500 too, so its rate of change is ticks per second for one loop, and the D term slams the motor to full power even though the arm hasn't moved. This is called derivative kick. The measurement only changes when the arm actually moves, so taking the rate of change of the measurement gives the same damping without the kick. The minus sign is there because, for a fixed target, the error goes down exactly as fast as the measurement goes up.
The integral needs protection when the output is maxed out. While the motor sits at full power the error keeps adding up, and all that stored-up push comes out as overshoot later. The fix is covered in Actuator Saturation & Anti-Windup.
Libraries like FTCLib include a PID class, which is fine to use, but check how it computes the
derivative. FTCLib's PIDController takes the rate of change of the error, so it will kick when the
target jumps.
The controller computes 3.7. What does that mean, and what does the SDK do with it? And why does it
matter that the motor is in It means the controller wants 3.7 times full power, which doesn't exist, so the output is clipped to 1.
While it sits there, anything the integral adds is windup. This method outputs a motor power. RUN_WITHOUT_ENCODER rather than a mode that treats the command as a
velocity or position request?Show solution
RUN_USING_ENCODER treats the command as a velocity target and
RUN_TO_POSITION as a position target, so sending the same number through those modes would change
what it means and give behavior this controller wasn't tuned for. Stacking loops can be done on
purpose, with an outer position loop feeding an inner velocity loop, but that's a design you tune
inner loop first, not something that should happen by accident.
The D term multiplies a rate of change, and differencing encoder readings over a short loop turns one tick of jitter into a big spike. A light low-pass filter on that computed velocity helps a lot. A noisy analog sensor, like a distance sensor, needs filtering before you use it at all.
PDFL: replacing the integral
Look back at the arm. The steady push it needed was for gravity, and gravity is predictable. You can just supply it, instead of waiting for an integral to discover it slowly and then having to protect that integral from windup. That's the idea behind a controller the FTC community calls PDFL, after the video linked below: proportional, derivative, feedforward, and a lower limit, with no integral.
The F and L terms are the same things you met in feedforward, under different names:
- P: proportional to the error, as before.
- D: the derivative of the measurement, passed through a low-pass filter so encoder jitter doesn't get amplified. (See low-pass filters.)
- F: a constant that holds the mechanism against gravity. This is from the feedforward lesson. On a slide it really is one constant. On an arm the hold changes with , so for an arm that sweeps a wide range, use instead and keep the rest.
- L: a small push in the direction of the error, just enough to overcome friction. This is . It's turned off inside a small dead zone around the target, because there the error's sign flips every loop and the push would make the mechanism buzz.
with the term only applied outside the dead zone.
Slowly raise the power by hand until the mechanism just starts to move up. Call that . Then lower the power until it just starts to creep down, and call that . Going up, the motor fights gravity and friction, so . Going down, gravity helps and friction still resists, so . Solving:
For example, if it starts moving up at 0.26 and creeps down at 0.14, then and . There's no single power that "holds it still," because friction lets it hold anywhere between those two readings.
A walkthrough of these changes: swapping the integral for feedforward, differentiating the measurement, and filtering the derivative, and why they work better than textbook PID on FTC mechanisms.
Open video// No integral term at all: F and L do that job explicitly.
double run(double target, double measurement, double dt) {
dt = Math.max(MIN_DT, dt); // measured, never assumed
double error = target - measurement;
double p = kP * error;
double rawD = firstLoop ? 0 : -(measurement - lastMeasurement) / dt;
double alpha = 1 - Math.exp(-dt / TAU);
filteredD += alpha * (rawD - filteredD);
double d = kD * filteredD;
lastMeasurement = measurement;
firstLoop = false;
double f = kF; // a constant that holds against gravity
double l = kL * Math.signum(error); // a static-friction floor
if (Math.abs(error) < DEADZONE) return p + d + f; // drop L near target
return p + d + f + l;
}
The encoder jitters by one tick. At One tick in 20 ms is 50 ticks per second of velocity that isn't real, multiplied by dt = 0.02 s, what velocity does that one tick look like? Then
check what alpha does as dt gets much larger than TAU.Show solution
kD and sent to the
motor every loop. The filter averages it out at the cost of a little lag. As dt grows past TAU,
shrinks toward zero and alpha goes to 1, which means "so much time has passed, just use
the new value."
Math.signum(error) flips every time the arm crosses the target. Trace three loops with the arm
wobbling one tick either side. What does the mechanism sound like?Show solution
l alternates between +kL and -kL, so the command jumps by at 50 Hz around a target the
arm has basically already reached. It buzzes and the gearbox takes the load for nothing. The dead zone
turns the friction push off once the arm is close enough that it doesn't matter.
With holding the load and breaking friction, there's nothing to wind up.
Where to go next
PID only reacts to error that has already happened, so pair it with feedforward for the bulk of the command. The rest of the module covers what happens when the motor maxes out (anti-windup), a simpler controller that often works better for flywheels (bang-bang), and how to move fast without overshooting by feeding the controller a motion profile instead of a step.
- CTRL ALT FTC - FTC-focused PID, feedforward, and tuning explanations.
- FTCLib Controllers - FTC library reference for PID/PIDF controller structure.
- PDFL - Improving Upon PID - video reference for the feedforward, derivative filtering, and lower-limit refinements discussed here.