TExcelTAD
Home › Control Systems & Automation › Mini Project: Model, Tune and Evaluate a Temperature or Speed Loop

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 10 Ω10\ \Omega resistor on 12 V12\ \text{V} 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 25 K25\ \text{K} above room temperature (about 50 ∘C50\,^\circ\text{C})
overshoot of the block temperature at most 2 K2\ \text{K} (8 %)
settling to ±0.5 K\pm 0.5\ \text{K} within 10 min10\ \text{min}
disturbance: a fan doubles the heat loss temperature dip at most 3 K3\ \text{K}, recovery to ±0.5 K\pm 0.5\ \text{K} within 10 min10\ \text{min}
actuator 0–14.4 W0\text{–}14.4\ \text{W} (PWM duty 0–100 %)
robustness phase margin at least 45∘45^\circ, gain margin at least 6 dB6\ \text{dB} on the identified model
safety independent cut-off at 70 ∘C70\,^\circ\text{C}; software trip; never unattended

2. First-principles model

From Thermal and Fluid Systems: heat capacity Ch=75 J/KC_h = 75\ \text{J/K} (about 85 g85\ \text{g} of aluminium plus the resistor), loss conductance 1/Rth=0.25 W/K1/R_\text{th} = 0.25\ \text{W/K}, so T(s)P(s)=4300s+1\frac{T(s)}{P(s)} = \frac{4}{300 s + 1}. The sensor in its pocket adds a lag (τs≈20 s\tau_s \approx 20\ \text{s}) and the heat takes time to travel from the resistor to the pocket (about 10 s10\ \text{s} of transport delay). The "true" plant used below for testing is therefore

G(s)=4 e−10s(300s+1)(20s+1)  K/WG(s) = \frac{4\,e^{-10 s}}{(300 s + 1)(20 s + 1)}\ \ \text{K/W}

The steady state at the setpoint needs 25×0.25=6.25 W25 \times 0.25 = 6.25\ \text{W} (43 % duty); with the fan, 12.5 W12.5\ \text{W} (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 % (7.2 W7.2\ \text{W}) from room temperature, log the sensor every 2 s2\ \text{s} for 25 min25\ \text{min}, and fit a first-order-plus-dead-time (FOPDT) model Ke−θsTs+1\frac{K e^{-\theta s}}{T s + 1} (Model-Based Tuning). The program generates that log from the true plant, with 0.05 K0.05\ \text{K} rms sensor noise, and fits it:

python · try it yourself
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 10 s10\ \text{s} transport delay: the FOPDT model has to represent the 20 s20\ \text{s} sensor lag somehow, and it does so mostly as extra dead time. The half rule of Model-Based Tuning would give θ≈10+20/2=20 s\theta \approx 10 + 20/2 = 20\ \text{s} and T≈300+10=310 sT \approx 300 + 10 = 310\ \text{s}; the least-squares fit, which weighs the whole curve, puts more of the lag into the delay (28.6 s28.6\ \text{s}) and keeps TT near 300 s300\ \text{s}. 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 KK, TT, θ\theta (Ziegler–Nichols, Cohen–Coon, IMC and lambda), then test each on the true plant, implemented as the microcontroller would run it: sample time Ts=1 sT_s = 1\ \text{s} (more than 20 samples per sensor time constant: Sampled-Data Loops), output clamped to 0–14.4 W0\text{–}14.4\ \text{W}, and clamping anti-windup (Anti-Windup, Discrete PID). Setpoint step to 25 K25\ \text{K} at t=0t = 0; the fan doubles the loss at t=1200 st = 1200\ \text{s}.

python · try it yourself
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 14.4 W14.4\ \text{W} at first, the heater saturates, and the anti-windup keeps the overshoot small (at most 0.63 K0.63\ \text{K}). They differ on the rest. Ziegler–Nichols and Cohen–Coon settle in about 330 s330\ \text{s} and keep the fan dip under 3 K3\ \text{K} (2.7 K2.7\ \text{K}, recovered in about 130 s130\ \text{s}). Lambda with λ=60 s\lambda = 60\ \text{s} is too slow for both the settling (762 s762\ \text{s}) and the fan (4.4 K4.4\ \text{K} dip, 17 min17\ \text{min} to recover). SIMC settles in 551 s551\ \text{s} and recovers in 575 s575\ \text{s}, but its dip of 3.6 K3.6\ \text{K} 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):

python · try it yourself
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 (45∘45^\circ, 6 dB6\ \text{dB}). The two quarter-decay rules that looked best in section 4 have phase margins of only 20–24∘20\text{–}24^\circ and gain margins under 4 dB4\ \text{dB}: a rise of only 50–60 % in plant gain (a factor of 103.4/20=1.4810^{3.4/20} = 1.48 to 103.9/20=1.5710^{3.9/20} = 1.57: 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 3 K3\ \text{K}. A SIMC tuning with τc=θ/2\tau_c = \theta/2 sits right on both limits (about 45∘45^\circ and a 3.1 K3.1\ \text{K} 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 (0.25 W/K×25 K=6.25 W0.25\ \text{W/K} \times 25\ \text{K} = 6.25\ \text{W}) 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 0.8 K0.8\ \text{K}, 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 85 g85\ \text{g}) with a 10 Ω10\ \Omega, 25 W25\ \text{W} 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 12 V12\ \text{V} bench supply with the current limit at 1.5 A1.5\ \text{A}; a bimetal thermal cut-out (70 ∘C70\,^\circ\text{C}) in series with the heater; a small PC fan for the disturbance.

Firmware. A fixed-rate task at Ts=1 sT_s = 1\ \text{s} (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 65 ∘C65\,^\circ\text{C} 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 0→25 K0 \to 25\ \text{K} with your chosen tuning; (3) fan on after settling; (4) a second tuning for comparison. Expect your KK within ±20 %\pm 20\,\% of 4 K/W4\ \text{K/W} and TT within ±30 %\pm 30\,\% of 300 s300\ \text{s} (convection, mounting and the block size differ); redo sections 4 and 5 with your numbers.

Hazards and safe setup. The block and resistor reach 50–70 ∘C50\text{–}70\,^\circ\text{C}: 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. 12 V12\ \text{V}, current-limited; no mains anywhere in the rig.

7. Write-up template

text
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 sensor

8. 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 (0→300 rad/s0 \to 300\ \text{rad/s}) and a load step; model the motor (Modelling a DC Motor); identify KK and the mechanical time constant from a step at 25 % duty (add a flywheel to make it slower than your sample rate allows comfortably: TsT_s of 1 ms1\ \text{ms} needs a time constant of at least about 20 ms20\ \text{ms}); 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 (≈29 s\approx 29\ \text{s}) exceed the 10 s10\ \text{s} transport delay of the true plant?

  1. the fit failed
  2. the FOPDT model lumps the 20 s sensor lag into an apparent delay
  3. the noise adds delay
  4. the heater is slow to switch

In section 4 all tunings show small setpoint overshoot. Why is that not proof that they are robust?

  1. the heater limit and the anti-windup shape the setpoint response; margins on the model must be checked separately
  2. the simulation is wrong
  3. overshoot does not matter
  4. the fan hides it

The heater needs 12.5 W12.5\ \text{W} with the fan on and can deliver 14.4 W14.4\ \text{W}. What does this mean for recovery after the fan starts?

  1. recovery is fast whatever the tuning
  2. only 1.9 W1.9\ \text{W} of reserve is left to reheat the block, so recovery is slow and limited by the actuator
  3. the loop becomes unstable
  4. the integrator is not needed

Which item belongs in the write-up's comparison with the specification?

  1. the firmware's variable names
  2. pass/fail per requirement with the measurement uncertainty
  3. the price of the parts
  4. the PWM frequency only