Skip to content
LumenaryAcademy
Signals 80 min

Feedback control

Measure, compare, correct. The closed loop in the frequency domain, PID control of a DC motor, root loci, stability margins, tuning rules and digital implementation.

Code tested · 6AI-draftedAwaiting review by an electrical engineer

Your guides: Chloe · The Physicist, Margaret · The Bench Engineer, Gideon · The Design Reviewer

MotivationH

Measure, compare, correct

Apply 6 V to a small DC motor and it spins at some speed, but which speed depends on the load on its shaft, the temperature of its windings and the state of the battery. If you need a particular speed, for a conveyor, a drone's propeller or a pump, setting the voltage and hoping (open-loop control) is not good enough. Instead, measure the speed, compare it with the speed you want, and adjust the voltage according to the difference. That is feedback, and it is one of the most powerful ideas in engineering: it makes systems accurate despite imprecise parts, fast despite sluggish physics, and steady despite disturbances.

You have already met feedback inside circuits. The operational amplifiers of Operational amplifiers owe their precise gains to it, and Feedback and oscillators showed its dark side: feedback with the wrong timing turns an amplifier into an oscillator. This lesson develops the classical, frequency-domain theory of feedback control using the tools of this level: transfer functions, poles, frequency responses and sampling. It works through one example throughout, the speed control of a small DC motor, simulated in Python. Lumenary Robotics' feedback and PID is the hands-on companion, applying these ideas to robot joints and wheels, and its state space and LQR continues where classical control stops.

DefinitionsH

Block diagrams and the closed loop

A block diagram draws a system as boxes (transfer functions) joined by arrows (signals), with circles where signals add. Three rules reduce any diagram of LTI blocks: blocks in series multiply (G1G2G_1G_2), blocks in parallel add (G1+G2G_1 + G_2), and a feedback loop, with GG forward and HH back, becomes G/(1+GH)G/(1 + GH).

reuC(s)controllerP(s)plantydn+−++measurement (sensor)
The standard feedback loop. The controller C compares the reference r with the measured output and drives the plant P; a disturbance d (such as a load torque) acts on the plant's input, and sensor noise n corrupts the measurement.

Read the diagram as equations: Y=P(U+D)Y = P(U + D) and U=C(R−Y−N)U = C(R - Y - N). Eliminating UU: Y=CP1+CP R+P1+CP D−CP1+CP N.Y = \frac{CP}{1 + CP}\,R + \frac{P}{1 + CP}\,D - \frac{CP}{1 + CP}\,N . The product L=CPL = CP around the loop is the loop gain (or loop transfer function), and two combinations of it govern everything:

Definition— Sensitivity and complementary sensitivity

The sensitivity function S=11+LS = \dfrac{1}{1 + L} and the complementary sensitivity function T=L1+LT = \dfrac{L}{1 + L}. The output tracks the reference through TT, the tracking error is E=R−Y=S RE = R - Y = S\,R (ignoring dd and nn), a disturbance reaches the output through SPSP, and sensor noise reaches it through −T-T. Always S+T=1S + T = 1.

At frequencies where the loop gain is large, ∣L∣≫1|L| \gg 1, S≈0S \approx 0 and T≈1T \approx 1: the output follows the reference, and disturbances are suppressed by the factor ∣S∣|S|. This is the magic of feedback, and it does not depend on knowing PP accurately: if ∣L∣=100|L| = 100, a 10% change in the plant changes the closed-loop response by only about 0.1%.

The poles of the closed loop are the roots of 1+L(s)=01 + L(s) = 0, the characteristic equation. Feedback moves the poles: that is how it can speed up a sluggish plant or damp an oscillating one, and also how it can destabilise a perfectly stable one.

Worked examplesH

Steady-state error and system type

How accurately does the loop follow a constant reference in the end? With the final-value theorem of The Laplace transform and stability (valid when the closed loop is stable), the error after a unit step R=1/sR = 1/s is ess=lim⁡s→0s⋅11+L(s)⋅1s=11+L(0).e_{ss} = \lim_{s\to 0} s \cdot \frac{1}{1 + L(s)} \cdot \frac{1}{s} = \frac{1}{1 + L(0)} . If L(0)L(0) is finite, a step leaves a permanent error. If LL has a pole at s=0s = 0, an integrator, then L(0)=∞L(0) = \infty and the error vanishes.

Theorem— Steady-state error and system type

Let the type of a stable unity-feedback loop be the number of integrators (poles at s=0s = 0) in L(s)L(s). A type-0 loop follows a step with error 1/(1+Kp)1/(1 + K_p), where Kp=L(0)K_p = L(0), and cannot follow a ramp. A type-1 loop follows a step with zero error and a unit ramp with error 1/Kv1/K_v, where Kv=lim⁡s→0sL(s)K_v = \lim_{s\to0} sL(s). A type-2 loop follows steps and ramps with zero error.

Proof

For a reference with transform 1/sm+11/s^{m+1} (a step for m=0m = 0, a ramp for m=1m = 1), the final-value theorem gives ess=lim⁡s→0s⋅11+L(s)⋅1sm+1=lim⁡s→01sm+smL(s)e_{ss} = \lim_{s\to0} s\cdot\frac{1}{1 + L(s)}\cdot\frac{1}{s^{m+1}} = \lim_{s\to0}\frac{1}{s^m + s^m L(s)}. If LL has qq integrators, smL(s)s^m L(s) tends to a finite non-zero constant when q=mq = m, to infinity when q>mq > m (error 0), and to zero when q<mq < m (error infinite). For q=m=0q = m = 0 this gives 1/(1+L(0))1/(1 + L(0)), and for q=m=1q = m = 1 it gives 1/Kv1/K_v.

∎

The same reasoning shows that an integrator in the controller also removes the effect of a constant disturbance, a case of the internal model principle: to cancel a signal perfectly, the loop must contain a model of what generates it.

Now the plant. A small brushed DC motor driving a flywheel obeys two equations: the armature circuit L di/dt=v−Ri−KωL\,di/dt = v - Ri - K\omega (the back-EMF KωK\omega opposes the supply) and the mechanics J dω/dt=Ki−bω−τloadJ\,d\omega/dt = Ki - b\omega - \tau_{\text{load}} (the torque KiKi accelerates the inertia against friction and load). Taking Laplace transforms and eliminating the current gives the transfer function from voltage to speed, P(s)=Ω(s)V(s)=K(Js+b)(Ls+R)+K2.P(s) = \frac{\Omega(s)}{V(s)} = \frac{K}{(Js + b)(Ls + R) + K^2}. The values below are illustrative, typical of a motor a few centimetres long.

python
import numpy as np

# A small brushed DC motor driving a flywheel (illustrative values, not a particular product).
R, L, K = 1.2, 0.6e-3, 0.02     # armature resistance (ohm), inductance (H), motor constant (N m/A = V s/rad)
J, b = 2e-5, 1e-5               # inertia (kg m^2), viscous friction (N m s)

# Speed per volt: P(s) = K / ((J s + b)(L s + R) + K^2)
den = np.polyadd(np.polymul([J, b], [L, R]), [K * K])
poles = np.sort(np.roots(den).real)[::-1]
P0 = K / den[-1]
print("plant poles:", np.round(poles, 1), "1/s  ->  time constants",
      ", ".join(f"{-1e3 / p:.2f} ms" for p in poles))
print(f"DC gain P(0) = {P0:.2f} (rad/s)/V;  no-load speed at 12 V = {12 * P0:.0f} rad/s = {12 * P0 * 60 / (2 * np.pi):.0f} rpm")

# Proportional control, unity feedback: closed loop T = Kp P / (1 + Kp P).
print("\n   Kp     loop gain Kp P(0)   steady-state error   closed-loop poles (no delay)")
for Kp in (0.05, 0.24, 1.0, 5.0):
    cl_poles = np.roots(np.polyadd(den, [Kp * K]))          # 1 + Kp P = 0  <=>  den + Kp K = 0
    txt = ", ".join(f"{p.real:.0f}{p.imag:+.0f}j" if abs(p.imag) > 1 else f"{p.real:.0f}" for p in sorted(cl_poles, key=lambda q: -q.imag))
    print(f"{Kp:6.2f}   {Kp * P0:12.2f}        {100 / (1 + Kp * P0):8.2f} %          {txt}")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

The motor has two real poles: a slow mechanical one (time constant 57.8 ms, the inertia spinning up against the back-EMF) and a fast electrical one (0.50 ms, the inductance). Proportional control, C=KpC = K_p, gives a type-0 loop, so it always leaves an error: 29% of the reference with a gentle gain, 7.9% at Kp=0.24K_p = 0.24, 2% at Kp=1K_p = 1. Raising the gain shrinks the error and speeds up the loop, and in this idealised continuous-time model the closed-loop poles never leave the left half-plane; they merely become more oscillatory. The real, digital loop is less forgiving, as we shall see.

ComputationC

PID control of the motor, simulated

The PID controller adds two more terms to the proportional one: u(t)=Kp(e(t)+1Ti∫0te(τ) dτ+Td dedt),C(s)=Kp(1+1Tis+Tds).u(t) = K_p\left(e(t) + \frac{1}{T_i}\int_0^t e(\tau)\,d\tau + T_d\,\frac{de}{dt}\right), \qquad C(s) = K_p\left(1 + \frac{1}{T_i s} + T_d s\right). The proportional term reacts to the present error. The integral term accumulates past error and keeps pushing until it is zero, making the loop type 1. The derivative term reacts to the error's rate of change, adding damping and phase lead. TiT_i (the integral time) and TdT_d (the derivative time) set the strengths of the last two. In practice the derivative is applied to the measurement rather than the error (so a step in the reference does not produce a huge spike), and it is low-pass filtered (so it does not amplify sensor noise without limit).

A model-based design. Choose TiT_i equal to the motor's mechanical time constant, 57.8 ms. The controller's zero at s=−1/Tis = -1/T_i then cancels the slow motor pole, and the loop gain becomes approximately L(s)=KpP(0)/(Tis)L(s) = K_p P(0)/(T_i s), an integrator, whose gain crosses 1 at ωc=KpP(0)/Ti\omega_c = K_p P(0)/T_i. Choosing ωc=200\omega_c = 200 rad/s (about 32 Hz) gives Kp=0.238K_p = 0.238. A PID controller can cancel both motor poles (with Ti=58.3T_i = 58.3 ms and Td=0.50T_d = 0.50 ms) and push the crossover higher; we take Kp=0.42K_p = 0.42, for about 57 Hz, a choice the stability margins will justify later.

The simulation is digital, like a real controller: the motor is discretised exactly at 1 kHz with a zero-order hold, the controller computes a new voltage each millisecond and applies it at the next sample (the time to measure and compute), and the voltage is limited to the 12 V supply. A load torque is applied at t=0.3t = 0.3 s.

python
import numpy as np

R, L, K, J, b = 1.2, 0.6e-3, 0.02, 2e-5, 1e-5      # the motor from the previous program
T, V_MAX = 1e-3, 12.0                               # controller runs at 1 kHz; supply limit 12 V

# Exact discretisation of the motor over one sample period (input held constant: a zero-order hold).
# State x = [speed w, current i];  J w' = K i - b w - load,  L i' = v - R i - K w.
A = np.array([[-b / J, K / J], [-K / L, -R / L]])
M = np.zeros((4, 4))
M[:2, :2], M[:2, 2], M[:2, 3] = A, [0, 1 / L], [-1 / J, 0]
def expm(X):
    n = max(0, int(np.ceil(np.log2(np.abs(X).sum(axis=1).max() / 0.5))))
    S, term = np.eye(len(X)), np.eye(len(X))
    for k in range(1, 16):
        term = term @ (X / 2 ** n) / k
        S = S + term
    for _ in range(n):
        S = S @ S
    return S
Phi = expm(M * T)
Ad, Bd, Ed = Phi[:2, :2], Phi[:2, 2], Phi[:2, 3]
tau_m, tau_e = sorted(-1 / np.linalg.eigvals(A).real)[::-1]       # 57.8 ms and 0.50 ms

def run(Kp, Ti=None, Td=0.0, N=10, anti_windup=True, ref=10.0, load=0.5e-3, t_end=0.6):
    """Digital PID speed loop. Returns the speed and the applied voltage at each sample."""
    x, u_next, I, D, y_prev = np.zeros(2), 0.0, 0.0, 0.0, 0.0
    w_log, v_log = [], []
    for k in range(int(round(t_end / T))):
        y = x[0]                                          # measure the speed
        e = ref - y
        if Td > 0:                                        # filtered derivative of the measurement
            D = Td / (Td + N * T) * D - Kp * Td * N / (Td + N * T) * (y - y_prev)
        y_prev = y
        v = Kp * e + I + D
        u = min(max(v, -V_MAX), V_MAX)                    # the supply cannot exceed 12 V
        if Ti is not None and (not anti_windup or u == v or e * v < 0):
            I += Kp * T / Ti * e                          # integrate (clamped while saturated)
        w_log.append(y)
        v_log.append(u_next)
        torque = load if k * T >= 0.3 else 0.0            # a load is applied at t = 0.3 s
        x = Ad @ x + Bd * u_next + Ed * torque
        u_next = u                                        # one sample of computation delay
    return np.array(w_log), np.array(v_log)

def report(name, w, v, ref, disturbance=True):
    k0 = 300                                              # sample index of the load step
    pre = w[:k0]
    rise = (np.argmax(pre >= 0.9 * ref) - np.argmax(pre >= 0.1 * ref)) * T
    over = max(0.0, pre.max() / ref - 1) * 100
    late = np.nonzero(np.abs(pre - ref) > 0.02 * ref)[0]
    settle = f"{(late[-1] + 1) * T * 1e3:5.0f} ms" if late[-1] < k0 - 1 else "  never"
    line = f"{name:18} {rise * 1e3:3.0f} ms {over:7.1f} %  {settle}"
    if disturbance:
        err = [round(ref - pre[-1], 3) + 0.0, round(ref - w[k0:].min(), 3) + 0.0, round(ref - w[-1], 3) + 0.0]
        line += f"   {err[0]:+7.3f}    {err[1]:7.3f}   {err[2]:+7.3f}"
    print(line + f"    {np.abs(v).max():5.1f} V" if disturbance else line + f"   {np.abs(v).max():5.1f} V")

designs = {
    "P   (Kp 0.24)":  dict(Kp=0.24),
    "PI  (Kp 0.238)": dict(Kp=0.238, Ti=tau_m),
    "PID (Kp 0.42)":  dict(Kp=0.42, Ti=tau_m + tau_e, Td=tau_m * tau_e / (tau_m + tau_e)),
    "PID (Z-N)":      dict(Kp=0.638, Ti=3.89e-3, Td=0.97e-3),   # Ziegler-Nichols, from Ku and Tu (see below)
}
print("10 rad/s step at t = 0, 0.5 mN m load at t = 0.3 s (errors in rad/s)")
print("design            rise  overshoot   settle   error@0.3s  max drop  error@0.6s  peak volts")
for name, d in designs.items():
    report(name, *run(**d), ref=10.0)

print("\n300 rad/s step from rest: the supply saturates")
print("design            rise  overshoot   settle   peak volts")
for aw in (False, True):
    w, v = run(Kp=0.238, Ti=tau_m, anti_windup=aw, ref=300.0, load=0.0)
    report("PI, anti-windup" if aw else "PI, no anti-windup", w, v, ref=300.0, disturbance=False)

w, v = run(**designs["PI  (Kp 0.238)"])
print("\nPI response to the 10 rad/s step (each # is 0.25 rad/s):")
for k in (0, 2, 4, 6, 8, 10, 12, 15, 20):
    print(f"t = {k:3} ms  {w[k]:6.2f} rad/s  {'#' * int(round(w[k] / 0.25))}")
print("and after the load step at 300 ms:", ", ".join(f"{w[k]:.2f}" for k in (300, 302, 305, 310, 320, 350, 400, 500)))
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Reading the first table:

  • P control settles at 9.21 rad/s instead of 10 (the 7.9% error predicted), and the load knocks it down a further 0.12 rad/s, permanently.
  • PI control rises in 6 ms with essentially no overshoot, settles in 11 ms, and after the load step dips by 0.11 rad/s and recovers completely, because the integral finds the extra voltage the load needs.
  • PID control is twice as fast (3 ms rise, 9 ms settling) for 5.6% overshoot and more voltage, and rejects the load better (a 0.073 rad/s dip).
  • The Ziegler–Nichols PID, discussed below, overshoots by 71%.

The second table is about a nonlinearity every real actuator has: a limit. A 300 rad/s step demands far more than 12 V, so the supply saturates, and the speed takes 33 ms just to rise from 10% to 90% of the target. Meanwhile, a naive integral term keeps accumulating the large error, winding up a huge value that must then be unwound by an error of the opposite sign: the speed overshoots by 22%. The fix, anti-windup, stops integrating while the output is saturated (unless the error would pull it out of saturation). With it, the overshoot vanishes. Every industrial PID implementation includes anti-windup.

ComputationC

The root locus: poles as the gain sweeps

How does stability depend on the gain? The root locus answers by plotting the closed-loop poles, the roots of 1+KpP(s)=01 + K_pP(s) = 0, as KpK_p sweeps upwards. Walter Evans gave rules in 1948 for sketching it by hand (it starts at the open-loop poles and ends at the open-loop zeros or at infinity); today we simply compute it.

For the continuous model with no delay, the first program showed the two poles meeting and moving apart vertically, never crossing into the right half-plane. But the real loop is digital, with one sample of computation delay. That delay adds a third pole, at z=0z = 0 in the z-plane, and changes everything.

python
import numpy as np

R, L, K, J, b = 1.2, 0.6e-3, 0.02, 2e-5, 1e-5
T = 1e-3

# The digital loop: the motor discretised exactly (zero-order hold), plus one sample of delay
# between measuring the speed and applying the new voltage.
A = np.array([[-b / J, K / J], [-K / L, -R / L]])
M = np.zeros((3, 3))
M[:2, :2], M[:2, 2] = A, [0, 1 / L]
def expm(X):
    n = max(0, int(np.ceil(np.log2(np.abs(X).sum(axis=1).max() / 0.5))))
    S, term = np.eye(len(X)), np.eye(len(X))
    for k in range(1, 16):
        term = term @ (X / 2 ** n) / k
        S = S + term
    for _ in range(n):
        S = S @ S
    return S
Phi = expm(M * T)
Ad, Bd = Phi[:2, :2], Phi[:2, 2]

def closed_loop_poles(Kp):
    """State [speed, current, voltage waiting to be applied]; the controller sets it to -Kp * speed."""
    F = np.zeros((3, 3))
    F[:2, :2], F[:2, 2] = Ad, Bd
    F[2, 0] = -Kp
    return np.linalg.eigvals(F)

print("   Kp     closed-loop poles in the z-plane      largest |z|   matching s-plane poles (1/s)")
for Kp in (0.05, 0.2, 0.3, 0.5, 0.8, 1.0, 1.2):
    z = closed_loop_poles(Kp)
    z = np.array(sorted(z, key=lambda q: (-round(abs(q), 9), -q.imag)))
    s = np.log(z[:2].astype(complex)) / T                      # z = e^{sT}  =>  s = ln(z) / T
    ztxt = ", ".join(f"{q.real:+.3f}{q.imag:+.3f}j" if abs(q.imag) > 1e-9 else f"{q.real:+.3f}" for q in z)
    stxt = ", ".join(f"{q.real:.0f}{q.imag:+.0f}j" if abs(q.imag) > 1e-6 else f"{q.real:.0f}"
                     for q in sorted(s, key=lambda q: -q.imag))
    print(f"{Kp:6.2f}   {ztxt:38}  {np.abs(z).max():8.4f}     {stxt}")

# Bisect for the gain at which the largest pole reaches the unit circle.
lo, hi = 0.5, 2.0
for _ in range(50):
    mid = (lo + hi) / 2
    lo, hi = (mid, hi) if np.abs(closed_loop_poles(mid)).max() < 1 else (lo, mid)
z = closed_loop_poles(lo)
crit = z[np.argmax(np.abs(z))]
Tu = 2 * np.pi * T / abs(np.angle(crit))
print(f"\nultimate gain Ku = {lo:.4f} V per rad/s; the loop then oscillates with period Tu = {Tu * 1e3:.2f} ms ({1 / Tu:.0f} Hz)")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.
Kp = Ku ≈ 1.06Re zIm z× open-loop poles · dots every ΔKp = 0.01
Root locus of the digital proportional speed loop in the z-plane, computed for gains from 0 to 1.5. The slow motor pole (near 0.98) and the fast one (near 0.14) move together, meet, and become a complex pair that leaves the unit circle at the ultimate gain Ku ≈ 1.06 (red: unstable). The delay's pole, starting at 0, moves left along the real axis.

At low gain the slow pole moves quickly inwards (a faster response: its s-plane equivalent goes from −17-17 to −65-65 s⁻¹ at Kp=0.05K_p = 0.05). Between Kp=0.2K_p = 0.2 and 0.30.3 the two motor poles meet and split into a complex pair, and from then on more gain means more oscillation: at Kp=1K_p = 1 the pair sits at radius 0.98, an oscillation that barely decays (the s-plane equivalent is −20±792j-20 \pm 792j). At Kp=1.064K_p = 1.064, the ultimate gain KuK_u, the pair reaches the unit circle and the loop oscillates for ever at 128 Hz, period Tu=7.78T_u = 7.78 ms. Above it the oscillation grows. In the laboratory, that growing oscillation is limited by the supply voltage and appears as a loud, constant buzz from the motor.

ComputationC

Stability margins: Bode and Nyquist

Root loci answer "at what gain?". Engineers more often ask "how close to instability is this design, in every respect?", and they answer it with the loop's frequency response L(jω)L(j\omega), which can be measured on real hardware even when no model exists.

The loop becomes unstable when, at some frequency, the signal going round the loop comes back with the same amplitude and inverted, so that L(jω)=−1L(j\omega) = -1. Nyquist's criterion makes this exact.

Theorem— Nyquist stability criterion

Let PolP_{\text{ol}} be the number of poles of L(s)L(s) in the right half-plane. Trace L(jω)L(j\omega) as ω\omega runs from −∞-\infty to ∞\infty (the Nyquist plot), and let NN be the number of times it encircles the point −1-1 clockwise. Then the closed loop has Z=N+PolZ = N + P_{\text{ol}} poles in the right half-plane. In particular, for a stable open loop, the closed loop is stable exactly when the Nyquist plot does not encircle −1-1.

The proof uses the argument principle of complex analysis (see Complex analysis): the number of times 1+L(s)1 + L(s) winds around zero, as ss traces a contour enclosing the right half-plane, counts its zeros minus its poles there, and the zeros of 1+L1 + L are the closed-loop poles. For a digital loop the same statement holds with z=ejωTz = e^{j\omega T} running round the unit circle and "outside the unit circle" in place of "right half-plane".

How far the plot stays from −1-1 is measured by two numbers.

Definition— Gain margin and phase margin

At the phase crossover frequency ω180\omega_{180}, where ∠L=−180°\angle L = -180°, the gain margin is GM=1/∣L(jω180)∣\mathrm{GM} = 1/|L(j\omega_{180})|, usually in decibels: the factor by which the gain could rise before instability. At the gain crossover frequency ωc\omega_c, where ∣L∣=1|L| = 1, the phase margin is PM=180°+∠L(jωc)\mathrm{PM} = 180° + \angle L(j\omega_c): the extra phase lag (for example, extra delay) the loop could tolerate.

Typical targets are a phase margin of 45° to 65° and a gain margin of 6 to 12 dB. On a Bode plot (gain in decibels and phase against log frequency, as in Frequency response and filters) both margins can be read at a glance, and the gain crossover frequency ωc\omega_c is roughly the closed-loop bandwidth. The program computes the digital loop's frequency response for each design, finds the margins, derives the Ziegler–Nichols settings from the same data, and counts Nyquist encirclements numerically.

python
import numpy as np

R, L, K, J, b = 1.2, 0.6e-3, 0.02, 2e-5, 1e-5
T = 1e-3
A = np.array([[-b / J, K / J], [-K / L, -R / L]])
M = np.zeros((3, 3))
M[:2, :2], M[:2, 2] = A, [0, 1 / L]
def expm(X):
    n = max(0, int(np.ceil(np.log2(np.abs(X).sum(axis=1).max() / 0.5))))
    S, term = np.eye(len(X)), np.eye(len(X))
    for k in range(1, 16):
        term = term @ (X / 2 ** n) / k
        S = S + term
    for _ in range(n):
        S = S @ S
    return S
Phi = expm(M * T)
Ad, Bd = Phi[:2, :2], Phi[:2, 2]
tau_m, tau_e = sorted(-1 / np.linalg.eigvals(A).real)[::-1]

def loop(w, Kp, Ti=None, Td=0.0, N=10):
    """Loop gain L = C(z) P(z) z^-1 on the unit circle z = e^{jwT}: controller, held motor, one-sample delay."""
    zi = np.exp(-1j * w * T)
    C = Kp + 0 * zi
    if Ti is not None:
        C = C + Kp * T / Ti * zi / (1 - zi)
    if Td > 0:
        a = Td / (Td + N * T)
        C = C + Kp * Td * N / (Td + N * T) * (1 - zi) / (1 - a * zi)
    P = np.array([np.linalg.solve(np.eye(2) / q - Ad, Bd)[0] for q in zi])   # [1 0] (zI - Ad)^-1 Bd
    return C * P * zi

w = np.logspace(0, np.log10(0.999 * np.pi / T), 20000)          # 1 rad/s up to the Nyquist frequency
def margins(**c):
    Lw = loop(w, **c)
    mag, ph = np.abs(Lw), np.unwrap(np.angle(Lw))
    i = np.argmax(mag < 1)                                         # gain crossover
    j = np.argmax(ph < -np.pi)                                     # phase crossover (-180 degrees)
    return w[i], 180 + np.degrees(ph[i]), w[j], -20 * np.log10(mag[j])

designs = {
    "P  Kp = 0.24":  dict(Kp=0.24),
    "P  Kp = 1.0":   dict(Kp=1.0),
    "P  Kp = 1.2":   dict(Kp=1.2),
    "PI  (model)":   dict(Kp=0.238, Ti=tau_m),
    "PID (model)":   dict(Kp=0.42, Ti=tau_m + tau_e, Td=tau_m * tau_e / (tau_m + tau_e)),
}
# Ziegler-Nichols from the ultimate gain and period: P alone, at the phase crossover.
_, _, w180, gm1 = margins(Kp=1.0)
Ku, Tu = 10 ** (gm1 / 20), 2 * np.pi / w180
designs["PID (Z-N)"] = dict(Kp=0.6 * Ku, Ti=Tu / 2, Td=Tu / 8)
print(f"from the Bode data: Ku = {Ku:.3f}, Tu = {Tu * 1e3:.2f} ms;  Z-N PID: Kp = {0.6 * Ku:.3f}, Ti = {Tu / 2 * 1e3:.2f} ms, Td = {Tu / 8 * 1e3:.2f} ms")

print("\ndesign          crossover      phase margin   gain margin")
for name, c in designs.items():
    wc, pm, wp, gm = margins(**c)
    print(f"{name:14} {wc / (2 * np.pi):6.1f} Hz       {pm:6.1f} deg     {gm:6.1f} dB")

# Nyquist: count how many times the curve L(e^{jwT}), for w from -pi/T to pi/T, encircles -1.
# The motor is stable, so the closed loop is stable exactly when the count is zero.
print("\nNyquist check for proportional control:")
ww = np.linspace(-np.pi / T, np.pi / T, 40001)
for Kp in (0.24, 1.0, 1.2):
    turns = np.sum(np.diff(np.unwrap(np.angle(1 + loop(ww, Kp))))) / (2 * np.pi)
    n = abs(int(round(turns)))
    print(f"  Kp = {Kp:4}: encirclements of -1 = {n}  ->  unstable closed-loop poles = {n}")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.
−0.23−1phase marginRe LIm LKp = 0.24 (stable, margins 72° and 12.9 dB)Kp = 1.2 (encircles −1: unstable)
The Nyquist plot of the proportional speed loop near the critical point −1, for positive frequencies (the negative-frequency half is its mirror image in the real axis). With Kp = 0.24 the curve crosses the negative real axis at −0.23, a gain margin of 12.9 dB, and meets the unit circle 72° away from −1, the phase margin. With Kp = 1.2 it crosses to the left of −1: the full plot encircles the critical point twice, and the closed loop has two unstable poles.

The numbers agree with the root locus: the phase crossover of the proportional loop gives the same Ku=1.064K_u = 1.064 and Tu=7.78T_u = 7.78 ms. Kp=1K_p = 1 is stable but with margins of only 0.5 dB and 4.5°, a loop that rings for dozens of cycles. Kp=1.2K_p = 1.2 has negative margins and encircles −1-1 twice: the two unstable poles of the root locus. The model-based PI design has margins of 67° and 12.9 dB, comfortably robust; the PID design trades some of that (59° and 7.9 dB) for a crossover almost twice as high, 57 Hz against 31 Hz.

ExplanationH

Ziegler–Nichols tuning and its limits

Many plants come without a model. In 1942 John Ziegler and Nathaniel Nichols, engineers at an American instrument company, published rules for tuning a PID controller from a simple experiment, and their rules became the most famous in the field. The closed-loop method: with integral and derivative action off, raise the proportional gain until the loop just oscillates steadily; record that ultimate gain KuK_u and the oscillation period TuT_u; then set

ControllerKpK_pTiT_iTdT_d
P0.5 Ku0.5\,K_u——
PI0.45 Ku0.45\,K_uTu/1.2T_u/1.2—
PID0.6 Ku0.6\,K_uTu/2T_u/2Tu/8T_u/8

For our motor this gives Kp=0.638K_p = 0.638, Ti=3.89T_i = 3.89 ms and Td=0.97T_d = 0.97 ms. The Ziegler–Nichols loop has the highest crossover (84 Hz) and the best rejection of the load step (a dip of only 0.059 rad/s), but a phase margin of 32°, a gain margin of 3.5 dB and a 71% overshoot on a reference step. That is not a bug: the rules were designed for process plants, to make the response to a load disturbance decay by a factor of about four per cycle, which is aggressive by modern standards.

Its limits, as practising engineers see them:

  • The experiment is risky. Driving a plant to the edge of instability is unacceptable for a chemical reactor or an aircraft. Modern relay autotuners, introduced by Karl Åström and Tore Hägglund in the 1980s, find KuK_u and TuT_u from a small, controlled oscillation instead.
  • The margins are thin. A 3.5 dB gain margin means a 50% rise in plant gain, from a heavier load or a fuller tank, could destabilise the loop.
  • One experiment, one point. KuK_u and TuT_u describe the plant at a single frequency, which serves plants with long delays poorly.

Today Ziegler–Nichols is best seen as a historical starting point. Model-based rules such as Skogestad's SIMC rules, lambda tuning, and optimisation against explicit margin and noise constraints give more robust loops, and software tools automate them.

ExplanationH

Digital implementation

Almost every controller built today is a program running on a microcontroller, a digital signal processor or a programmable logic controller. The theory of this level tells you what to watch for.

  • Sample fast enough. A common rule of thumb samples 10 to 30 times faster than the closed-loop bandwidth; our 1 kHz controller with a 31 Hz crossover is at 32 times.
  • Count the delay. Measuring, computing and holding the output cost about one and a half sample periods, which removes phase 1.5 ωT1.5\,\omega T at every frequency. At our PI crossover (197 rad/s) that is 0.30 rad, about 17° of phase margin spent on being digital.
  • Discretise each term sensibly. The integral becomes a running sum, Ik=Ik−1+Kp(T/Ti) ekI_k = I_{k-1} + K_p (T/T_i)\,e_k; the derivative becomes a filtered difference of the measurement, with the filter constant NN (typically 5 to 20) capping its high-frequency gain at KpNK_p N.
  • Handle the limits. Clamp the output to what the actuator can do, use anti-windup, and initialise the integral when switching from manual to automatic so the output does not jump (bumpless transfer). On fixed-point processors, scale variables so the integrator cannot overflow.
  • Keep time. Run the controller from a hardware timer interrupt, because timing jitter is extra, varying delay; Real-time and low-power design covers this.

Here is the heart of such a controller as it might be written in C for a microcontroller (not run here: it needs a real timer, ADC and PWM driver).

c
/* PI speed controller, called from a 1 kHz timer interrupt. Not run: needs real hardware. */
typedef struct { float kp, ki_t, u_min, u_max, integral; } pi_ctrl;

float pi_update(pi_ctrl *c, float reference, float measured)
{
    float e = reference - measured;
    float v = c->kp * e + c->integral;
    float u = v > c->u_max ? c->u_max : (v < c->u_min ? c->u_min : v);
    /* anti-windup: integrate only when not saturated, or when the error unwinds it */
    if (u == v || (v > c->u_max && e < 0.0f) || (v < c->u_min && e > 0.0f))
        c->integral += c->ki_t * e;            /* ki_t = Kp * T / Ti */
    return u;                                  /* written to the PWM duty cycle */
}

If you build a motor controller yourself, use a small motor, a current-limited bench supply or a small battery, and a shaft with nothing that can fly off or catch fingers or hair. An unstable loop drives the motor to full power and reverses it violently, which is harmless at a few watts and dangerous at a few kilowatts. Industrial drives are guarded, and they include certified safety functions, such as a hardware-enforced "safe torque off" defined in the IEC 61800-5-2 standard, that do not depend on the control software behaving.

ExplanationH

Where control lives in industry

  • Process control. Refineries, chemical plants, paper mills and water works run thousands of loops each (flow, pressure, level, temperature), overwhelmingly PI and PID, inside distributed control systems and programmable logic controllers. The hard problems are delays, interacting loops, and keeping thousands of loops well tuned as plants age.
  • Motor drives. Electric vehicles, trains, lifts and robots use field-oriented control: a fast inner PI loop on the motor currents (bandwidths in the kilohertz), an outer speed loop and an outermost position loop, each several times slower than the one inside it, so each can be designed with this lesson's tools. Transformers and machines describes the machines.
  • Power converters. Every switching power supply regulates its output with a feedback loop, typically crossing over at a tenth of the switching frequency or below, shaped with compensators and checked for phase margin on a network analyser (see Power electronics).
  • Flight control. Most modern airliners are fly-by-wire: flight-control computers drive the control surfaces through redundant loops whose gains are scheduled with speed and altitude, under strict certification. Drones run PID attitude loops at hundreds of hertz.
  • Power grids. Generators share load through proportional droop control, and slower integral loops restore the frequency; The power grid explains how.

Beyond classical control lie state-space, optimal and model predictive control, which Lumenary Robotics develops in state space and LQR and model predictive control.

Common misconceptionsH

Common misconceptions

Misconception

"More gain is always better." More gain reduces steady-state error and speeds up the response only until the margins run out. In the digital motor loop, Kp=1K_p = 1 was barely stable and Kp=1.2K_p = 1.2 unstable, although the idealised continuous model said any gain was fine. Delay is what the idealised model forgot.

Misconception

"Derivative action predicts the future." It extrapolates the present slope, which helps damping, but it also amplifies high-frequency noise in proportion to frequency. Unfiltered derivative action on a noisy sensor makes the actuator chatter. That is why it is filtered, applied to the measurement, and often left out altogether (most industrial loops are PI).

Misconception

"Integral action fixes everything." It removes steady-state error, but adds phase lag (eroding the margins) and winds up whenever the actuator saturates. A loop with too strong an integral, like the Ziegler–Nichols design here, overshoots badly.

Misconception

"A stable closed loop is a good closed loop." A loop with 4.5° of phase margin is stable and nearly useless: it rings after every disturbance and goes unstable if the plant changes slightly. Margins, not mere stability, are the design target.

History & global context

A short history

The theory of feedback begins with James Watt's centrifugal governor for steam engines (1788) and James Clerk Maxwell's 1868 analysis of why such governors sometimes oscillated. In 1922 Nicolas Minorsky described three-term (PID) control for steering ships. In 1927 Harold Black at Bell Labs invented the negative-feedback amplifier, which made long-distance telephony possible; in 1932 his colleague Harry Nyquist explained when such amplifiers were stable, and Hendrik Bode turned frequency-response design into the method this lesson uses. Ziegler and Nichols published their rules in 1942 and Walter Evans the root locus in 1948; from around 1960, Rudolf Kálmán and others developed the state-space methods of modern control.

Optional Christian reflection · Correction as a gift

A reflection from the Christian tradition that inspires Lumenary Academy. It is not part of the mathematics and you are welcome to skip it.

Feedback works because the system is willing to be told it is wrong, every millisecond, and to act on it. The margins are a kind of humility built into the design: an admission that our model of the world is imperfect, and a reserve kept for the surprises that will come. Many traditions, including the Christian one, have long seen that people, too, grow by welcoming correction rather than resisting it.

Exercises

Exercises

1. Feedback control

Warm-upHuman

A unity-feedback loop has no integrator, and its loop gain at DC is L(0)=19L(0) = 19. The closed loop is stable. After a step change in the reference, what steady-state error remains, as a percentage of the step?

2. Feedback control

CoreHuman

The motor of the lesson is under PI speed control (a type-1 loop). The speed reference now ramps steadily upwards at 100 rad/s per second, well within what the motor can do. After the transient, what is the speed error?

Choose one

3. Feedback control

Warm-upHuman

In a Ziegler–Nichols test on a heating process, the loop under proportional control oscillates steadily at the gain Ku=2.5K_u = 2.5 with a period Tu=40T_u = 40 s. What integral time TiT_i, in seconds, do the Ziegler–Nichols rules give for a PID controller?

4. Feedback control

CoreHuman

A loop has L(s)=100s(s+10)L(s) = \dfrac{100}{s(s + 10)}. Find its phase margin, to the nearest degree.

5. Feedback control

CoreHuman

A plant is stable on its own (no open-loop poles in the right half-plane). With a particular controller, the full Nyquist plot of LL encircles the point −1-1 twice in the clockwise direction. What can you conclude about the closed loop?

Choose one

6. Feedback control

CoreComputational

Write phase_margin(num, den, delay=0.0) returning the phase margin, in degrees, of the continuous-time loop L(s)=N(s)D(s)e−sτL(s) = \dfrac{N(s)}{D(s)}e^{-s\tau}, with polynomial coefficients highest power first and τ\tau = delay in seconds. Evaluate L(jω)L(j\omega) on a fine logarithmic grid of frequencies, find the first frequency where ∣L∣|L| drops below 1, and return 180°+∠L180° + \angle L there, using an unwrapped phase. Assume ∣L∣|L| crosses 1 once, going down.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

7. Feedback control

StretchComputational

Complete the PI class: update(error) must return the controller output clamped to [u_min, u_max], and must not wind up: while the output is saturated, it should only integrate errors that would bring it back out of saturation. The tests run your controller on a first-order plant at 1 kHz, check that the output limits are respected, that a step and a constant disturbance leave no steady-state error, and that a large step (which saturates the output) does not overshoot by more than 5%.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Further reading and resources

  • Feedback Systems: An Introduction for Scientists and Engineers · Karl J. Åström and Richard M. MurrayA complete control textbook whose authors make it freely available online, with examples from biology to aerospace.
  • Python Control Systems LibraryOpen-source tools for transfer functions, root loci, Bode and Nyquist plots, margins and state-space design.
  • Regeneration theory · Harry Nyquist · 1932Bell System Technical Journal; the paper that introduced the Nyquist stability criterion.
  • Optimum settings for automatic controllers · John G. Ziegler and Nathaniel B. Nichols · 1942Transactions of the ASME; the source of the Ziegler–Nichols tuning rules.
  • Simple analytic rules for model reduction and PID controller tuning · Sigurd Skogestad · 2003Journal of Process Control; the SIMC rules, a widely used model-based alternative to Ziegler–Nichols.