PID controller explained

Closed-loop feedback diagram of a PID controller: setpoint minus measured angle gives the error e; three terms P = Kp·e, I = Ki·∫e dt, D = −Kd·dy/dt sum to the command u; a saturation block limits u before the actuator; the body rotates with its inertia; an IMU measures the angle and feeds it back to the comparison point
Download SVG
Embed

Copy this HTML to use the diagram on your site (CC BY 4.0, keep the credit line):

<figure><img src="https://cosmicaxis.space/img/pid-controller-en.svg" alt="Closed-loop feedback diagram of a PID controller: setpoint minus measured angle gives the error e; three terms P = Kp·e, I = Ki·∫e dt, D = −Kd·dy/dt sum to the command u; a saturation block limits u before the actuator; the body rotates with its inertia; an IMU measures the angle and feeds it back to the comparison point" width="600" height="500"><figcaption>Source: <a href="https://cosmicaxis.space/en/pid-controller/">CosmicAxis</a> · CC BY 4.0 · Based on: Åström and Murray, Feedback Systems (2020), figures 11.1 and 11.11</figcaption></figure>
Source

Åström and Murray, Feedback Systems (2020), figures 11.1 and 11.11

A PID (proportional–integral–derivative) controller computes a command from the error between setpoint and measurement: P acts on the present error, I on the accumulated error, D on the rate of change of the error. A survey of more than 11,000 industrial controllers found 97% use PID (Åström and Murray, 2020).

01Knowledge

What is a PID controller and how does closed-loop feedback work?

A PID controller is an algorithm inside a closed-loop feedback system: it measures the quantity to hold, compares it with the setpoint, and computes an actuator command that drives the error to zero. Åström and Murray (chapter 11) cite a survey by Desborough and Miller (2002): 97% of more than 11,000 controllers in refining, chemicals and paper use PID.

In the pitch-hold loop of the cover image, an IMU measures the angle y, the computer forms the error e = r − y (r is the setpoint angle), the PID computes the command u, and a motor or gimbaled nozzle turns u into torque. A closed loop corrects disturbances it did not predict, such as wind or an off-center mass, but can oscillate if it reacts too hard or too late. PID is the control block of the guidance, navigation and control (GNC) loop in avionics, navigation and flight software.

What do the P, I and D terms of a PID controller each do?

The PID command is the sum of three terms: u(t) = Kp · e(t) + Ki · ∫e dt + Kd · de/dt. According to Åström and Murray, P looks at the present error, I at the past error, and D at the coming error through linear extrapolation.

  • P (proportional): a large error gets a strong push; a large Kp speeds up the response but adds oscillation.
  • I (integral): I accumulates while any error remains, so it removes the steady-state error from a constant disturbance such as an off-center mass, at the price of more overshoot.
  • D (derivative): when the angle closes fast on the target, D brakes early, like a damper. D amplifies noise, so it needs a low-pass filter.

In industry D is often off because temperature and pressure change slowly: in a survey of more than 100 boiler–turbine units in Guangdong, 94.4% of controllers were PI (Åström and Murray, 2020). A drone’s tilt, a rocket or a satellite attitude axis has almost no friction, so D is essential.

What are overshoot, settling time and steady-state error?

Overshoot, settling time and steady-state error grade a PID controller on a step response: change the setpoint abruptly, for example from 0° to 10°, and record the measurement (Åström and Murray, section 6.3).

Step response to 10° of a one-axis test rig over 2 seconds: the PID curve rises to 10.64° (6% overshoot) and enters the ±2% band around 10° after 0.74 s; the PD curve stops at 7.76°, a 2.24° steady-state error caused by an offset torque
Source

CosmicAxis own calculation by the Python simulation in the article; definitions after Åström and Murray, section 6.3

  • Overshoot (Mp): the percentage by which the measurement exceeds the final value at its first peak.
  • Settling time (Ts): the time to enter and stay inside a ±2% band around the final value (some texts use 1% or 5%).
  • Steady-state error: setpoint minus measurement once oscillation has died out.

In the plot, the PD controller stops at 7.76° because a 0.05 N·m offset torque pulls the angle down: error = offset torque / Kp = 0.05 / 1.28 rad = 2.24°. With the I term, the angle reaches exactly 10° after 0.74 s, at the cost of 6% overshoot.

How do you tune a PID controller with Ziegler–Nichols?

The Ziegler–Nichols method (1942) tunes a PID with one experiment: switch off I and D, raise Kp until the system oscillates steadily, record the critical gain kc and period Tc, then read the table. Table 11.1 of Åström and Murray (frequency-response method) gives:

Controller Kp Ti (= Kp/Ki) Td (= Kd/Kp) Source, accessed
P 0.5 kc — — Åström–Murray, 2026-10-02
PI 0.45 kc Tc/1.2 — Åström–Murray, 2026-10-02
PID 0.6 kc Tc/2 Tc/8 Åström–Murray, 2026-10-02

Åström and Murray name two drawbacks: too little process information is used, and the closed loop is not very robust.

For an axis with only inertia the experiment fails: pure P plus motor lag oscillates with growing amplitude at every Kp, so no kc exists (CosmicAxis own calculation). Pole placement suits better: for natural frequency ωn and damping ratio ζ, Kp = J · ωn² and Kd = 2 · ζ · ωn · J, with J the moment of inertia. The test rig, J = 0.02 kg·m², ωn = 8 rad/s, ζ = 0.7, gives Kp = 1.28 N·m/rad and Kd ≈ 0.22 N·m·s/rad; then add a small Ki.

What are actuator saturation and anti-windup?

Saturation is when the actuator is at its limit, such as a motor at maximum speed or a gimbal at its end stop. According to Åström and Murray (section 11.4), the loop is then effectively cut while the I term keeps accumulating error. This is integrator windup: the I term swells and must unwind after the error changes sign, causing large overshoot. Their example 11.5, a cruise control on a 6° slope, has the error back to zero at 25 s, yet the car settles only at 40 s. Sensor saturation is different: an IMU saturation flag held too long helped cause the loss of the Schiaparelli lander in 2016.

Two common anti-windup methods, both needing the true actuator limits:

  • Clamping: while the command is saturated and the error pushes it further out, stop adding to the I term.
  • Back-calculation: feed the saturated-minus-raw command back into the I term through a gain kaw, a few times Ki in the book.

How does a discrete PID run on a microcontroller?

A discrete PID runs on a computer at a fixed sampling period h: the integral becomes a sum and the derivative becomes the difference of two measurements divided by h. According to Åström and Murray (section 11.5), each cycle reads the sensor, outputs the command, then updates the state, to reduce delay. The book’s formulas, with k the sample index:

  • P term: P(k) = Kp · e(k).
  • I term: I(k+1) = I(k) + Ki · h · e(k), plus an anti-windup term.
  • Filtered D term, backward difference: D(k) = Tf/(Tf + h) · D(k−1) − Kd/(Tf + h) · (y(k) − y(k−1)), with Tf = Td/N and N between 5 and 20.

The D term differentiates the measurement y, not the error e: when the setpoint jumps, the derivative of the error becomes a large spike called derivative kick. The PX4 documentation puts the D term of the rate loop on the feedback path to avoid it.

The period h must be steady: Arduino’s delay() adds computation time, so h drifts with load and corrupts both I and D. A real flight computer runs the PID as a high-priority periodic task on an RTOS.

02Practice

How do you simulate PID tilt control in Python?

The simulation holds the tilt angle of a one-axis test rig (a seesaw bar with two propeller motors) and prints metrics for six parameter sets. The rig parameters are assumed; the results are CosmicAxis own calculation.

import math

J, LAG, U_MAX, BIAS = 0.02, 0.03, 0.5, 0.05   # kg·m², s, N·m, N·m (assumed)
H = 0.004                                     # s: 250 Hz PID loop

def run(kp, ki, kd, target, d_on_meas=True, anti_windup=True):
    r = math.radians(target)
    ang = w = m = I = e_old = ang_old = u_peak = 0.0
    y = []
    for _ in range(1500):                     # 6 s
        e = r - ang
        d = -(ang - ang_old) / H if d_on_meas else (e - e_old) / H
        u_raw = kp * e + I + kd * d
        u = max(-U_MAX, min(U_MAX, u_raw))    # saturation
        if not (anti_windup and u != u_raw and e * u_raw > 0):
            I += ki * e * H                   # clamping: stop integrating while saturated
        e_old, ang_old, u_peak = e, ang, max(u_peak, abs(u_raw))
        for _ in range(4):                    # plant simulated at 1 kHz
            m += (u - m) / LAG * H / 4
            w += (m - BIAS) / J * H / 4
            ang += w * H / 4
        y.append(math.degrees(ang))
    return y, u_peak

def metrics(y, target):
    if max(map(abs, y)) > 3 * target:
        return "growing oscillation", "—", "—"
    outside = [i for i, v in enumerate(y) if abs(v - target) > 0.02 * target]
    t_s = "—" if outside[-1] > 1450 else f"{(outside[-1] + 1) * H:.2f}"
    return f"{max(0, max(y) / target - 1) * 100:.0f}", t_s, f"{abs(target - y[-1]):.2f}"

for name, kp, ki, kd, target, dm, aw in [
        ("P", 1.28, 0, 0, 10, 1, 1), ("PD", 1.28, 0, 0.22, 10, 1, 1),
        ("PID, D on error", 1.28, 1.5, 0.22, 10, 0, 1),
        ("PID, D on measurement", 1.28, 1.5, 0.22, 10, 1, 1),
        ("PID 60°, no anti-windup", 1.28, 1.5, 0.22, 60, 1, 0),
        ("PID 60°, anti-windup", 1.28, 1.5, 0.22, 60, 1, 1)]:
    y, u_peak = run(kp, ki, kd, target, dm, aw)
    print(f"{name:24}", *metrics(y, target), f"{u_peak:.2f}", sep=" | ")

Output on Python 3.14.6; the columns are overshoot (%), 2% settling time (s), steady-state error (°) and peak raw command (N·m):

P                        | growing oscillation | — | — | 4.61
PD                       | 0 | — | 2.24 | 0.23
PID, D on error          | 5 | 0.70 | 0.00 | 9.82
PID, D on measurement    | 6 | 0.74 | 0.00 | 0.23
PID 60°, no anti-windup  | 29 | 2.19 | 0.00 | 1.36
PID 60°, anti-windup     | 12 | 1.42 | 0.00 | 1.34

Four lessons: pure P cannot hold a body with only inertia; PD sits 2.24° off because of the offset torque; D on the error demands 9.82 N·m in the first cycle, almost 20 times the limit, while D on the measurement needs 0.23 N·m; with a 60° step, clamping the I term cuts overshoot from 29% to 12%.

Raise LAG to 0.08 s and the same PID overshoots 25%, because delay eats the stability margin. On a real rig, remove the propellers when uploading code, clamp the rig, and take the angle from a Kalman filter or a complementary filter.

03Reality

How does the SLS rocket use PID to steer its nozzles?

The SLS rocket of the Artemis program holds attitude during ascent with a PID control law, according to NASA Marshall’s paper AAS 14-038 (Orr et al., 2014), because classical PID with filters and gain scheduling has flown successfully on large launch vehicles for more than 50 years.

  • P term: keeps the vehicle stable, since the rocket body is aerodynamically unstable.
  • I term: low gain, zero until just after the flyaway maneuver off the tower, and ramped to zero as the solid rocket boosters tail off; its input is scaled before integration to avoid windup.
  • D term: uses the filtered angular-rate error from gyros to damp the vehicle body and propellant slosh, as on the second flight of Falcon 1.

The command is angular acceleration (rad/s²), so the P and D gains tie directly to natural frequency and damping as in the pole placement above; a command allocator turns it into the deflection of each de Laval nozzle. The vehicle is long and flexible, so the bending filter must attenuate bending oscillation by at least 6 dB below the critical gain, and nominal margins must reach ±30° of phase and ±6 dB (table 1).

How did the Ingenuity helicopter survive on Mars thanks to its stability margins?

The Ingenuity helicopter survived its sixth flight because its control loop had wide stability margins, according to chief pilot Håvard Grip (NASA JPL, 27 May 2021). Its flight software is built on F´ (F Prime), JPL’s open-source flight software framework. Ingenuity estimates attitude and position from an IMU plus a navigation camera photographing the ground 30 times per second. Around second 54 one image was lost, so every later image carried a wrong timestamp; the estimator kept “correcting” errors that did not exist, and the helicopter rocked beyond 20° in roll and pitch with a surge in power. It still landed about 5 m from the planned point: the system was designed to tolerate large errors, including timing errors, and in the final phase the software stops using camera images, so the rocking ended.

The lesson: a control loop, PID or not, is only as good as its measurements. In the Ariane 5 flight 501 failure, the flight computer read diagnostic data as real attitude and swung the nozzles to full deflection. A crewed spacecraft project must test its control loops with delayed, missing and wrongly timestamped measurements.

04Milestone

Milestone: check yourself

If you can do all of these, move on to the next article in this phase.

  • Can you read overshoot, 2% settling time and steady-state error on a step-response plot?
  • Can you explain why a PD controller leaves a 2.24° error under an offset torque and a PID controller does not?
  • Can you write a discrete PID loop with the derivative on the measurement and integrator anti-windup?

Frequently asked questions

What does PID stand for?

PID stands for proportional–integral–derivative: three terms that act on the present error, the accumulated past error and the trend of the error.

Do you always need all three of P, I and D?

No. In a survey of more than 100 boiler–turbine units in Guangdong, 94.4% of controllers were PI and only 3.7% were PID (Åström and Murray, 2020). The D term pays off for bodies with inertia and little friction, such as a drone's tilt angle.

How does a drone use PID?

The PX4 flight stack nests loops: the innermost is three independent PID controllers holding roll, pitch and yaw rates; the outer attitude loop computes the rate needed (PX4 documentation).

References

  1. Åström and Murray — Feedback Systems, 2nd ed., v3.1.5 (2020), chapter 11 PID Control — accessed
  2. Åström and Murray — Feedback Systems, 2nd ed., v3.1.5 (2020), full text (section 6.3 step response) — accessed
  3. PX4 User Guide — Multicopter PID Tuning Guide — accessed
  4. Orr, Wall, VanZwieten and Hall — Space Launch System Ascent Flight Control Design, AAS 14-038 (2014) — accessed
  5. Grip — Surviving an In-Flight Anomaly: What Happened on Ingenuity's Sixth Flight, NASA (27 May 2021) — accessed

Cite this article

CosmicAxis. (2026). PID controller explained: P, I, D terms, tuning, example. https://cosmicaxis.space/en/pid-controller/