Skip to main content

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, u=kPeu = k_P e. Put it on an arm that has to hold itself out horizontally.

Say the arm needs 0.2 power to hold against gravity, and kP=0.01k_P = 0.01 power per degree. A proportional controller only produces 0.2 power when the error is 0.2/0.01=20°0.2 / 0.01 = 20°. So the arm settles 20° low and stays there. Doubling kPk_P 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.

LoopMeasured angleError eeError added up, ∑e Δt\sum e\,\Delta tChange in angle per second
170°20°0.40 °·s—
272°18°0.76 °·s+100 °/s
373.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: uP=kPeu_P = k_P e.

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, uI=kI∑e Δtu_I = k_I \sum e\,\Delta t, 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, ∫e dt\int e\,dt.

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: uD=−kD×(rate of change of the measurement)u_D = -k_D \times (\text{rate of change of the measurement}). In calculus the rate of change is the derivative.

Put together:

u=kP e+kI∫e dt−kDdmdtu = k_P\,e + k_I \int e\,dt - k_D \frac{dm}{dt}

where mm is the measurement. You'll also see the D term written as +kD de/dt+k_D\,de/dt, 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.

Idea
A mass on a spring
  • 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 mm the boundary between overshooting and not is kD=2mkPk_D = 2\sqrt{m k_P}. 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.

Live demoPID altitude hold — drag the target!
Drag inside this box, or focus it and use the up/down arrow keys, to move the target altitude.
TargetAltitude
P term
0
I term
0
D term
0
ChallengeFire a wind gust, then be back within ±0.10 m of the target within 3.5 s (hold it for half a second). Try it with each preset.not yet
Altitude: —Target: —Error: —
Idea
Three things to try
  1. P only. The drone settles below the target. Without an integral term, it can only produce the thrust to fight gravity by staying low.
  2. 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.
  3. 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 kPk_P until the mechanism just starts to oscillate, then back off a bit. Add kDk_D to damp the overshoot. Add kIk_I 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.

SymptomLikely causeTry
Slow to respondkP too lowraise kP
Overshoots and oscillateskP too high or kD too lowlower kP, raise kD
Stops short of the targetno kI, or missing feedforwardadd feedforward, then a little kI
Slow, wide oscillationkI too highlower kI
Big overshoot after a long move at full powerintegral windupadd anti-windup (next lesson)
Jittery, twitchykD too high for the noiselower 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 Δt\Delta t, as in From Math to a Loop:

uk=kPek+kI∑jejΔtj−kDmk−mk−1Δtu_k = k_P e_k + k_I \sum_{j} e_j \Delta t_j - k_D \frac{m_k - m_{k-1}}{\Delta t}
FTCPID for an arm, derivative on the measurement
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 500/0.02=25,000500 / 0.02 = 25{,}000 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.

ExerciseWhat an output of 3.7 means

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 RUN_WITHOUT_ENCODER rather than a mode that treats the command as a velocity or position request?

Show solution

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_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.

Tip
Filter the velocity, not the position

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 kGk_G from the feedforward lesson. On a slide it really is one constant. On an arm the hold changes with cos⁡θ\cos\theta, so for an arm that sweeps a wide range, use kGcos⁡θk_G\cos\theta instead and keep the rest.
  • L: a small push in the direction of the error, just enough to overcome friction. This is kSk_S. 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.
u=kP e−kD m˙filtered+kF+kL sign⁡(e)u = k_P\,e - k_D\,\dot m_\text{filtered} + k_F + k_L\,\operatorname{sign}(e)

with the kLk_L term only applied outside the dead zone.

Idea
Measuring F and L

Slowly raise the power by hand until the mechanism just starts to move up. Call that uupu_\text{up}. Then lower the power until it just starts to creep down, and call that udownu_\text{down}. Going up, the motor fights gravity and friction, so uup=kF+kLu_\text{up} = k_F + k_L. Going down, gravity helps and friction still resists, so udown=kF−kLu_\text{down} = k_F - k_L. Solving:

kF=uup+udown2,kL=uup−udown2.k_F = \frac{u_\text{up} + u_\text{down}}{2}, \qquad k_L = \frac{u_\text{up} - u_\text{down}}{2}.

For example, if it starts moving up at 0.26 and creeps down at 0.14, then kF=0.20k_F = 0.20 and kL=0.06k_L = 0.06. There's no single power that "holds it still," because friction lets it hold anywhere between those two readings.

PDFL: Improving Upon PID -

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
FTCPDFL: P, filtered D, constant F, static-friction L
// 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;
}
ExerciseHow much jitter the filter removes

The encoder jitters by one tick. At 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

One tick in 20 ms is 50 ticks per second of velocity that isn't real, multiplied by 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, e−dt/τe^{-dt/\tau} shrinks toward zero and alpha goes to 1, which means "so much time has passed, just use the new value."

ExerciseWhy L turns off near the target

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 2kL2k_L 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 kFk_F holding the load and kLk_L 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.

Sources & references
  • 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.