Tuning PID controllers

Tuning PID controllers

How to tune the PID controllers of the autopilot for stable flight across the simulated airplanes of all kinds, from speedy fighter jet, inert commercial airliner all the way to light propeller aircraft?

For a while, I’ve been extending GeoFS, a browser based flight simulator. I am now able to write programs to fly the airplanes in the simulator. Good fun, and very educational, too. Naturally, I wanted to program my own autopilot to steer the airplane. I built the autopilot on top of a set of PID controllers.

P for Proportional. I for Integral. D for Derivative. How does a PID controller work? How to build some intuition? How to find the right parameter values for the PID gains such that the airplane doesn’t oscillate or even become unstable and stall? Well, one thing after the other.

What is a PID controller? There are plenty of resources available. Just, for context, here’s the basic PID controller, let’s say for controlling the vertical speed of the airplane. The controller output $u$ might be sent to the elevator, and error $e$ the measured difference between the desired vertical speed setpoint $r$ and the measured vertical speed $y$.

$$\begin{aligned} u(t) = K_p e(t) + K_i \int_{0}^{t}e(\tau)\,\mathrm{d}\tau + K_d \frac{\mathrm{d}e(t)}{\mathrm{d}t} \end{aligned} $$

However, in the context of a simulation on the computer, everything is discrete. So for $k > 0$ and timesteps $\Delta t_k = t_k - t_{k-1}$ (at framerate, between 30-60 fps) and some appropriate initial conditions, we can use a discrete form of the PID controller, which can then be turned into a program.

$$\begin{aligned} u_{k} = K_p e_k + K_i \sum_{j=0}^{k}e_j\Delta t_j + K_d \frac{e_k - e_{k-1}}{\Delta t_k} \end{aligned} $$

The first controller in the autopilot makes the airplane reach and keep a certain set airspeed by varying thrust (“speed on thrust”). If the airplane goes too fast, decrease the throttle. If too slow, increase the throttle. The basic idea really is not complicated at all.

Another controller I built to keep a certain vertical speed by moving the elevator (“vertical speed on elevator”). Things are getting more interesting by the minute. Now we have two controllers that can each affect both airspeed and vertical speed. The total energy of the airplane is kinetic and potential energy combined. Pitching up trades kinetic energy for potential energy. Pitching down trades potential energy for kinetic energy. Adding thrust increases total energy. Typically, adding thrust also wants to make the airplane pitch up, particularly when the engines are mounted underneath the wings. If poorly tuned, these two PID controllers can get into an escalating cycle of pitching up, pitching down, and adding/removing thrust at just the wrong moments. Something to watch out for.

I also added a controller for making the airplane roll by deflecting the ailerons. Finally, I added a controller for yaw by moving the rudder. For yaw, I built one controller for yaw damping—even though I did not notice any visible tendencies of Dutch roll in the simulator; I don’t know how realistic it is, and I cannot judge either. I also added another controller to keep turns coordinated so that the airplane does not sideslip during the turn. It was inspired by Boeing’s SMYD (more the “YD” part, presumably), but my cursory research was not conclusive: at least not to the point where I could say “oh, let me implement this the same way”. In any case, the system I am experimenting with looks a bit like this:

turn coordinator <- K * roll rate + pid control output
rudder input <- manual pedal + yaw damper + turn coordinator

The yaw damper P-controller output acts on bandpass-filtered sideslip (controlling sideslip at higher frequencies), a proportional feed-forward term on roll rate linking aileron input to rudder input (to anticipate adverse yaw; some magic constant K), and the PID controller to keep the turn coordinated (controlling sustained sideslip at lower frequencies). For many of the aircraft, this ended up working reasonably well. At the same time, I am wondering what would happen if I added a feed-forward term on bank angle…

Altogether, there is now a set of five PID controllers: two affecting pitch (speed on thrust, vertical speed on elevator), one affecting roll (roll angle via ailerons), and two affecting yaw (yaw damper, turn coordinator).

PID controller plots
Telemetry coming from the five PID controllers for an already tuned aircraft. The P-term is in red, the I-term in blue, the D-term in green. Towards the right, the autopilot followed a setpoint change for the heading.

I wanted to control the following ten aircraft on GeoFS: A350-900, A380-800, B737-700, B777-300ER, Concorde, Dassault Rafale, Cessna 172S, Zlín Z-50, Pilatus PC-7 Mk.II, and the Piper Cub. A wide range with very different flight characteristics, more or less closely modelled after their real counterparts (I won’t be able to judge). That’s up to 150 parameters to tune (some controllers don’t have $K_i$ or $K_d$ terms by design)… Hours of fun?

From experience, it’s always good to tune parameters by hand first, and build some intuition, if possible. What happens if I double the proportional gain of the controller of vertical speed on elevator? Oops, now the airplane starts violently pitching up and down, and it diverges from the setpoint rather than settling on it. What happens if I drastically increase the integral gain of the roll angle controller? Oops, it overshoots and I’m getting bank angle warnings.

Once some basic intuition is in place, I’d rather move on and explore how to automatically find suitable PID gains across all ten airplanes and their respective five PID controllers each. Fortunately, flight tests in a browser simulator are cheap, and if I found a way to pick $K_p$, $K_i$, and $K_d$ quickly (semi-automatically), then solving the problem should become tractable for a hobbyist.

[roll_angle_pid]
# optimized on 2026-11-21 from study 174 trial 17 (ITAE = 0.1229)
# http://127.0.0.1:8080/dashboard/studies/174/trials?numbers=17
kp = 0.21671552579797518
ki = 0.00029983101074664535
kd = 0.001030476042014631
min = -1.0
max = 1.0

A .toml file containing the best PID gains found for the roll angle controller for a specific aircraft.

I built a test card for each controller, instructing the autopilot to perform a certain maneuver such as increasing the roll angle from 0° to 20°, hold, and then return to 0°. A cost function would then score how well/poorly the autopilot did on this maneuver. Finally an optimization loop picks the PID gains for the roll angle controller (in this example) that achieved the lowest cost. This all sounded easier at first to build than it turned out to be.

Well, at least the “genie” (thanks, Kent Beck, for either coining or popularizing this term) helped me to rapidly plumb the experiment pipeline together. An HTTP server running the optimizer (Optuna) piping the next set of PID gains to the browser, a wish granted. A couple of scripts to select the best PID gains after a study completes, a wish granted. A little panel in the browser to select what airplanes and which test cards to run, another wish granted. I can focus on building the test card, designing the cost function, and learning more about these things instead. Thanks, genie.

Optuna dashboard
This Optuna dashboard shows the 35 trials run to find good PID gains for the vertical speed on elevator controller of the B777-300ER.

The part of designing test cards, and choosing appropriate cost functions was harder than I had expected. I began with the integral of time-weighted absolute error (ITAE), which penalizes error late during the measured period of time. For example, I built a test card that instructed the autopilot to keep the B777 level first, then climb at a rate of 1500 feet/minute. If the vertical speed oscillates long after the airplane should have settled, the ITAE should pick it up and penalize the choice of PID gains of the vertical speed on elevator controller, which is optimized using this test card.

$$ \mathrm{ITAE} = \sum_{k=a}^{b} t_k |e_k| \Delta t_k $$

The test card for the speed on thrust controller instructed the autopilot to perform a double step. Increase the airspeed by 10 knots, hold it, then decrease it by 10 knots (at least for jets). The test card also instructed the autopilot to keep level flight, so that a change in thrust manifests in airspeed, not in climb rate.

The test card for the vertical speed on elevator similarly instructed the autopilot to keep a constant airspeed throughout. The autopilot is instructed to fly level first, then a setpoint change to a vertical speed of 1500 feet/min (depending on airplane; the Cessna cannot climb as fast as the B737 or the Rafale).

The test card for the yaw damper first deflected the rudder left and right, thus giving the airplane a kick before instructing the autopilot to dampen the induced swinging motion around the yaw axis.

The test card for the roll angle I already described. The PID controller for the roll angle actually controls the inner loop in my autopilot program. An outer loop uses fuzzy control to make the airplane change heading. I followed advice to tune inner loops first, and hence ended up with a test card with two setpoint changes on roll angle.

The last test card was about coordinated turns. I learnt a lot when designing this test card. The mechanisms of turning an airplane around are pretty intriguing. First, roll and counter adverse yaw into the turn. Then, keep the turn coordinated by applying enough rudder to avoid sideslip (“to keep the ball centered”).

Sideslip indicator
Sideslip indicator in the Cessna 172 in GeoFS. My PID controller doesn't eliminate the sideslip entirely. This suggests that there is room for improvement in the turn coordinator subsystem.

Once experimenting, soon I found the results across the test cards somewhat unsatisfying, occasionally far worse than my hand selected PID gains. Pure ITAE didn’t work well enough across the test cards. I ended up with a weighted sum instead, penalising overshoot, oscillation, saturation, and control chatter (a lot of movement of the control input to the control surfaces) in addition to the ITAE. I chose the weights to fit the desired characteristics for the particular maneuver performed during a test.

An airplane cannot and should not instantaneously roll from 0° to 20°. Yet, the ITAE term in my earlier versions of the cost function asked the autopilot to achieve the impossible. Instead, I designed the desired trajectory for the roll angle to be smoother, using a raised cosine. Then, I could track ITAE against this smooth trajectory, rather than the abrupt step function.

// The reference trajectory increases the roll angle from zero to
// ROLL_ANGLE_STEP_DEGREES within a specified period of time.
const ref = useHalfCosineStep({
  x0: measuringCostStart, // ms
  y0: 0, // degrees
  x1: measuringCostStart + 5000, // ms
  y1: ROLL_ANGLE_STEP_DEGREES, // degrees
})
const actual = this.getSeries.execute('roll_angle') ?? Series.empty()
const halfCosineStepError = Series.map(actual, (rollAngle) => ({
  time: rollAngle.time,
  value: ref(rollAngle.time) - rollAngle.value,
}))

The entire process took about two weeks (calendar time, this is certainly not my full-time job), starting and sequencing studies of typically 15-25 trials per aircraft and test card (a trial lasting usually 60s), iterating over test card, cost function, and also improving the controller design.

Mojave desert
Test scenario in the Mojave desert. About 5 knots of wind, mild turbulences, but otherwise relatively calm conditions.

Preventing the so-called derivative kick was the most important change to the PID controller logic itself. This is well-studied. I opted for a combination of derivative-over-measurement and a low-pass filter to reduce the effect of noise in the measurements. What’s the derivative kick? When the setpoint of a controller abruptly changes, the derivative term in the PID output spikes briefly, and yanks the airplane around in a way that is quite visible in the simulator. It’s also visible in the little plots I use to visualise the P,I,D terms over time. Time to take the kick out of the derivative by modifying the original PID controller (the additional low-pass filter is omitted in the equation below):

$$ K_d \frac{e_k - e_{k-1}}{\Delta t_k} \qquad\textrm{is replaced by}\qquad K_d \frac{y_k - y_{k-1}}{\Delta t_k} $$

Taking the derivative between two consecutive measurements does not respond to steep setpoint changes, yet maintains some of the desired damping effect.

// Calculate the derivative term using derivative on measurement, fed
// through a low-pass filter. In the very first step, the derivative
// remains zero, and thus does not contribute to the control output.
let d = this.d
if (dt > 0 && this.y !== null) {
  const dRaw = (-kd * (y - this.y)) / dt
  d = lowPass(dRaw, this.d, dt, this.derivativeFilterTau)
}

Above code snippet provides a glimpse into the internals of the PID controller implementation, showing the lines where the derivative-on-measurement is calculated, and fed through a low-pass filter.

As the derivative term is said to be sensitive to noise, I also added a low-pass filter to both measurement and the derivative term each. It’s been a while since my signal processing course at KTH, Stockholm (happy memories).

The B777-300ER with tuned PID controllers performs a turn. The setpoint change in heading is fed through an fuzzy outer-loop controller into the roll angle controller. The turn coordinator is running at all times, and adds some rudder during the turn.

What are the results? To my surprise, the whole process wasn’t only harder than expected, it also led to far better outcomes than expected, too.

  • The autopilot handles the Cessna gently, keeping it nice and level, at the desired airspeeds, rolling swiftly into and out of turns, making it to new headings, changing climb rate as desired.

  • The Rafale, with its massive excess thrust accelerates quickly to the desired new airspeed without ending up in phugoid motion.

  • The A380 with its inertia needs a different combination of PID gains than the Rafale or the Cessna. Yet the autopilot gets it smoothly onto a new heading, as well.

  • The B737 has a wonky entrance into a turn, something’s not working as well with the turn coordinator as it could. On an ILS approach, the autopilot keeps the glide slope and stays on the extended runway centerline, although it had already been able to do so with the hand tuned PID parameters. The changed gains for the vertical speed controller, however, invalidate the hardcoded timing of the flare in the autoland system: the B737 now floats down the runway for longer than usual before touchdown: maybe it’s time for optimising autoland with a dedicated test card, as well as controller improvements.

  • The Piper Cub is handled well, although enters bad oscillations in overspeed conditions. Control surfaces are more effective at higher speeds, and here, overspeed pushes the controller into unstable territory. With gain scheduling, this might be avoidable: smaller control outputs at higher airspeeds, larger outputs at lower airspeeds. Options for the future.

Building and tuning these PID controllers has been a great source of pleasure: the flight simulator provides immediate visible feedback; I was able to put some long-forgotten signal processing theory into practice; the genie took away the parts that I did not want to spend as much time on; decent amounts of struggle along the way, and the outcomes exceeded my own expectations.