Flight control: PID, cascades, filters and loops · 5 MIN READ
PID altitude control: P, I and D on the collective thrust
Close an altitude loop through SetThrust with a PID controller that takes its derivative from the measurement, clamps its integral and saturates its output, and judge each variant by rise time, overshoot, settling time and steady-state error.
SetThrust hands the program the collective thrust: about 0.5 hovers, more climbs, less sinks, and nothing else holds the altitude. Thrust sets vertical acceleration while you care about position, so the plant is a double integrator with a little drag, the simplest plant on which a naive controller rings. This lesson builds the PID found in every flight stack's inner loops, flies four variants of it through the same 10 m step on identical simulators, and measures what each term buys.
drones · A MAP OF THE IDEA
- Feedforward hover thrust
- P on altitude error
- I clamped, frozen at limit
- D from climb rate
Useful when
- Three gains cover most single-axis loops on a multicopter.
- Each term maps to a measurable symptom: offset, ringing, overshoot.
Watch out
- An integral without clamping turns saturation into overshoot.
- D differentiates noise; feed it a filtered rate, not raw altitude.
Implementation & operation cost: A few lines of code and a tuning session per airframe, repeated whenever mass, propellers or battery change.
Three terms, three jobs
In this simulator the vertical motion in manual thrust is z'' = 2g(u - 0.5) - 0.3 z': thrust u above 0.5 accelerates upward, below 0.5 downward, and a weak drag is the only damping. The proportional term pushes in proportion to the present error, which on a double integrator acts like a spring with almost no damper, so P alone overshoots and rings. A feedforward bias, the controller's estimate of hover thrust, does most of the holding; when that estimate is wrong (a payload, a sagging battery, a different propeller) a P-only loop needs a standing error to make up the difference, (true hover - bias) / Kp. The integral term accumulates past error until it supplies that missing thrust. The derivative term opposes the rate of change, adding the damping the plant lacks. Each term has a symptom you can measure: offset without I, ringing without D, overshoot when I is allowed to wind up.
Four controllers, one step
The program climbs to 5 m on the autopilot, waits 2 s, then hands thrust to a controller and commands 15 m for 40 s at 50 Hz. Every controller uses a hover guess of 0.45 while the true hover thrust is 0.50, and reads the true altitude so that only the controller differs (the next lessons replace it with an estimate). Rise time is the time from 10% to 90% of the step, overshoot is the peak beyond 15 m as a share of the 10 m step, settling time is the last moment the altitude was outside a band of 2% of the step (0.2 m), mean err and ripple cover the last 10 s, and sat is the share of steps with thrust at 0 or 1. The PID flight is landed and saved for the replay.
package main
// PID altitude control: the program owns the collective thrust and must
// climb from 5 m to 15 m and stay there. Four controllers fly the same
// step on identical simulators; the PID flight is saved for the replay.
import (
"fmt"
"math"
"gopherforge.app/drone"
)
// PID computes a thrust command from an altitude error.
type PID struct {
Kp, Ki, Kd float64
Bias float64 // feedforward: our estimate of hover thrust
Min, Max float64 // actuator limits
IMax float64 // limit on the integral's contribution
AntiWindup bool // clamp the integral and freeze it while saturated
integral float64
prevMeas float64
primed bool
}
// Update runs one control step. The derivative acts on the measurement,
// not on the error, so a setpoint change does not kick the output.
func (c *PID) Update(setpoint, meas, dt float64) float64 {
err := setpoint - meas
deriv := 0.0
if c.primed {
deriv = -(meas - c.prevMeas) / dt
}
c.prevMeas, c.primed = meas, true
candidate := c.integral + c.Ki*err*dt
raw := c.Bias + c.Kp*err + candidate + c.Kd*deriv
out := clamp(raw, c.Min, c.Max)
pushingPastLimit := raw != out && (raw > out) == (err > 0)
if !c.AntiWindup || !pushingPastLimit {
c.integral = candidate
}
if c.AntiWindup {
c.integral = clamp(c.integral, -c.IMax, c.IMax)
}
return out
}
type metrics struct {
rise, overshoot, settle float64
settled bool
meanErr, ripple, sat float64
}
const start, goal, window = 5.0, 15.0, 40.0
// fly climbs to 5 m on the autopilot, then hands thrust to the controller
// for a 10 m step and measures the response on the true altitude.
func fly(name string, c *PID) (metrics, *drone.Sim) {
sim := drone.New(drone.Config{Seed: 1})
d := sim.Drone()
d.Arm()
d.TakeOff(start)
sim.RunUntil(30, func(float64) bool { return d.State().Mode == drone.Hold })
sim.Run(2, nil)
sim.Mark(name + ": step to 15 m")
step := goal - start
t0 := sim.Time()
var t10, t90, lastOut, sum float64
peak, lo, hi := start, math.Inf(1), math.Inf(-1)
var n, satSteps, steps int
sim.Run(window, func(t float64) {
z := d.State().Pos.Z
u := c.Update(goal, z, sim.Dt())
d.SetThrust(u)
el := t - t0
if t10 == 0 && z >= start+0.1*step {
t10 = el
}
if t90 == 0 && z >= start+0.9*step {
t90 = el
}
peak = math.Max(peak, z)
if math.Abs(goal-z) > 0.02*step {
lastOut = el
}
if el >= window-10 {
sum += goal - z
lo, hi = math.Min(lo, z), math.Max(hi, z)
n++
}
if u == c.Min || u == c.Max {
satSteps++
}
steps++
})
return metrics{
rise: t90 - t10,
overshoot: math.Max(0, peak-goal) / step * 100,
settle: lastOut,
settled: lastOut < window-10,
meanErr: sum / float64(n),
ripple: hi - lo,
sat: float64(satSteps) / float64(steps) * 100,
}, sim
}
func main() {
gains := func(kp, ki, kd float64, antiWindup bool) *PID {
return &PID{Kp: kp, Ki: ki, Kd: kd, Bias: 0.45, Min: 0, Max: 1, IMax: 0.1, AntiWindup: antiWindup}
}
runs := []struct {
name string
c *PID
}{
{"P", gains(0.10, 0, 0, true)},
{"PI", gains(0.10, 0.03, 0, true)},
{"PID", gains(0.10, 0.03, 0.12, true)},
{"PID no anti-windup", gains(0.10, 0.03, 0.12, false)},
}
fmt.Println("step 5 m -> 15 m, hover guess 0.45 (true hover 0.50), 50 Hz")
fmt.Printf("%-19s %6s %9s %8s %9s %7s %5s\n", "controller", "rise", "overshoot", "settle", "mean err", "ripple", "sat")
var keep *drone.Sim
for _, r := range runs {
m, sim := fly(r.name, r.c)
settle := "never"
if m.settled {
settle = fmt.Sprintf("%.1f s", m.settle)
}
fmt.Printf("%-19s %4.1f s %8.0f%% %8s %7.2f m %5.2f m %4.0f%%\n",
r.name, m.rise, m.overshoot, settle, m.meanErr, m.ripple, m.sat)
if r.name == "PID" {
keep = sim
}
}
d := keep.Drone()
d.Land()
keep.RunUntil(60, func(float64) bool { return d.State().Landed })
keep.Save()
}
func clamp(v, lo, hi float64) float64 { return math.Max(lo, math.Min(hi, v)) }P rises fastest (1.0 s) but overshoots 55%, never enters the 0.2 m band and settles at a mean error of 0.50 m, exactly (0.50 - 0.45) / 0.10. PI removes that offset on average but adds lag to a loop that had almost no damping: 60% overshoot and a ripple of 7.25 m still swinging after 30 s. PID rises in 2.0 s with 4% overshoot, settles in 7.7 s and ends at 0.00 m error. The same gains without anti-windup reach 25% overshoot and settle in 9.5 s, because the integral grew during the climb and had to unwind past the target. The last line is the saved PID flight: landed, battery 90%.
Derivative on measurement, not on error
Because error = setpoint - measurement, its derivative equals minus the measurement's derivative whenever the setpoint is constant. The two differ only when the setpoint changes: a 10 m step differentiated over one 0.02 s sample is 500 m/s, which times Kd = 0.12 asks for a thrust of 60 for one step, a derivative kick that slams the motors. Taking D from the measurement keeps all the damping and drops the kick. The derivative also amplifies noise: differencing a barometer with 0.3 m of noise at 50 Hz gives a rate noise of about 21 m/s. Real controllers therefore take the rate from the estimator (or the gyro, for the rate loop) and low-pass filter the D path, as PX4 does in its rate controller.
// Derivative on error: kicks when the setpoint jumps.
dErr := (err - c.prevErr) / dt
// Derivative on measurement: equal while the setpoint is constant,
// and no kick when it changes.
dMeas := -(meas - c.prevMeas) / dt
// Better: the estimator's climb rate, low-pass filtered (tauD seconds).
c.dFilt += (-climbRate - c.dFilt) * dt / (tauD + dt)
d := c.Kd * c.dFiltThe first form differentiates the setpoint too. The second is what the program's Update method does. The third avoids differencing a noisy altitude at all: an estimator already provides the climb rate, and a first-order low-pass with time constant tauD trims what noise remains before the gain multiplies it.
Windup, clamping and saturation
Thrust is limited to 0..1, so for part of a large step the controller asks for more than the motors can give. An integral that keeps accumulating during that time stores error the plant could never act on, and it must be paid back as overshoot after the target is reached. The program uses two common defences together: it clamps the integral's contribution to 0.1 of thrust (twice the expected hover error), and it freezes integration while the output is saturated in the direction the error pushes. Back-calculation, which bleeds the integral by the amount the output was clipped, is a third. Also reset or preload the integral when a mode hands control to the loop, so the first output continues the previous thrust instead of jumping, and saturate the output yourself rather than trusting the next layer to do it.
Fly it in GopherForge
Create the project with New project > Robotics and simulation > Drone flight, replace main.go with this lesson's program (mission.go can stay; this program does not use it) and tap Run. The table appears in the console; open Output to watch the replay of the PID flight: the take-off to 5 m, the marked step to 15 m with its small overshoot in the altitude strip, and the landing. Then change the gains in main, for example Kd to 0 or AntiWindup to false, and compare the tables and replays.
TAKE THIS WITH YOU
On a thrust-to-altitude loop, P alone leaves an offset and rings, I removes the offset but adds lag, and D supplies the damping. Take D from the measurement, clamp the integral and freeze it while the output saturates, and judge a tune by rise time, overshoot, settling time and steady-state error.
Check your understanding
Why do flight controllers usually compute the PID derivative term from the measured altitude instead of from the error?
Go to the source
Progress stays in this browser. No account needed.