Mini Project: Model, Tune and Evaluate a Temperature or Speed Loop
The milestone of this course is to model, implement, tune and evaluate a closed-loop control system. In this project you do all four for the low-voltage heater block that has appeared since the introduction: a resistor on bolted to an aluminium block, a temperature sensor in a pocket, a MOSFET switched by a microcontroller. You will write a specification, build a first-principles model, identify a simpler model from a step test, tune a PI controller four ways, implement it as a sampled controller with actuator limits and anti-windup, test it against a disturbance and for robustness, and write it up. A speed-loop variant with the small DC motor follows the same steps (section 8). Every step links to the lesson that teaches it.
1. Specification
Write it before any design (Open and Closed Loop):
| Requirement | Value |
|---|---|
| setpoint | above room temperature (about ) |
| overshoot of the block temperature | at most (8 %) |
| settling to | within |
| disturbance: a fan doubles the heat loss | temperature dip at most , recovery to within |
| actuator | (PWM duty 0–100 %) |
| robustness | phase margin at least , gain margin at least on the identified model |
| safety | independent cut-off at ; software trip; never unattended |
2. First-principles model
From Thermal and Fluid Systems: heat capacity (about of aluminium plus the resistor), loss conductance , so . The sensor in its pocket adds a lag () and the heat takes time to travel from the resistor to the pocket (about of transport delay). The "true" plant used below for testing is therefore
The steady state at the setpoint needs (43 % duty); with the fan, (87 %): the heater is just big enough, which the specification must respect.
3. Step test and identification
On the bench: run the heater open loop at 50 % () from room temperature, log the sensor every for , and fit a first-order-plus-dead-time (FOPDT) model (Model-Based Tuning). The program generates that log from the true plant, with rms sensor noise, and fits it:
import numpy as np
from scipy.optimize import curve_fit
def true_plant_log(P, t, h=0.1):
"""Heater block 4 K/W, 300 s; sensor lag 20 s; 10 s transport delay. Sensor reading at times t."""
T = Tsens = 0.0
buf = [0.0] * int(10 / h)
times, vals = [], []
for tk in np.arange(0, t[-1] + h / 2, h):
times.append(tk); vals.append(Tsens)
buf.append(P)
u = buf.pop(0)
T += h * (4 * u - T) / 300
Tsens += h * (T - Tsens) / 20
return np.interp(t, times, vals)
rng = np.random.default_rng(7)
t = np.arange(0, 1500, 2.0)
y = true_plant_log(7.2, t) + rng.normal(0, 0.05, t.size)
def fopdt(t, K, T, theta):
return np.where(t > theta, 7.2 * K * (1 - np.exp(-(t - theta) / T)), 0.0)
(K, T, theta), cov = curve_fit(fopdt, t, y, p0=[3, 200, 5], bounds=([0, 1, 0], [10, 2000, 100]))
sd = np.sqrt(np.diag(cov))
print(f"FOPDT: K = {K:.3f} +/- {sd[0]:.3f} K/W, T = {T:.1f} +/- {sd[1]:.1f} s, theta = {theta:.1f} +/- {sd[2]:.1f} s")
res = y - fopdt(t, K, T, theta)
print(f"fit residual {np.std(res):.3f} K rms; final value {y[-50:].mean():.2f} K at 7.2 W")FOPDT: K = 4.003 +/- 0.001 K/W, T = 302.7 +/- 0.3 s, theta = 28.6 +/- 0.1 s
fit residual 0.072 K rms; final value 28.54 K at 7.2 W
The fitted delay is larger than the transport delay: the FOPDT model has to represent the sensor lag somehow, and it does so mostly as extra dead time. The half rule of Model-Based Tuning would give and ; the least-squares fit, which weighs the whole curve, puts more of the lag into the delay () and keeps near . Both are modelling choices, not errors. The tiny parameter uncertainties printed are the noise-only part: the real uncertainty is the model-structure mismatch, which is why section 5 checks robustness.
4. Four tunings, one plant
Compute PI settings from the identified , , (Ziegler–Nichols, Cohen–Coon, IMC and lambda), then test each on the true plant, implemented as the microcontroller would run it: sample time (more than 20 samples per sensor time constant: Sampled-Data Loops), output clamped to , and clamping anti-windup (Anti-Windup, Discrete PID). Setpoint step to at ; the fan doubles the loss at .
import numpy as np
K, T, theta = 4.003, 302.7, 28.6 # identified in section 3
def closed_loop(Kp, Ti, Ts=1.0, h=0.1, t_end=2400.0):
Tb = Tsens = I = P = 0.0
buf = [0.0] * int(10 / h) # 10 s transport delay of the true plant
m = int(round(Ts / h))
log = []
for n in range(int(t_end / h)):
tk = n * h
if n % m == 0: # controller runs every Ts
e = 25.0 - Tsens
v = Kp * e + I
P = min(max(v, 0.0), 14.4)
if v == P or (v > P and e < 0) or (v < P and e > 0):
I += Kp * Ts / Ti * e # integrate only when it does not push further into the limit
g = 0.5 if tk >= 1200 else 0.25 # fan on at 1200 s
buf.append(P)
u = buf.pop(0)
Tb += h * (u - g * Tb) / 75.0 # block temperature (the thing we care about)
Tsens += h * (Tb - Tsens) / 20.0 # sensor reading (what the controller sees)
log.append((tk, Tb, P))
a = np.array(log)
s1, s2 = a[a[:, 0] < 1200], a[a[:, 0] >= 1200]
over = max(0.0, s1[:, 1].max() - 25.0)
out1 = np.where(np.abs(s1[:, 1] - 25) > 0.5)[0]
out2 = np.where(np.abs(s2[:, 1] - 25) > 0.5)[0]
settle = s1[out1[-1], 0] if out1.size else 0.0
recover = s2[out2[-1], 0] - 1200 if out2.size else 0.0
iae = np.sum(np.abs(25.0 - a[:, 1])) * h
return over, settle, 25.0 - s2[:, 1].min(), recover, iae
tauc = theta # SIMC "tight" choice
rules = {
"Ziegler-Nichols step": (0.9 * T / (K * theta), 3.33 * theta),
"Cohen-Coon PI": (T / (K * theta) * (0.9 + theta / (12 * T)), theta * (30 + 3 * theta / T) / (9 + 20 * theta / T)),
"lambda PI, 60 s": (T / (K * (60 + theta)), T),
"SIMC PI, tau_c = theta": (T / (K * (tauc + theta)), min(T, 4 * (tauc + theta))),
}
print("rule : Kp W/K Ti s | overshoot settle fan dip recover IAE")
for name, (Kp, Ti) in rules.items():
over, settle, dip, rec, iae = closed_loop(Kp, Ti)
print(f"{name:22s}: {Kp:7.2f} {Ti:7.1f} | {over:6.2f} K {settle:6.0f} s {dip:6.2f} K {rec:6.0f} s {iae:6.0f} K*s")rule : Kp W/K Ti s | overshoot settle fan dip recover IAE
Ziegler-Nichols step : 2.38 95.2 | 0.33 K 333 s 2.72 K 133 s 2559 K*s
Cohen-Coon PI : 2.40 79.5 | 0.63 K 332 s 2.69 K 128 s 2539 K*s
lambda PI, 60 s : 0.85 302.7 | 0.00 K 762 s 4.43 K 1020 s 5471 K*s
SIMC PI, tau_c = theta: 1.32 228.8 | 0.00 K 551 s 3.57 K 575 s 3859 K*s
Evaluate against the specification. All four meet the overshoot limit: every rule asks for more than at first, the heater saturates, and the anti-windup keeps the overshoot small (at most ). They differ on the rest. Ziegler–Nichols and Cohen–Coon settle in about and keep the fan dip under (, recovered in about ). Lambda with is too slow for both the settling () and the fan ( dip, to recover). SIMC settles in and recovers in , but its dip of misses the limit. Before choosing, check robustness.
5. Robustness on the model
A tuning that works on one simulation must also tolerate model error. Compute the margins on the identified FOPDT model, with the delay as a Padé approximation (Stability Margins):
import numpy as np
import control as ct
K, T, theta = 4.003, 302.7, 28.6
G = ct.tf([K], [T, 1]) * ct.tf(*ct.pade(theta, 5))
rules = {
"Ziegler-Nichols step": (0.9 * T / (K * theta), 3.33 * theta),
"Cohen-Coon PI": (T / (K * theta) * (0.9 + theta / (12 * T)), theta * (30 + 3 * theta / T) / (9 + 20 * theta / T)),
"lambda PI, 60 s": (T / (K * (60 + theta)), T),
"SIMC PI, tau_c = theta": (T / (K * (2 * theta)), min(T, 8 * theta)),
}
for name, (Kp, Ti) in rules.items():
C = ct.tf([Kp * Ti, Kp], [Ti, 0]) # Kp (1 + 1/(Ti s))
gm, pm, wpc, wgc = ct.margin(C * G)
print(f"{name:22s}: gain margin {20 * np.log10(gm):5.1f} dB, phase margin {pm:5.1f} deg, "
f"crossover {wgc:.4f} rad/s")Ziegler-Nichols step : gain margin 3.9 dB, phase margin 24.2 deg, crossover 0.0329 rad/s
Cohen-Coon PI : gain margin 3.4 dB, phase margin 19.9 deg, crossover 0.0337 rad/s
lambda PI, 60 s : gain margin 13.7 dB, phase margin 71.5 deg, crossover 0.0113 rad/s
SIMC PI, tau_c = theta: gain margin 9.8 dB, phase margin 57.7 deg, crossover 0.0177 rad/s
Compare with the robustness line of the specification (, ). The two quarter-decay rules that looked best in section 4 have phase margins of only and gain margins under : a rise of only 50–60 % in plant gain (a factor of to : a different block, a stronger heater) would make them oscillate. Lambda and SIMC are robust. So no PI tuning meets every line: the fast ones are fragile, the robust ones let the fan pull the block down by more than . A SIMC tuning with sits right on both limits (about and a dip in the same simulations), which is too close to call on a real rig.
The way out is structural, not a cleverer PI: the controller knows when it switches the fan on, so a feedforward of the extra loss () removes most of the dip while the robust SIMC tuning stays in place (Cascade, Feedforward and Ratio Control). Add it to closed_loop (one line: v = Kp * e + I + (6.25 if tk >= 1200 else 0.0)) and check the dip against the specification: with the SIMC gains it falls to about , recovered within a minute. That conclusion, reached by evaluating against written requirements, is the point of the project.
6. Build it
Parts. Aluminium block (about ) with a , aluminium-housed resistor bolted on with thermal paste; a digital temperature sensor or an NTC in a drilled pocket; a logic-level N-MOSFET with gate resistor and a flyback-free resistive load; a USB-powered microcontroller; a bench supply with the current limit at ; a bimetal thermal cut-out () in series with the heater; a small PC fan for the disturbance.
Firmware. A fixed-rate task at (timer interrupt, not a delay loop) that reads the sensor, runs the PI with clamping anti-windup (Discrete PID), sets the PWM duty, and logs time, setpoint, measurement, duty and the integral state over the serial port. Add a software trip at that latches the heater off (Interlocks), and a manual mode with bumpless transfer (Practical PID).
Tests. (1) The open-loop step of section 3 on your hardware; (2) setpoint step with your chosen tuning; (3) fan on after settling; (4) a second tuning for comparison. Expect your within of and within of (convection, mounting and the block size differ); redo sections 4 and 5 with your numbers.
Hazards and safe setup. The block and resistor reach : burns. Mount it on stand-offs on a non-flammable surface, keep cables clear, keep the cut-out in the circuit at all times, never leave the rig powered and unattended, and switch off at once if anything smells or discolours. , current-limited; no mains anywhere in the rig.
7. Write-up template
Title, author, date
1. Objective and specification (table of section 1, with any changes and why)
2. Hardware (photo or sketch, parts, sensor position, safety measures)
3. Model (first-principles G(s); identified K, T, theta with uncertainty;
plot of measured vs fitted step)
4. Controller design (rules used, gains, sample time, anti-windup method)
5. Results (setpoint and disturbance responses, plots;
table: overshoot, settling, dip, recovery, IAE, max duty)
6. Robustness (gain and phase margins on the model; test with +/-20 % in K and T)
7. Comparison with the specification (pass/fail per line, with measurement uncertainty)
8. Discussion (what limited performance: actuator size, delay, noise, quantisation)
9. Conclusions and next steps (e.g. feedforward for the fan, cascade with a power loop)
Appendix: firmware listing, raw data files, calibration of the sensor8. Variant: a DC motor speed loop
The same steps work for the roadmap's speed-control project with the small motor (Motor Control): specify a speed step () and a load step; model the motor (Modelling a DC Motor); identify and the mechanical time constant from a step at 25 % duty (add a flywheel to make it slower than your sample rate allows comfortably: of needs a time constant of at least about ); tune a PI (with an inner current loop if your driver measures current: Cascade Control); clamp the duty and the current; and evaluate the same table. Hazards: clamp the motor, guard the shaft and flywheel, set the supply current limit.
Test yourself
Why does the identified FOPDT delay () exceed the transport delay of the true plant?
- the fit failed
- the FOPDT model lumps the 20 s sensor lag into an apparent delay
- the noise adds delay
- the heater is slow to switch
In section 4 all tunings show small setpoint overshoot. Why is that not proof that they are robust?
- the heater limit and the anti-windup shape the setpoint response; margins on the model must be checked separately
- the simulation is wrong
- overshoot does not matter
- the fan hides it
The heater needs with the fan on and can deliver . What does this mean for recovery after the fan starts?
- recovery is fast whatever the tuning
- only of reserve is left to reheat the block, so recovery is slow and limited by the actuator
- the loop becomes unstable
- the integrator is not needed
Which item belongs in the write-up's comparison with the specification?
- the firmware's variable names
- pass/fail per requirement with the measurement uncertainty
- the price of the parts
- the PWM frequency only