Skip to content
Tech Interview Prep
Technical interview guide

Control Systems & PID

The feedback loop that keeps a robot at a target state: proportional, integral, and derivative control, and why all three matter.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Current MathWorks, NI, Rockwell Automation, Arduino PID, python-control, SciPy, NIST SP 800-82 Rev. 3, IEC functional-safety, and OSHA guidance reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Choose open-loop or closed-loop control for a process.

Answer

Core answer. Two questions decide it: can you measure the output, and what does being wrong cost? If the output is measurable and an unmeasured disturbance can push it off target, close the loop. If the command-to-output relationship is repeatable and the cost of error is low, open loop is cheaper and cannot go unstable. Say that in the first minute, then justify it with the plant's own numbers.

Mechanism. Open loop applies a fixed command, so the output error equals the plant's own error: ambient shifts, aging, batch variation all land directly on the output. Closed loop measures the output and corrects, so sensitivity to plant gain variation drops by the loop-gain factor 1/(1+L).

Worked example: a 2 L water bath, 500 W heater, UA = 10 W/K, ambient 20 °C. Nominal steady state: ΔT = P/UA = 500/10 = 50 K, so 70 °C. Open loop at 100% duty:

  • Ambient rises to 30 °C → steady state 80 °C, a 10 K error.
  • Heater ages to 450 W → 20 + 45 = 65 °C, a 5 K error.

Closed loop with proportional loop gain L = 20: the same 10 K equivalent disturbance leaves 10/(1+20) ≈ 0.5 K error. That factor is the whole argument for feedback.

When open loop wins. Stepper-driven positioning where the load cannot stall; timed dosing through a validated pump; a conveyor oven running a fixed recipe. No sensor, no stability problem, no windup.

When feedback is hard. Dead time. If transport delay approaches or exceeds the plant time constant, PID tuning degrades into oscillation. In the bath, sensor lag plus mixing is ~20 s against τ = C/UA = 8360/10 ≈ 840 s: ratio 0.024, easy. A 30 m pipe with 60 s residence time against a 20 s time constant is the opposite case; use feedforward or a scheduled open-loop profile instead.

Failure modes and detection.

  • Sensor drift: the loop holds the wrong value. Detect with a second sensor or a model cross-check; a 2 °C drift on a 70 °C setpoint is invisible in the reading itself.
  • Integral windup during saturation: output pinned at 100%, error accumulating. Detect by output at limit with error persisting; fix with anti-windup clamping.
  • Instability from dead time: sustained oscillation at period ≈ 2× dead time. Detect in the trend; reduce gain or add derivative action.
  • Mode transfer bump: manual→auto steps the actuator. Detect by a discontinuity in the command trace; fix with bumpless transfer.
open loopclosed loop
sensornonerequired; accuracy sets the error floor
disturbance rejectionnone; error = disturbance1/(1+L)
stability risknonereal if dead time is large
costactuator + schedulesensor + controller + tuning

Decision rule. Measure the output, estimate the disturbance magnitude and the cost of the resulting error, and check dead time against the time constant. High error cost with small dead-time/τ ratio → close the loop. Otherwise run open loop on a scheduled command and add feedback only where the error is observable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Explain P, I, and D contributions and tradeoffs.

Answer

Assume the parallel form C(s) = Kp(1 + 1/(Ti s) + Td s/(1 + Td s/N)), with N typically 8–20. The three terms trade speed, offset, and noise against phase margin.

P: output is Kp times the present error e = sp − y. It sets bandwidth and stiffness: higher Kp speeds the response and reduces offset, but for a type-0 plant the offset never reaches zero. For G(s) = 2/(0.5s+1) and Kp=4, the closed-loop DC gain is 8, so a unit step leaves steady-state error 1/(1+8) = 0.111, i.e. 11.1% offset. Push Kp until phase margin drops below ~45° and you get overshoot and ringing; the plant's own lag plus any dead time sets the limit.

I: output is (Kp/Ti)∫e dt. It removes the offset: any nonzero e keeps integrating until e = 0. The cost is phase. The integrator alone contributes −90°; in the parallel PI form the combined phase is −90° + atan(ωTi). At ω=2 rad/s with Ti=0.5 s that is −90° + 45° = −45°, which eats phase margin and slows the loop. Under actuator saturation the integral keeps accumulating, windup, so the controller overshoots when the actuator comes out of saturation. Detect it by watching the integral term against the output limit; fix with clamping or back-calculation.

D: output is Kp Td de/dt, filtered. It adds phase lead: at ω=2 rad/s with Td=0.1 s and N=10, the lead is atan(0.2) − atan(0.02) = 11.3° − 1.1° = 10.2°. That damps oscillation and lets you raise Kp. The trade-off is noise: derivative gain rises with frequency. With Kp Td = 0.2 s, 10 mV RMS noise at 100 Hz produces about 0.2 × 2π × 100 × 0.01 = 1.26 V RMS at the controller output if unfiltered. The filter caps high-frequency gain at Kp N = 20, cutting that to roughly 0.2 V RMS. Apply D to the measurement, not the error, to avoid a setpoint kick.

TermTransfer functionPhase at crossoverSteady-state errorMain failure
PKp0°1/(1+Kp K) for type 0oscillation
IKp/(Ti s)−90°0windup
DKp Td s/(1+Td s/N)+90° max, less with filter0noise/jitter

Discrete implementation, derivative on measurement, filtered, with integral clamp:

Python
# Python 3.11
class PID:
    def __init__(self, kp, ti, td, n, dt, i_max):
        self.kp, self.ti, self.td, self.n, self.dt = kp, ti, td, n, dt
        self.i_max = i_max
        self.i = 0.0
        self.d = 0.0
        self.prev_y = None

    def step(self, sp, y):
        e = sp - y
        self.i += self.kp * self.dt / self.ti * e
        self.i = min(max(self.i, -self.i_max), self.i_max)
        if self.prev_y is None:
            self.prev_y = y
        dy = y - self.prev_y
        alpha = self.td / (self.td + self.n * self.dt)
        self.d = alpha * self.d - self.kp * self.td * self.n / (self.td + self.n * self.dt) * dy
        self.prev_y = y
        return self.kp * e + self.i + self.d

Trace with Kp=2, Ti=1 s, Td=0.1 s, N=10, dt=0.01 s, i_max=10. Then alpha = 0.1/(0.1+0.1)=0.5, and the dy coefficient = 20.110/0.2 = 10. Start sp=1, y=0. Step 1: e=1, i=0.02, prev_y=0, dy=0, d=0, output=2.02. Step 2: y=0.1, e=0.9, i=0.038, dy=0.1, d=0.50−100.1=−1.0, output=2*0.9+0.038−1.0=0.838. That is the derivative braking as the measurement rises.

Tuning: Ziegler-Nichols ultimate gain gives Kp=0.6 Ku, Ti=Tu/2, Td=Tu/8. Lambda tuning for a first-order-plus-dead-time plant K=2, τ=0.5 s, θ=0.1 s, choose λ=0.5 s: Kp = τ/(K(λ+θ)) = 0.5/(2*0.6) = 0.417, Ti = τ = 0.5 s. Sample at 10–20× the dominant time constant: for τ=0.5 s, dt = 25–50 ms; for the derivative filter, keep dt ≤ Td/10, so Td=0.1 s needs dt ≤ 10 ms.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Define control-loop performance and reliability metrics.

Answer

Core answer. Split the list in two, because they answer different questions. Performance metrics say how well the loop tracks setpoint and rejects disturbance while the plant is healthy. Reliability metrics say whether it keeps doing that safely across modes, faults, load and time. Assume a SISO regulatory loop, PID or MPC, sampled at fixed period Ts, driving an actuator with a range and a slew limit. A candidate who recites one flat list has not answered the question; the split is the answer.

Performance. Time domain: rise time (10–90%), settling time into a ±2% band, percent overshoot, steady-state error, and an integral criterion (IAE, ISE, ITAE) when comparing tunings. Disturbance rejection: peak deviation and recovery time after a step load. Frequency domain: gain margin (≥6 dB typical), phase margin (45–60°), and the sensitivity peak Ms = max|S(jω)|. Ms is the number to quote for robustness, keep it under 2 (6 dB), because it bounds both disturbance amplification and noise transmission at once.

Reliability. Actuator saturation time and rate-limit time as a fraction of runtime; integrator value at saturation exit (windup); peak deviation on mode transfer (auto/manual, gain schedule); sample jitter and deadline-miss count; age of the freshest feedback sample; interlock trips and nuisance-trip rate; safe-transition time to a safe state; drift of any of the above by operating region and firmware version.

The trade-off. Bandwidth buys rise time and costs robustness. Push crossover up and Ms rises, so noise amplification |C·S| at high frequency rises with it, and the actuator works harder. You cannot get fast rise, low overshoot and low actuator effort at the same operating point: pick two, and say which you picked and why.

Worked trace. Plant y[k+1] = y[k] + 0.1·u[k], setpoint 1.0, PI with Kp=2, Ki=1, actuator clamped to [0, 1.5]. Integral I accumulates e each sample.

keIu=2e+Iu appliedy
01.001.003.001.500.15
30.553.104.201.500.60
60.103.854.051.501.05
10−0.502.751.751.501.65
11−0.652.100.800.801.73
12−0.731.37−0.090.001.73
15−0.73−0.82−2.280.001.73

Read the metrics off it: saturation time is 12 samples (k=0–11), peak is 1.73 so overshoot is 73%, and the integral reached 3.85 while the actuator was pinned. That stored 3.85 is the windup, and it is why the output sits at 1.73 for four samples after the actuator unclamps. Settling time is long and the integral criterion is large; both trace to windup, not to the gains.

Failure modes and detection. Windup shows as saturation time high with integral large at exit: fix with back-calculation or conditional integration, and watch the integral-at-exit metric. Noise-driven actuator wear shows as high |C·S| with rising rate-limit time: add a derivative filter or lower crossover. Jitter shows as deadline misses with rising Ms in the sampled loop: check Ts against the closed-loop bandwidth. Nuisance trips show as interlock count rising while performance metrics stay flat: that is a threshold problem, not a tuning problem. Report each metric with its operating region and version, or drift will look like noise.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Design integral action for a biased process.

Answer

I'd start by pinning down the bias: constant load disturbance, model mismatch, or stiction? For a biased process, the integral term supplies the steady-state actuator output that proportional action cannot. Assume SISO, PI control, actuator saturates, sample time Δt.

Mechanism: at steady state, any nonzero error keeps changing the integrator, so the loop only settles when e=0. That is why integral action removes offset. The cost is phase lag: integral adds a pole at the origin, reducing phase margin and causing oscillation if Ti is too small.

Design: pick Ti relative to the dominant plant time constant τ. For a first-order-plus-dead-time process, a common starting point is Ti ≈ τ, then tune. If τ=10 s and dead time θ=1 s, Ti=10 s is a reasonable first guess. Ki = Kp/Ti. With Kp=2, Ki=0.2 s^-1. Sample at Δt ≤ Ti/10, so 1 s here. Discrete update: I[k] = I[k-1] + Ki*e[k]Δt; u = Kpe + I. Use velocity form for bumpless transfer.

Anti-windup: when the actuator saturates, error persists and I ramps. Three options:

methodmechanismwhen to usecost
clampinglimit I to [I_min, I_max] from actuator rangesimple loops, known limitstoo tight loses offset removal
conditional integrationfreeze I when u saturated and e drives further into saturationsetpoint steps, slow actuatorscan chatter without hysteresis
back-calculationI += KieΔt + (1/Tt)*(u_sat - u_unsat)*Δtdefault when limits knownneeds Tt tuning

For back-calculation, start with Tt = Ti for PI. It gives smooth recovery.

Failure modes: windup. Detect by I at clamp while u pinned and e same sign; symptom is overshoot and slow reversal, cost is off-spec product and valve wear. Reset bump on manual/auto: detect by Δu at transfer; initialize I = u_manual - Kp*e. Sensor loss: detect by bad quality or frozen measurement; freeze I and hold last output. Integral oscillation: detect by sustained oscillation that doesn't decay when Kp is reduced; lower Ki or add deadband. Unreachable setpoint: detect by u pinned at limit with constant e; that is windup, not offset removal.

Worked trace: Ki=0.5 per step, e=1 for 5 steps, u saturates at 1. No clamp: I = 0, 0.5, 1.0, 1.5, 2.0, 2.5. Clamp at I_max=1: I = 0, 0.5, 1.0, 1.0, 1.0, 1.0. Now e=-1. Unclamped I: 2.5→2.0→1.5→1.0→0.5→0.0, five steps. Clamped: 1.0→0.5→0.0, two steps. That is the windup cost in recovery time.

The test that catches most of this: drive the actuator into saturation for longer than Ti, reverse the setpoint, and measure recovery.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design derivative action without excessive noise or setpoint kick.

Answer

Assume a fixed sample time Ts, a first-order-plus-dead-time plant, and a PID you can implement in the standard form u = Kp(b r − y) + Ki∫(r−y)dt + Kd(c ṙ − ẏ). The answer: set c = 0 so derivative acts on measurement, filter it with a first-order low-pass whose time constant is Tf = Td/N with N between 8 and 20, and sample at Ts ≤ Td/10. That is the industrial default; everything else is tuning around it.

Derivative on error differentiates the setpoint. A step in r makes ṙ an impulse, so u jumps by Kd·Δr/Ts: the setpoint kick. Setting c = 0 removes r from the derivative path entirely; the term becomes −Kd ẏ, which is zero during a setpoint step because y has not moved yet. The cost is that derivative no longer anticipates setpoint changes, so you rely on proportional and integral for tracking. If you need some anticipation, use c between 0 and 1, not 1.

Filtering is not optional. Ideal derivative gain rises as Kd·ω, so broadband measurement noise is amplified without bound. A first-order filter Kd s/(1 + s Tf) rolls off above f_c = 1/(2π Tf) = N/(2π Td). At high frequency the gain flattens at Kd/Tf = Kd·N/Td, so noise gain is proportional to N. The price is phase lag: at loop crossover ω_c the filter contributes −arctan(ω_c Tf).

For Td = 1 s and ω_c = 1 rad/s:

NTf (s)f_c (Hz)phase lag at ω_chigh-freq gain
40.250.6414.0°4·Kd
100.101.595.7°10·Kd
200.053.182.9°20·Kd

Pick N as low as the phase margin allows. If you have 45° margin and the filter eats 15°, you are at 30° and will ring.

Python
# Python 3.12, fixed Ts
Ts, Td, N = 0.1, 1.0, 10.0   # Ts = Td/10
Tf = Td / N                   # 0.1 s
alpha = Tf / (Tf + Ts)        # 0.5
d_filt, y_prev = 0.0, 0.0

def d_on_measurement(y):
    global d_filt, y_prev
    dy = (y - y_prev) / Ts
    d_filt = alpha * d_filt + (1.0 - alpha) * dy
    y_prev = y
    return d_filt

Trace: setpoint steps 0→1 at t = 0, y stays 0 for one sample. dy = 0, d_filt = 0. No kick. With derivative on error, de = 1, de/Ts = 10, and d_filt jumps to 5 after one sample: a 5·Kd output spike.

Failure modes. Underfiltered (N too high or no filter): actuator chatter, valve packing wear, audible hiss, motor heating. Detect by FFT of u showing energy at sensor noise frequencies, or actuator current RMS. Cost: valve maintenance interval drops from years to months. Overfiltered (N too low): phase lag erodes margin. With Td = 1 s, N = 2 gives Tf = 0.5 s and 26.6° lag at ω_c = 1; step-response overshoot grows and disturbance rejection slows. Detect by step test overshoot and gain margin. Quantization: a 12-bit ADC on 0–10 V gives q = 2.44 mV. Raw derivative spike q/Ts = 24.4 mV/s; with Kd = 2 that is 49 mV on u: a visible limit cycle at the sample rate. Jitter: dividing by measured dt makes derivative gain vary with scheduling; use fixed Ts or a monotonic timestamp, and detect by correlating d_filt variance with CPU load. Dead time: if θ > Td, derivative predicts the wrong direction; drop it. Detect by oscillation near 1/(2θ).

Drop derivative entirely when the measurement is noisy flow or pressure, θ/Td > 1, Ts > Td/5, or PI already meets the spec. Alternatives: PI plus feedforward, a lead-lag compensator, a Kalman-filter derivative, or MPC if you have the model.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Shape setpoint response separately from disturbance rejection.

Answer

The short answer

A setpoint change enters at the reference input; a load disturbance enters after the controller, at the plant. The feedback path sets disturbance rejection and the stability margins; the reference path decides how the loop answers an operator. So shape them separately: when the tuning you need to reject disturbances makes every setpoint change slam the output, keep the tuning and change the reference path.

Why they decouple

ISA two-degree-of-freedom PID, with r = SP, y = PV, b and c the proportional and derivative setpoint weights, and a derivative filter of time constant Tf = Td / N:

u = Kp * [ (br - y) + (1/Ti) * int(r - y) dt + Td * (c * dr/dt - dy/dt) / (1 + Tfs) ]

Measurement to output: Kp * [ 1 + 1/(Tis) + Tds/(1 + Tfs) ] Reference to output: Kp * [ b + 1/(Tis) + c * Tds/(1 + Tfs) ]

C_fb contains no b and no c, so the loop transfer L = C_fb * P, the sensitivity S = 1/(1 + L), the margins and the disturbance rejection are all untouched; b and c move only T = C_ff * P / (1 + L). The integral still acts on the full error, so weights reshape a step but cannot make tracking faster than the closed-loop poles allow. Beyond two scalars, filter r.

Named cases: b = c = 1 is the plain 1-DOF PID; b = 1, c = 0 is PI-D, derivative on measurement only; b = 0, c = 0 is I-PD. MATLAB's pidstd2 exposes these as B and C; DCS and PLC PID blocks offer the same choice as derivative source = PV, or a setpoint lead-lag.

Worked numbers

Hypothetical loop: first-order-plus-dead-time plant, K = 2 %/%, tau = 30 s, theta = 5 s. Lambda tuning at lambda = 15 s gives Kp = tau / (K * (lambda + theta)) = 30/40 = 0.75, Ti = 30 s. Add Td = 8 s with N = 10, so Tf = 0.8 s.

A 10% setpoint step at b = c = 1 peaks the filtered derivative at Kp * Td * A / Tf = Kp * N * A = 0.75 * 10 * 10 = 75% of output at t = 0+, decaying with an 0.8 s time constant, on top of a 7.5% proportional step. That is derivative kick, and no load disturbance can match it: the derivative acts on a measurement, and a measurement cannot jump. Because the peak equals Kp * N * A, the filter is a second knob - N = 5 halves it to 37.5%.

  • c = 0 removes the 75% outright; b = 0.5 cuts the proportional step to 3.75%. Disturbance rejection does not move at all.
  • Ramp the setpoint over 30 s instead: dr/dt = 0.333 %/s, so the derivative settles at 0.75 * 8 * 0.333 = 2% of output, about 38x below the spike. Cost: the PV trails the SP for the whole ramp and the SP - PV alarm must allow for it.

Choosing between them

MechanismWhat it changesCostPick it when
Setpoint weights b, creference path only; one config line, no extra statestwo scalars; the integral still sees SP, so integral-driven overshoot staysthe loop is tuned right for disturbances and only SP steps are violent - try this first
Setpoint ramp, first-order or lead-lag filterthe whole reference trajectory; smooth actuator traveladds lag and a standing SP - PV error; alarm budgets changelarge operator moves, rate-limited or mechanically stressed actuators
Reference model or feedforwardthe tracking shape you chooseneeds an accurate model kept currentservo and high-performance loops where the two specs genuinely conflict

Failure modes

  • Derivative kick. Detect: trend OP and SP at 1 s - OP spikes when SP steps, not when PV moves. Cost: valve and pump wear per move, surge pressure, trips on OP limits. Fix: c = 0.
  • Windup on a long ramp. OP pins at its limit while the error stays one-signed and the integral charges. At Ki = Kp / Ti = 0.025 1/s, 60 s at an average 8% error stores 12% of output of charge and gives about that much overshoot when the PV arrives. Detect: OP at its limit for longer than Ti. Fix: back-calculation anti-windup with tracking time Tt = sqrt(Ti * Td) = sqrt(240) = 15.5 s.
  • A setpoint filter wired into the error instead of the reference: disturbance rejection slows too. Detect: step the load with the filter in and out - the peak must be identical.
  • A ramp or filter on a cascade secondary setpoint: the outer loop's output is the inner loop's SP, so filtering it spends inner-loop bandwidth. Detect: compare inner-loop crossover with and without.

The check that decides it: step the setpoint, then step the load, before and after the change. The disturbance trace stays the same to within noise; only the setpoint trace may move.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Commission feedback sign and direction safely.

Answer

What I'd say first

Assumptions: one flow loop. 0–100 L/min magnetic flowmeter on a 4–20 mA input, fail-closed control valve on a 4–20 mA output, PLC PID at a 100 ms sample. The process can absorb a 5% output step without tripping. If there's no headroom, no trip, or no manual mode, the plan changes.

The safe order is: prove the signal path in manual, prove actuator direction with a bounded step, prove plant sign and dead time from that same step, and only then close the loop at a gain low enough that a wrong sign saturates slowly instead of instantly.

1. Signal path, no actuator motion. Force the AO to 4.00 mA and 20.00 mA and read the flowmeter's raw counts at both. A 0–20 mA card driving a 4–20 mA valve leaves the valve shut until 20% command and shifts everything 25%: you see it as a dead band at the bottom of the range, not as a sign error.

2. Actuator direction, bounded. Step the output 0 → 5% in manual. Valve gain here is 1 L/min per % output, so expect +5 L/min. If flow falls, the valve is air-to-close or the AO is inverted.

3. Plant sign and dead time. Same step: nothing measurable for about 1 s (dead time θ), then 63% of the 5 L/min change within one time constant τ ≈ 3 s. If PV moves opposite to the command, the feedback sign is inverted: fix it in the controller's direct/reverse action or the wiring, never by negating the gain.

4. Close the loop. IMC PI: Kc = τ/(K(λ+θ)) with λ = θ = 1 s gives Kc = 3/(1×2) = 1.5 %/(L/min), Ti = τ = 3 s. Commission at a third of that: Kc = 0.5, Ti = 3 s, output clamped to ±10% around the operating point.

Why that gain is safe: with the correct sign the error decays with a ~2 s time constant. With the wrong sign, Δe = K·Kc·(Δt/Ti)·e / (1 − K·Kc) = 0.033·e per sample: 3.3% per sample, ~39% per second. A 5 s auto window therefore shows the error climbing monotonically and the output railing, while the clamp keeps the valve near where it started.

Failure modes and how each is caught

failuresymptomdetection
inverted feedbackerror grows monotonically, output rails5 s auto test at Kc = 0.5; error up ~3%/sample
inverted actuatorPV moves opposite the output step5% manual step, sign of ΔPV
0–20 vs 4–20 mAvalve dead below 20% commandraw mA read back at 0% and 100%
dead time mis-estimatedsustained oscillation, period ≈ 4θperiod of PV after a setpoint step
stictionPV flat for small Δu, then jumps1% steps, measure hysteresis

Alternatives, and when to pick them. Manual-only bump test: safest, use when the process tolerates no closed-loop excursion at all (exothermic reactor, no trip). Low-authority auto at a third of the IMC gain: the default above. Staged auto with gain scheduling: only once sign is proven and the loop is genuinely nonlinear.

Abort on PV past the trip, |ΔPV| > 10% per second, or the output railed for more than 2 s. Freeze the loop, capture the trend, and re-verify after any wiring, firmware, or scaling change: a re-flashed AO card can silently flip the 4–20/0–20 setting.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design timing for a digital PID loop.

Answer

Core answer. Assume a plant with dominant time constant τ and a target closed-loop bandwidth f_bw. Sample at Ts ≤ 1/(10·f_bw): 10× oversampling of crossover. For a 100 Hz loop that is Ts = 1 ms. Budget total loop latency (sensor + compute + actuator) under Ts/2 = 500 µs, and jitter under 5% of Ts = 50 µs. Run a fixed-period timer, but compute I and D from measured elapsed time, not the nominal period. Put an analog anti-alias filter at f_s/2 or lower ahead of the ADC.

Why the interval, not Nyquist. The zero-order hold adds phase lag of roughly 180°·f·Ts at frequency f. At 10× oversampling of a 100 Hz crossover that is 18°; at 5× it is 36°, which eats most of a 45° phase margin. Nyquist's 2× is a reconstruction limit, not a control limit: the loop closes on phase, so you pay for every degree the hold and the latency steal.

Why jitter corrupts D. The derivative term is D = Kd·Δe/Ts. A ±10% jitter in Ts is a ±10% error in derivative gain, and since Δe is small and noisy, that jitter is broadband noise multiplied by Kd/Ts. Using measured dt removes the gain error but injects dt noise straight into D, so clamp dt to [0.5·Ts, 2·Ts] and reject anything outside.

Why stale data breaks the loop. A sample timestamped older than one period means the controller acts on the past; the loop sees extra dead time, which is pure phase loss with no gain benefit. Reject samples older than Ts and count the rejects.

Fixed period vs event-driven vs measured dt.

schemeintervalstrengthcost
fixed periodicnominal Tspredictable, tunable, easy to reason aboutscheduler jitter, wasted CPU
event-drivenon each samplelowest latencyvariable dt breaks fixed gains
measured elapsedactual dtrobust to jitter and overrundt noise into D, needs clamp

Pick fixed-period for the schedule and measured dt for the gains: that is the combination that survives a real RTOS.

C
/* C11, monotonic clock */
static double last_t;
double now = monotonic_seconds();
double dt  = now - last_t;
if (dt < 0.5*Ts || dt > 2.0*Ts) { overrun_count++; return; } /* reject */
last_t = now;
double d = Kd * (e - e_prev) / dt;   /* measured dt, not nominal Ts */
integral += Ki * e * dt;
e_prev = e;

Failure modes and how you catch them.

  • Overrun: worst-case execution exceeds Ts. Symptom is growing phase lag and oscillation at crossover. Detect with a deadline-miss counter and a watchdog on the loop task.
  • Missing samples: the integrator keeps accumulating on stale error and winds up. Detect a timestamp gap greater than Ts and freeze the integral on that cycle.
  • Clock drift: a wall-clock jump makes dt negative or huge. Use a monotonic clock; the clamp above catches the rest.
  • Aliasing: unmodeled high-frequency content folds into the band and shows as a limit cycle. Detect by looking at the error spectrum, not just its RMS.

Test worst-case execution, scheduler interference, and a deliberately dropped sample before you trust the loop.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Make PID gains and sample time configuration safe.

Answer

Store gains in units that do not contain the sample time, and bind gains and Ts into one versioned record so neither moves alone: Kp (dimensionless), Ti and Td in seconds, Tf = Td/N in seconds. Derive every per-scan coefficient from Ts inside the controller. The gain set, Ts and Tf sit in one record with a CRC, and the controller refuses to start if the configured Ts differs from the one the record was tuned at. That is the whole fix: a coefficient with Ts already folded in belongs to exactly one sample time.

The backward-Euler form most code uses:

integral += Kp * (Ts / Ti) * e
d = (Tf/(Tf+Ts)) * d + (Kp*Td/(Tf+Ts)) * (e - e_prev)
u = Kp*e + integral + d

Firmware that precomputes ki_step = KpTs/Ti, a = Tf/(Tf+Ts), b = KpTd/(Tf+Ts) and stores them carries Ts invisibly inside those numbers. Same loop, Ts moved from 10 ms to 20 ms, coefficients untouched:

stored formexampleat 20 ms with 10 ms coefficients
Kp, Ti s, Td s, Tf sKp=2, Ti=0.5, Td=0.05, N=10unchanged; integral and derivative act at the same rate per second
Kp, Ki 1/s, Kd sKi=4, Kd=0.1unchanged
per-scan integral stepki_step = 0.04integral rate 4.0/s drops to 2.0/s; effective Ti becomes 1.0 s
stored filter pole and gaina = 0.333, b = 6.67derivative gain to a ramp doubles, 10 against the correct 5; filter constant 5 ms becomes 10 ms, corner 31.8 Hz becomes 15.9 Hz

Integral trace, Kp = 2, Ti = 0.5 s, e held at 1.0: at 10 ms, Ts/Ti = 0.02, Kp*(Ts/Ti) = 0.04 per scan and 100 scans/s, so 4.0 per second; at 20 ms, 0.08 per scan and 50 scans/s, so 4.0 per second, unchanged because Ti is in seconds. Carry ki_step = 0.04 across instead: 4.0 per second at 10 ms, 2.0 at 20 ms, and effective Ti = KpTs/ki_step = 20.02/0.04 = 1.0 s.

Derivative, Td = 0.05 s, N = 10 gives Tf = 0.005 s and a 31.8 Hz corner. At 10 ms, a = 0.005/0.015 = 0.333 and b = 0.1/0.015 = 6.67, so the gain to a ramp is b/(1-a) = 10, matching KpTd/Ts. The correct values at 20 ms are a = 0.2 and b = 4, gain 5; keeping the stored pair doubles derivative action and sets the implemented filter constant to aTs/(1-a) = 0.01 s, moving the corner to 15.9 Hz.

Jitter: passing measured elapsed time into Ts/Ti is what simple_pid does with sample_time=None. It tracks real time but turns timer jitter into integral-rate noise, so a 50% dt swing is a 50% integral-rate swing on that scan. Run from a fixed cyclic interrupt, and use measured dt only to reject scans whose dt leaves 20% of nominal, counting rejects.

def step(self, e, ts):
    # ts: nominal Ts on fixed-cycle firmware, measured elapsed time otherwise
    if not (0.8*self.Ts_nom <= ts <= 1.2*self.Ts_nom):
        self.rejects += 1
        return self.u_prev
    ki = self.Kp * (ts / self.Ti)
    a = self.Tf / (self.Tf + ts)
    b = self.Kp * self.Td / (self.Tf + ts)
    self.i = clamp(self.i + ki*e, self.i_min, self.i_max)
    self.d = a*self.d + b*(e - self.e_prev)
    self.e_prev = e
    self.u_prev = self.Kp*e + self.i + self.d
    return self.u_prev

Feed d from the measurement, not the error, to avoid derivative kick on setpoint steps.

Detecting the failures: editing the cycle time with stored coefficients shows as 30-50% overshoot or a slow ramp after the period change, caught by a startup assert that record Ts equals running Ts plus a CI step test at two Ts values. Reused filter coefficients show as output stepping or buzzing in steady state; log the standard deviation of u and the sign changes per second, both of which roughly double with a 2x derivative gain. Windup shows as 30-50% overshoot after long saturation; count consecutive scans with u at its limit and e above threshold, and trip back-calculation near 20. Jitter shows in a dt histogram; alert when p99 exceeds 1.2*Ts.

Trade-offs: pre-scaled coefficients save two multiplies per scan and are defensible only on fixed-cycle firmware that will never change Ts, with Ts in the same immutable record. Measured dt is right when the scheduler is not real-time and a nominal Ts would be a lie; clamp it and accept the gain noise. Do not do both, and check conversions with scipy.signal.cont2discrete((num, den), dt=Ts, method='bilinear') or MATLAB c2d(sys, Ts, 'tustin'), comparing discrete and continuous step responses at crossover. Sample at about 10x the closed-loop bandwidth: a 2 Hz loop wants Ts of 50 ms or less, below which (e - e_prev)/Ts amplifies encoder quantisation.

Ship gains and Ts as one blob, keep the previous blob for rollback, and make a cycle-time change with a non-matching blob fail to start.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Implement and test anti-windup.

Answer

The 90-second version

Windup is the integral term accumulating while the controller cannot act on the result: the output is pinned at a limit, the actuator is rate-limited, a downstream block has overridden it, or the loop is in manual. The integral is the only state that remembers past error, so it keeps integrating past the point where the output stopped moving. When the error reverses, the output has to spend that stored value before it comes off the limit, and the bill arrives as overshoot and a long recovery.

Assumptions I would state out loud: position-form PI, fixed sample time Ts, the controller knows the real output limits, and the actual actuator position is available to feed back.

Two mechanisms, one default. Conditional integration freezes the integral when the output is at a limit and the error still drives it further into that limit - so it can still unwind when the error reverses. Back-calculation is the better default because it also covers a rate-limited, overridden or dead actuator: compute the unsaturated output, clamp it, then add the difference to the integral through a tracking time Tt.

Python
# Python 3.11, position-form PI, fixed Ts
class PI:
    def __init__(self, kp, ki, ts, u_min, u_max, tt):
        self.kp, self.ki, self.ts = kp, ki, ts
        self.u_min, self.u_max, self.tt = u_min, u_max, tt
        self.i = 0.0

    def step(self, sp, pv, u_applied=None):
        e = sp - pv
        u_unsat = self.kp * e + self.i
        u = min(self.u_max, max(self.u_min, u_unsat))
        if u_applied is not None:   # rate limit, manual, downstream override
            u = u_applied
        self.i += self.ki * self.ts * e + (self.ts / self.tt) * (u - u_unsat)
        return u

Note what feeds back: the value that actually reached the plant, not the command the block computed. Feeding back the command hides exactly the override case you need to survive.

Why the tracking time works

With Kp = 2, Ki = 5 per second (so Ti = Kp/Ki = 0.4 s), Ts = 0.01 s, output range 0 to 100 percent, setpoint stepped 0 to 50. Error is 50 unit, P = 100, so the output is on the limit from the first sample. Assume the PV crosses the setpoint at 2.5 s and sits 4 units above it after.

t (s)eI, no anti-windupu, no AWI, Tt = Tiu, back-calc
0.05001000100
2.50625100100100
2.6-462110010092

The assumed PV path above is illustrative; the integrator arithmetic is not. Without anti-windup the integral grows at Kie = 250 units/s and reaches 625. The output only comes off the limit when I drops below 100 - P = 108, so 517 units must be shed at Ki|e| = 20 units/s: about 26 more seconds of the valve held wide open while the PV climbs.

Back-calculation pays down the excess every sample at (Ts/Tt)excess = 0.025excess, so the excess settles where Kie = excess/Tt, i.e. excess = TtKie = Kpe = 100. The unsaturated output never runs more than one proportional term past the limit, and at the 2.6 s sample I = 100 with P = -8 gives u_unsat = 92: the output leaves the limit at the zero crossing instead of half a minute later.

The same identity gives the disabled-actuator case for free. Force u_applied = 0 with e = 20 and the equilibrium is I + P = TtKie = Kpe, so I decays to 0 rather than growing at 100 units/s - re-enabling starts from the proportional term alone, no kick. Starting point for Tt: the rule of thumb in Astrom and Hagglund's PID literature is Tt = Ti for PI and Tt = sqrt(TiTd) for PID. Smaller Tt returns faster and can oscillate at the limit; larger approaches no anti-windup at all.

Testing

  1. Unreachable setpoint: step to 10x range for 10Ti. Assert the excess u_unsat - u_max settles at Kpe within a few percent after 5*Tt, and that the integral is bounded. On a real loop, assert the valve does not stay at the limit after the PV crosses the setpoint.
  2. Actuator dead: hold u_applied = 0 for 60 s at e = 20 and log I. Expect it to decay toward 0 with Tt = Ti; if it grows at 100 units/s the tracking path is not wired.
  3. Reversal under saturation: step the setpoint down while saturated and measure time from PV zero-crossing to the output leaving the limit. Expect roughly 0 to 2*Tt, and overshoot no worse than the unsaturated tuning gives.
  4. Rate limit and downstream override: repeat 1-3 with u_applied coming from the rate limiter or the override block.
  5. Bumpless manual-to-auto: preload via the same tracking input and assert the output step at the switch is within one sample of normal movement.

Two failure modes to check for. Too small a Tt snaps the output off the limit and limit-cycles around it - look for oscillation with a period near 2*Tt in the output trace, not in the PV. And a test that uses a noisy PV to 'prove' windup is testing the wrong thing: measurement noise is handled by the derivative filter, so such a test passes with no anti-windup present.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design manual-to-automatic and restart transitions.

Answer

Assumptions: single-loop positional PID in a PLC or DCS, 100 ms scan, output 0–100% to a control valve, derivative taken on measurement.

Core answer (first 90 seconds). Bumpless transfer means the controller's internal state is made consistent with the actual output before it takes authority, so the output does not step. Three things have to line up: the integral term, the derivative history, and the setpoint.

The integral term is the one that bites. In positional form:

u = Kp*e + I + Kd*(PV_prev - PV)/Ts

While in manual, every scan you back-calculate I = u_manual - Kp*e - Kd*(PV_prev - PV)/Ts. The instant you switch to auto, u = u_manual exactly: zero bump.

Concrete: Kp = 2, error = 3%, steady so D = 0, operator's manual output = 42%. Back-calculated I = 42 - 6 = 36%. On auto, u = 6 + 36 = 42%. No step. If you instead left I at a stale 20%, u = 6 + 20 = 26%: a 16% step. On a 100 mm valve stroke that is 16 mm, and at a 2%/s actuator that is an 8-second slew the process sees as a disturbance.

Derivative: seed PV_prev = current PV on the takeover scan, otherwise the first scan computes D from a zero or stale PV and spikes.

Setpoint: in manual, track SP to PV (or hold the operator's SP deliberately). If SP sits at 60% while PV is 40%, auto starts with e = 20%, P = 40%: an immediate swing.

Cascade. The primary's output is the secondary's setpoint. When the secondary is in manual, the primary must back-calculate its integral so its output equals the secondary's actual setpoint, not its own last computed value.

Restart. On power-up, drive the output to a configured safe value: often the last value from non-volatile memory, or a preset (0% for a fuel valve). Preload I to match, then ramp to the auto value at a configured rate, e.g. 5%/s.

Trade-offs. Integral tracking is bumpless but inherits whatever the operator did in manual, if they parked the valve somewhere bad, auto starts there and corrects slowly. Ramping the output or setpoint limits the rate of change; it protects a sensitive process but adds lag and can fight the controller. Hard takeover (no tracking) is only acceptable when the manual and auto values are already close. Bumpless schemes are not worth it on bang-bang loops or fixed-speed actuators: there is no continuous output to bump.

Failure modes and detection.

  • Stale manual value: commanded 42% but valve feedback says 10%. Detect by comparing command vs. position feedback; alarm if |cmd - actual| > 5% for > 2 s. Track actual, not commanded.
  • Saturated output / windup: output pinned at 100% with error the same sign for many scans. Detect output-at-limit AND error sign; fix with integral clamping or back-calculation.
  • Sensor failure: PV out of 4–20 mA range, frozen, or rate-of-change beyond a threshold. On bad PV, hold output, freeze I, alarm.
  • Rapid toggling: repeated auto/manual flips cause repeated bumps. Detect transition count in a window; enforce a minimum dwell (e.g. 2 s).
  • Restart bump: output resets to 0 then jumps to 42%. Detect by comparing restart output to last known; ramp instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Specify output, rate, and operating-envelope constraints.

Answer

I'd pin the axis before quoting a single limit, because "output, rate, envelope" means nothing until the hardware is fixed. Take a 48 V BLDC joint on field-oriented control, 50:1 harmonic drive, motor Kt = 0.09 N·m/A, 19-bit absolute encoder, winding NTC, DC-bus monitor. All limits joint-side, SI.

The answer is three clamps applied in this order (magnitude, then rate, then acceleration) because each one changes what the next sees. Magnitude: position ±2.967 rad (±170°) soft, ±3.054 rad (±175°) on independent hard switches; torque 90 N·m peak at 20 A, 36 N·m continuous at 8 A. Rate: 3.142 rad/s (180°/s). Acceleration: 15.71 rad/s² (900°/s²). Envelope: winding ≤155 °C (class F), bus 42–58 V, ambient ≤40 °C.

Here's the shaper and a trace through it.

Python
# joint-side SI, dt = 1 ms control period
POS_MIN, POS_MAX = -2.967, 2.967      # rad
VEL_MAX, ACC_MAX = 3.142, 15.71       # rad/s, rad/s^2
TAU_MAX          = 90.0               # N*m

def shape(q_cmd, q, v, dt=1e-3):
    q_cmd = min(max(q_cmd, POS_MIN), POS_MAX)              # 1 magnitude
    v_cmd = min(max((q_cmd - q)/dt, -VEL_MAX), VEL_MAX)    # 2 rate
    a_cmd = min(max((v_cmd - v)/dt, -ACC_MAX), ACC_MAX)    # 3 accel
    return q + v_cmd*dt, v_cmd, a_cmd

Call it with q = 0, v = 0, q_cmd = 3.5 rad. Step 1 clamps 3.5 to 2.967. Step 2 computes (2.967 − 0)/0.001 = 2967 rad/s and clamps to 3.142. Step 3 computes (3.142 − 0)/0.001 = 3142 rad/s² and clamps to 15.71. It returns q = 0.003142 rad, v = 3.142 rad/s, a = 15.71 rad/s². Both the rate and the acceleration clamp bind; the position clamp already fired.

That trace is why anti-windup has to be gated on torque, not on position error. The error here is 2.967 rad, huge, but the actuator is not saturated; it is tracking 15.71 rad/s² exactly. An integrator gated on position error winds up and overshoots. Gate it on applied torque instead: freeze the integrator when |tau_applied| ≥ 0.98·TAU_MAX and back-calculate with a tracking time constant of 0.05 s. The rate limiter sits upstream of the current loop, so it never trips anti-windup; only the torque clamp does.

For an unreachable setpoint you have three options, and the choice is about who owns the command. Reject with an error when a supervisor issues a move: the caller must know it was refused. Clamp and flag "limited" when a teleop stream is arriving at 100 Hz, because dropping a frame is worse than lagging. Shape a jerk-limited S-curve when you own the planner, which keeps the rate limiter from ever binding and leaves the integrator alone. Clamping silently is the one to avoid: the caller sees a position that never arrives and no reason why.

Failure modes, with what trips them:

failuredetectioncost
stall|v| < 0.087 rad/s with |I| ≥ 18 A for 200 ms20 A into a stalled winding heats at ~6× the continuous I²t rate
thermal deratingNTC rise > 0.5 °C/scontinuous torque 36 → 25 N·m; trip at 155 °C
rapid reversalbus > 58 V on the DC-bus monitorregen has nowhere to go; brake chopper or trip
supply deratingbus < 42 Vpeak current derated; torque shortfall at speed shows as current-loop saturation with the bus flag set
downstream overridecommanded vs applied torque differ > 3 cyclesSTO opened; drive must report "disabled", not "at setpoint"

After any trip, require an explicit clear and a re-home before motion resumes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Add feedforward to a feedback loop.

Answer

Core answer

Feedforward acts on a disturbance before it reaches the output; feedback only acts after it already has. So the honest framing is: feedforward never replaces feedback. It removes the bulk of a measurable disturbance so the PID has less to correct.

Take a tank heater holding outlet temperature at 80 °C by commanding a steam valve, 0–100% opening, gain 1.5 kW per percent. Inlet flow and inlet temperature are measured upstream. The steady-state energy balance gives the feedforward law:

u_ff = F · c_p · (T_sp − T_in) / K, c_p = 4.18 kJ/(kg·K)

At F = 0.5 kg/s and T_in = 20 °C: u_ff = 0.5 × 4.18 × 60 / 1.5 = 83.6%. The PID now only trims model error, so its output sits near zero at steady state.

Sum point: u = clamp(u_ff + u_fb, 0, 100), with the PID integrator frozen or back-calculated while the clamp is active. Summing the feedforward into the error instead of the controller output makes the integrator fight it. If the disturbance path has different dynamics from the control path, the static gain is not enough: use G_ff(s) = −G_d(s)/G_p(s), which for a first-order plant plus dead time is a static gain with a lead-lag.

Worked disturbance

Numbers below come from a first-order model of this plant (40 s time constant, 8 s valve-to-sensor dead time), not field data.

Inlet flow steps 0.5 → 0.7 kg/s at t = 0. Required heat becomes 0.7 × 4.18 × 60 = 175.6 kW, so u_ff = 117%: past the valve limit. The valve pins at 100%, the loop saturates, and T_out sags until flow returns or the setpoint is relaxed. That is the failure feedforward exposes: it will happily command outside the actuator's range.

Keep the step inside range instead: 0.5 → 0.58 kg/s gives u_ff = 0.58 × 4.18 × 60 / 1.5 = 97%. The valve moves at t = 0 and the outlet excursion is bounded by model error, roughly 1 °C in the model, against the 3–5 °C the feedback loop alone produces while it waits out the 8 s dead time.

Failure modes and detection

failuresymptomdetection
gain error (c_p or K off by 20%)persistent offset the integrator absorbsu_fb / u_total > 20% at steady state
dead-time mismatchcorrection arrives before or after the disturbancestep test with feedforward only, compare against model
stale or missing FF inputFF holds last value or drops to zerowatchdog on the flow transmitter; > 2 s stale → feedback-only, retune PID
operating point changevalve authority shifts, gain no longer linearschedule K against valve position; re-identify after a setpoint change
saturationvalve at limit, integrator winds upclamp plus back-calculation; alarm on valve at limit with nonzero error > 30 s

When not to use it

If the disturbance cannot be measured, or the measurement lags longer than the feedback loop's own settling time, feedforward adds mistimed actuation and noise. And because it is open loop, it never removes steady-state error by itself: any model bias lands on the integrator.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design and tune a cascade control system.

Answer

What I'd say first

Cascade pays off when a disturbance enters the process before it reaches the variable you actually care about. You add a secondary measurement close to the actuator, close a fast inner loop on it, and let the outer loop on the primary variable write the inner loop's setpoint instead of touching the valve.

Concretely: a jacketed reactor. Primary = reactor temperature (what decides yield). Secondary = jacket temperature. Actuator = steam valve. A header-pressure swing hits the jacket in seconds; the reactor's thermal mass means it would take minutes to show. Single-loop control on reactor temperature only sees the upset after it has already propagated.

Assumptions and numbers

  • The inner loop must be 3–10× faster than the outer. Below ~3× the two loops fight and you get interaction; above ~10× you are usually paying for a sensor you do not need.
  • Here: jacket loop closed-loop time constant ≈ 10 s, reactor loop ≈ 200 s → ratio 20×, comfortably inside.
  • Controller form: PI on both. Derivative on a noisy jacket thermocouple just amplifies noise, and the inner loop is fast enough that D buys little.

Tuning order

  1. Outer in manual: hold the jacket setpoint fixed. Step the steam valve, fit FOPDT to jacket temperature, tune the inner PI (IMC or Ziegler-Nichols).
  2. Close the inner loop. Step the outer setpoint (reactor temp). The inner loop now looks like a near-unity-gain, small-lag element to the outer loop. Fit that apparent model, tune the outer PI.
  3. Never tune the outer first: its response is dominated by the inner loop's dynamics, so you would be tuning against a plant that changes the moment you close the inner loop.

Worked trace: header pressure step

Steam header drops 0.2 bar; jacket temperature starts falling at ~0.5 °C/s.

  • Single loop: reactor temp does not move measurably for ~60 s (thermal lag). The controller reacts at t≈60 s, the valve opens, and reactor temp dips ~1.5 °C before recovering.
  • Cascade: the jacket sensor sees the drop within one scan (~1 s). The inner PI opens the valve, jacket temp recovers in ~30 s. Reactor temp excursion stays under ~0.2 °C.

That roughly 7× reduction in primary-variable excursion is the whole point.

Limits, anti-windup, modes

The outer output is clamped to jacket setpoint limits (say 20–150 °C). When the valve saturates fully open the inner loop cannot follow, so the outer integrator must stop: back-calculation or conditional integration. On inner sensor failure or manual mode, the outer loop tracks the actual jacket setpoint so the transfer back is bumpless.

Failure modes

  • Inner sensor drift or failure: the outer loop drives to a wrong jacket temp. Detect by comparing jacket temp against a valve-position model; on mismatch, fall back to single-loop on reactor temp.
  • Inner loop too slow (fouled jacket, stuck valve): the ratio collapses, the loops interact, and you get oscillation. Detect by watching inner closed-loop settling time; if it exceeds ~1/3 of the outer, retune or abandon cascade.
  • Outer windup during saturation: reactor temp overshoots on recovery. Detect by inspecting the integrator value at saturation.

When not to use it

Cascade costs an extra transmitter, an extra controller block, and ongoing tuning. Skip it when the secondary measurement is noisy or has dead time comparable to the primary, when the disturbance is not local to the actuator, or when a single loop already holds the primary variable inside spec. The decision hinges on one question: is there a fast, measurable variable sitting between the disturbance and the thing you care about?

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Migrate a PID tune between controller implementations.

Answer

Core answer (first 90 seconds)

Ask which two implementations and what the loop does before touching numbers. A tune is not a set of numbers: it is numbers plus the form that gives them meaning. Convert through the canonical form, verify with a component trace, then stage bounded hardware tests.

Assumptions I'd state out loud: source is a continuous-form PID with gains (Kp, Ki, Kd) in engineering units; target is a discrete implementation at a different sample time, with a filtered derivative and back-calculation anti-windup. Change either assumption and the conversion changes.

The conversion

Independent (parallel)Standard / ISA
outputu = Kp·e + Ki∫e dt + Kd·de/dtu = Kc(e + (1/Ti)∫e dt + Td·de/dt)
mapping—Kp = Kc, Ki = Kc/Ti, Kd = Kc·Td

Worked: Kc = 2.0, Ti = 10 s, Td = 2 s → Kp = 2.0, Ki = 0.2 s⁻¹, Kd = 4.0 s.

Four things break when you copy those numbers across.

Integral units. If the target accumulates per sample rather than per second, the per-sample gain is Ki·Δt. At Δt = 0.1 s that is 0.02, not 0.2. Copying 0.2 gives 10× the integral action and a loop that cycles instead of settling.

Derivative filter. A first-order filter with N = 10 puts the corner at Tf = Td/N = 0.2 s, about 0.8 Hz. Above that the D term rolls off, so the target has less high-frequency damping than the source. Either raise Kd or accept slower recovery from fast disturbances.

Derivative on error vs measurement. On a 10-unit setpoint step at Δt = 0.1 s, derivative-on-error produces a kick of Kd·ΔSP/Δt = 4.0 × 100 = 400 output units: the output saturates instantly. Derivative-on-measurement removes it. Check which the target does.

Anti-windup and mode tracking. Back-calculation unwinds the integral with time constant Tt; conditional integration sheds it in one sample once the error reverses. If the target has no back-calculation and the source did, recovery from a long saturation is seconds slower. Mode tracking: if the target does not preload the integral to the current output on manual→auto, a loop held at 2 units of error for 30 s steps its output by Ki·e·t = 0.2 × 2 × 30 = 12 units at the transfer.

Also check direct/reverse action (a sign flip turns negative feedback into positive) and output scaling (0–100 % vs engineering units). Both are one-line checks that produce a runaway loop if missed.

Verification

Simulate both against the same plant model and the same setpoint/disturbance sequence, then diff the traces: output, P/I/D components, and integral state. A component trace localises a mismatch to one term in seconds; a closed-loop response alone does not. Then bounded hardware tests (setpoint step, load disturbance, saturation excursion, manual/auto transfer) with the old tune loaded and a rollback path.

Trade-offs

Converting is right when the plant is unchanged and you trust the source tune. If the plant or actuator changed, or the source tune was marginal, re-identify and retune instead: a converted marginal tune is still marginal. Simulation comparison is enough to skip hardware tests only when the target's discretisation and anti-windup match the source's; if either differs, the difference shows up on hardware, not in the model.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Control a process with substantial dead time.

Answer

Assume a self-regulating SISO process, first-order plus dead time: G(s)=K e^{-θs}/(τs+1). "Substantial" means θ/τ > 1. The core answer: you cannot make the loop faster than the dead time. Dead time adds phase lag -ωθ. At crossover, that lag eats phase margin. For a PI controller with integral time set to τ, phase margin is 45° when ωθ = π/4. So closed-loop bandwidth is about π/(4θ), time constant ~1.3θ, 2% settling ~5θ. If θ=30 s, expect ~150 s minimum. Any tuning that promises faster will oscillate.

Identify θ and τ from a step test: θ is the time from step to first measurable PV change; τ is the time to reach 63% of the final change after that. Do this at several operating points because θ often changes with flow or speed.

Use SIMC PI: Kc = τ/(K(λ+θ)), Ti = τ. For robust λ=θ, Kc = τ/(2Kθ). Example: θ=30 s, τ=10 s, K=2. Kc = 10/(2230)=0.083, Ti=10 s. Sample at T_s ≤ θ/10 = 3 s. Add anti-windup: back-calculation with T_t = sqrt(Ti*T_s) ≈ 5.5 s, or conditional integration. Skip derivative: it adds noise and little phase lead when θ/τ > 1.

If no model, relay feedback: relay amplitude d=5%, oscillation amplitude a=10% gives Ku = 4d/(πa) = 0.64. Ultimate period Pu from zero crossings. ZN PI would give Kc=0.45*0.64=0.29, Ti=Pu/1.2. That is 3.5x the SIMC gain and will oscillate on a θ/τ=3 process.

Smith predictor removes the modelled delay from the feedback path: controller sees G_m without e^{-θ_m s}. It recovers phase margin, so you can raise Kc. But it is a model-based cancellation. If actual delay exceeds model by Δθ, the error e^{-θs} - e^{-θ_m s} adds phase -ωΔθ. With bandwidth ω≈π/(4θ), Δθ=θ/2 eats ~22° of phase margin. Δθ=θ likely oscillates. Detection: sustained oscillation at a period near 2(θ+τ) after a setpoint step. Fix: reduce Kc by the ratio θ_m/θ_actual, or switch to conservative PI.

MPC handles constraints and multivariable dead time, but needs a model and compute. Use it when you have measurable disturbances, constraints, and a validated model. Feedforward if disturbance is measurable: G_ff = -G_d/G_p, but dead time must be matched. Setpoint shaping: ramp the setpoint over θ to avoid overshoot.

Windup during long transport delays: if valve saturates for 3θ, integral accumulates 3x normal. When PV finally moves, overshoot >20%. Detect by controller output pinned at limit for >θ. Fix anti-windup. Delay uncertainty: if transport time changes (e.g., conveyor speed), retune or schedule gain. Dropout: if sensor drops for >θ, hold last value and freeze integrator.

ApproachWhenCost
PI with SIMCθ/τ > 1, model uncertainsimple, robust, slow
Smith predictorθ/τ > 1, model accuratefast, sensitive to delay error
MPCmultivariable, constraintsmodel + compute

If θ/τ > 1 and model is poor, plain conservative PI with anti-windup is the right answer. If model is accurate and delay dominates, Smith predictor. If constraints and multivariable, MPC.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Define control performance acceptance criteria.

Answer

Short answer. Acceptance criteria are the numbers you sign off before the machine ships. A number on its own means nothing, so I fix the operating point and the test signal first: a 400 W servo axis, 10:1 gearbox, 0.002 kg·m² reflected inertia, Kt = 0.5 N·m/A, 10 A drive peak; 8 kHz current loop, 1 kHz position loop; 4096 counts/rev encoder on the motor. Then I sign off a table. The figures are for that axis: a worked example, not a spec sheet; the structure is what transfers.

CriterionTest signalThresholdHow measured
Steady-state tracking error1 rev/s ramp≤ 0.03 rev (123 counts)mean error over the last 0.5 s
Settling time0.1 rev step≤ 120 ms to ±2%time to enter and stay in the band
Overshoot0.1 rev step≤ 5%peak minus final value
Disturbance recovery2 N·m step at the motor shaftback inside ±2% within 150 mserror envelope after the step
Actuator effortworst-case move≤ 10 A peak, ≤ 6 A rms over the movecurrent log
Saturation timeworst-case move≤ 50 mstime spent at the current limit
Stability marginsswept-sine injectionGM ≥ 6 dB, PM ≥ 45°Bode from the sweep
Noise sensitivityencoder at resttorque ripple ≤ 2% of ratedFFT of the torque command

Why those numbers. The settling band comes from the next operation, not the controller: 2% versus 5% is a real cycle-time difference on a pick-and-place. Saturation time matters because while current is clamped the loop is effectively open: the integrator keeps accumulating, so the longer it saturates the more overshoot appears on release. Margins matter because delay and gain variation eat phase; PM sets closed-loop damping, and 45° is the floor I'd accept, 60° is comfortable.

Worked check. Tuning ζ = 0.7, ω_n = 50 rad/s (8 Hz), type-1 position loop:

  • Overshoot Mp = exp(−πζ/√(1−ζ²)) = exp(−2.199/0.714) = 0.046 → 4.6%, inside the 5% band.
  • 2% settling t_s ≈ 4/(ζω_n) = 4/35 = 114 ms, inside 120 ms, but only 5% margin.
  • Peak time t_p = π/(ω_n√(1−ζ²)) = 3.142/35.7 = 88 ms.
  • Ramp error: Kv = ω_n/(2ζ) = 35.7 s⁻¹, so a 1 rev/s ramp leaves e_ss = 1/35.7 = 0.028 rev = 115 counts, inside the 123-count limit.
  • Current: peak acceleration is ω_n² × step = 2500 × 0.628 = 1571 rad/s², so peak torque is 0.002 × 1571 = 3.1 N·m and peak current 3.1/0.5 = 6.3 A. Inside the 10 A peak, so the step size and the bandwidth are jointly feasible.

Failure modes and detection. Integrator windup: after a large step the current clamps at 10 A, the integrator keeps growing, and release gives 20–30% overshoot. Detected by comparing commanded to measured current and by overshoot breaking the band; fixed with an anti-windup clamp. Encoder quantization plus D gain: one count at 4096 counts/rev differentiated at 1 kHz is a 1.5 rad/s velocity step, which shows up as torque ripple in the FFT of the torque command. Mechanical resonance: a gearbox mode near crossover produces a limit cycle at that frequency. Audible whine, FFT peak. Delay growth with load erodes PM and shows as overshoot that grows with load.

Trade-offs. Tightening settling raises bandwidth, which raises noise sensitivity and actuator heating. Peak acceleration scales with ω_n², so halving settling time quadruples peak current: this axis would need 25 A to settle in 57 ms, well past the drive. Pick thresholds from the machine's cycle time and thermal budget, not from the best the controller can do.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Use gain and phase margins in controller validation.

Answer

If I'm validating a controller, I treat gain and phase margins as a budget, not a pass/fail badge. Assume a linearized SISO loop L(s)=C(s)P(s) at a stated operating point, and that the dominant uncertainties are loop gain and loop delay. Then the margins answer two questions: how much gain can rise before the Nyquist plot reaches -1, and how much extra phase (usually delay) can appear at gain crossover before it does.

Mechanism. Phase margin is 180° plus the phase of L at the gain crossover frequency ω_c. For a dominant second-order pair, PM is roughly 100ζ degrees for ζ below about 0.7, so 45° corresponds to ζ≈0.4-0.45 and roughly 20-25% overshoot on a step; 60° is closer to ζ≈0.6 and about 10% overshoot. Gain margin is the factor by which gain can increase before |L|=1 at the phase crossover; 6 dB is a factor of 2. Delay eats phase linearly: an extra delay τ adds -ωτ radians. So delay margin is PM_rad/ω_c. If PM=45° (0.785 rad) and ω_c=10 rad/s, τ_max=78.5 ms. A 20 ms sensor-plus-compute delay leaves 58.5 ms. That is the number I'd put in the validation report, not just “PM=45°”.

Sensitivity. S=1/(1+L) and T=L/(1+L). The peak Ms=max|S| is the worst disturbance amplification; Ms=2 (6 dB) means a disturbance at that frequency comes out twice as large. Common targets and what they bound:

QuantityTypical targetWhat it bounds
PM45-60°delay margin = PM_rad/ω_c; damping
GM6-10 dBgain increase before phase crossover
Ms<2 (6 dB)worst disturbance amplification
Mt<1.5noise amplification at crossover

These are rules of thumb, not laws. If the plant has a resonant peak near crossover, a healthy PM can still hide a large Ms and a lightly damped ringing mode.

Alternatives. Separate GM/PM are cheap and interpretable, but they vary one quantity at a time. Disk margin computes the largest Nyquist disk that avoids -1 and gives a simultaneous gain/phase guarantee; it is more conservative and better when gain and phase drift together. Monte Carlo over parameter distributions gives a violation probability but no guarantee, and μ-analysis handles structured uncertainty at the cost of a model and weighting functions. I'd use GM/PM plus delay margin for a first pass, disk margin when the uncertainty is coupled, and Monte Carlo to check the tails.

Failure modes. Gain-scheduled loops can be stable at every grid point and unstable between them; detect by sweeping the schedule and linearizing at intermediate points, or by a slow ramp in time domain. Actuator saturation or stiction can produce limit cycles that linear margins never see; detect as a sustained oscillation whose amplitude grows with command. A firmware change that adds 10 ms of delay can consume a delay margin that was already thin. Noise and quantization can be amplified by a high-bandwidth crossover; check the measured noise spectrum at the actuator.

Validation sequence: measure or identify the loop at each operating point, compute ω_c, PM, GM, Ms, Mt, and delay margin; compare against the budget; then run step, disturbance, and saturation tests. If the model and measurement disagree by more than a few dB near crossover, fix the model before trusting the margins.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Plan a safe controller identification and auto-tuning procedure.

Answer

What I'd say first

Auto-tuning is a live-plant experiment, so I plan it like one: fix the safe envelope, excite, identify, tune conservatively, validate in stages, keep a rollback. The order is forced: you can't choose an excitation amplitude until you know the noise band and the alarm limits, and you can't choose gains until you know the dead time.

Preconditions

Loop in manual (or the tuning tool's output disabled), plant at steady state, no cascade master driving the setpoint, no override/selector or feedforward active, and no other controller fighting for the same final element. Operator on standby with a manual abort. Confirm the final element actually moves: a sticking valve poisons the whole test.

Excitation

A step test gives a full model; a relay test gives only ultimate gain and period but keeps the PV bounded, which matters when the loop is near a quality limit. Step amplitude: pick ΔOP so the PV excursion is 3–5× the PV noise band (2σ) yet stays inside the alarm limit with margin. If the noise band is 0.5 °C and the high alarm is 140 °C, a step that swings the PV 18 °C is too much: cut the amplitude or move the operating point.

Identification

Fit first-order-plus-dead-time: K = ΔPV/ΔOP, θ from the delay before the PV moves, τ from the 63 % point. Worked: OP 50 → 55 %, PV 120 → 138 °C. K = 18/5 = 3.6 °C/%. The PV reaches 63 % of 18 = 11.3 °C at t = θ + τ; if that lands at 140 s and the PV first moves at 20 s, then θ = 20 s and τ = 120 s.

Tuning

ruleKcτicharacter
ZN open-loop1.2τ/(Kθ) = 2.02θ = 40 saggressive, ~quarter-amplitude decay
IMC, λ = θτ/(K(λ+θ)) = 0.83τ = 120 sdetuned; robustness set by λ

IMC wins when dead time is uncertain: λ ≥ θ keeps the loop stable under roughly a 30 % error in θ. ZN is fine for a fast, forgiving loop where you want the tightest response.

Validation

Close the loop at the IMC gains, apply a setpoint step of a few percent, check overshoot under ~10 % and settling within about 3τ. Then let a real disturbance hit it. Only then hand back.

Failure modes

  • Sticking valve: the OP–PV plot shows a deadband then a jump. Detect by hysteresis on a repeat step. Cost: a wrong K and a loop that oscillates at the stick-slip frequency.
  • Disturbance mid-test: the K estimate drifts. Detect by non-repeatable step responses; re-run.
  • Integrator loop (level): the step never settles. Use a relay test or a different method.
  • Abort: PV crosses the alarm, OP saturates, or rate exceeds its limit. Roll back to the tune you saved before starting.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate gain scheduling.

Answer

Core answer (first 90 seconds). Gain scheduling is for a plant whose dynamics change with a measurable variable: airspeed, engine speed, Mach, dynamic pressure. You pick that variable as the scheduling variable, split its range into regions, design a linear controller in each region, and interpolate the gains between region centers. The assumption that makes it work is quasi-static: the scheduling variable moves slowly compared with the closed-loop bandwidth, so at any instant the plant looks like the linear model you tuned against.

Concretely: (1) choose a scheduling variable that correlates with the dominant dynamics and is measured reliably; (2) partition its range into overlapping regions; (3) tune one controller per region, same structure and units; (4) interpolate gains linearly across the overlap; (5) validate at design points and, critically, at intermediate points.

Why interpolation can destabilize. Each local controller stabilizes the plant at its design point. But stability is not preserved under a convex combination of controller coefficients: the closed-loop characteristic polynomial depends nonlinearly on the gains, so a blend of two stabilizing controllers can put closed-loop poles in the right half-plane at an intermediate operating point. That is why you validate between regions, not just at them.

Alternatives. LPV synthesis treats the scheduling variable as a formal parameter and produces one controller with a stability guarantee across the range; it needs a parametric model and is heavier to design. A single robust controller (H∞, μ) works when dynamics vary little; it avoids scheduling logic but is conservative. Use gain scheduling when the variable is measurable, dynamics vary widely, and a robust controller would cost too much performance. Avoid it when the variable is noisy or unavailable, or when variation is small.

Worked example (figures illustrative). Aircraft longitudinal control, scheduling variable calibrated airspeed, 100–300 kn. Three regions with ~10 kn overlap (~14% of a 70 kn span):

RegionAirspeed (kn)KpKiKd
1100–1701.20.50.10
2160–2400.80.30.05
3230–3000.50.20.02

Design points at region centers 135, 200, 265 kn. Interpolation linear on airspeed:

Python
# regions: (v_min, v_max, gains), sorted by v_min, adjacent regions overlap
regions = [
    (100, 170, (1.2, 0.5, 0.10)),
    (160, 240, (0.8, 0.3, 0.05)),
    (230, 300, (0.5, 0.2, 0.02)),
]

def gains_at(v, regions):
    if v <= regions[0][0]:
        return regions[0][2]
    if v >= regions[-1][1]:
        return regions[-1][2]
    for (lo1, hi1, g1), (lo2, hi2, g2) in zip(regions, regions[1:]):
        if lo2 <= v <= hi1:          # inside the overlap
            a = (v - lo2) / (hi1 - lo2)
            return tuple((1 - a) * x + a * y for x, y in zip(g1, g2))
    for lo, hi, g in regions:        # inside a single region, no overlap
        if lo <= v <= hi:
            return g
    return regions[-1][2]

Trace: at 165 kn (overlap center) the code returns 0.5·(1.2, 0.5, 0.10) + 0.5·(0.8, 0.3, 0.05) = (1.00, 0.40, 0.075). At 145 kn it falls through to region 1, (1.2, 0.5, 0.10). At 290 kn it clamps to region 3, (0.5, 0.2, 0.02).

Validation. At design points and overlap centers (135, 165, 200, 235, 265 kn): step response, gain margin > 6 dB, phase margin > 45°, settling < 2 s, overshoot < 10%. Between regions: slow and fast transitions, watch for limit cycles. Hysteresis: inject noise near boundaries. Sensor fault: inject stuck/zero/rate faults. Fallback: verify the safe tune. python-control's margin and step_response, or MATLAB margin/step, give the margins directly.

Failure modes. Sensor fault reads zero or sticks: cross-check redundant sensors and rate of change, fall back to a conservative tune. Rapid traversal (airspeed changing faster than the loop can track, e.g. >50 kn/s) breaks the quasi-static assumption: rate-limit the scheduling variable or switch to a robust controller. Noisy variable causes chattering at boundaries: low-pass filter (cutoff ~1 Hz) plus hysteresis. Out-of-range variable: clamp to endpoint gains. Hysteresis deadband: switch only after crossing the boundary by a margin, e.g. 5% of region width.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design controller behavior for sensor timeout and bad quality.

Answer

Clarify first: is this a regulatory PID loop, a safety function, or a monitoring tag? I'll assume a 100 ms control task reading a fieldbus pressure transmitter for a PID loop, with a separate safety function if the hazard is high. The answer: a timeout or bad-quality flag makes the measurement invalid, not zero. The controller must stop treating it as process evidence, bound its output, and enter a designed degraded mode.

Mechanism. In a PID, the integral term accumulates error e = SP - PV every scan. If PV is stale, e stays nonzero and the integral winds until the output saturates. Derivative on measurement sees zero change, so it decays to zero, but that is not a safe substitute for freezing it. So on invalid quality: freeze the derivative (set D=0 or hold last valid derivative), stop integral accumulation, and hold or ramp the output. If you must unwind integral, do it at a bounded rate, e.g. 1% output per second, and clamp the integral term to the output limits (anti-windup). Bumpless return: when quality returns, do not let the PID jump. Initialize the integral term so the PID output equals the current held output, then release the loop. That is back-calculation/tracking.

Concrete settings. Assume sensor period 50 ms, control task 100 ms. Max age = 3 missed updates = 150 ms; beyond that, quality is Bad. For a slow temperature loop with 1 s update, max age 5 s. For 4-20 mA, NAMUR NE 43 defines valid range roughly 3.8-20.5 mA; below 3.6 mA or above 21 mA is a fault. OPC UA quality Bad or Uncertain should be treated as invalid; Uncertain may allow limited continuation if the hazard analysis says so. Alarm per ISA-18.2 with a bad-quality alarm, not a process alarm. Carry timestamp, sequence number, and quality with each sample so you can detect stale, out-of-order, and duplicate data.

Decision by hazard. Low hazard: hold last output, alarm, require operator acknowledge. Medium: use redundant sensor or a model-based estimate for a limited time, e.g. 10 s, then degrade. High hazard per IEC 61511: transfer to manual, or drive to the safe state (fail-closed valve, shutdown). Never integrate the same sample forever.

HazardResponseBound
LowHold last output, alarmClamp to last valid ±5%
MediumRedundant sensor or model estimate ≤10 sClamp to safe range
HighManual transfer or safe stateFail-closed / shutdown

Failure modes to test: intermittent dropouts (debounce 2-3 scans), stale-plausible frozen value (rate-of-change check or redundant comparison), corrupted data (CRC, range check), and slow drift. Detect with age counter, quality flag, range check, and cross-check. Recovery qualification: require N consecutive good samples, e.g. 5, and a rate-of-change within limits before returning to auto. Log the event with timestamp, tag, quality, and output.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Secure setpoint and mode changes in an OT control loop.

Answer

What I'd say first

Assume this is a BPCS regulatory loop, not a safety function: the SIS interlock sits outside and must not be reachable from the control network (IEC 61511 separation). Assume the network is segmented into zones and conduits per IEC 62443, and the PLC/RTU is the last point that can reject a command.

The answer: authenticate the actor and the device, authorize the exact loop, action and mode, integrity-protect a canonical command that binds identity, target, value, units, mode, sequence, issue time and expiry, then re-validate range, rate, permissives and freshness at the controller, and confirm the applied state plus the resulting measurement, not just the receipt.

Where to enforce

Two credible places. Enforce at the controller and the policy survives a compromised gateway or engineering workstation; that's the IEC 62443-4-2 component view, and it's what you want at SL2/SL3. Enforce at a gateway or DCS and you get one policy point and easier auditing, but the gateway becomes both a single point of failure and a target: compromise it and every downstream loop is writable. For setpoints I'd do both: gateway for policy and logging, controller for the final check. The controller check is the one that matters.

Session vs per-message

OPC UA gives you a session: X.509 application certificates, security policies Basic256Sha256 or Aes256Sha256RsaPss, security modes Sign or SignAndEncrypt, and a UInt32 secure-channel sequence number the server rejects if it doesn't increase (BadSequenceNumberInvalid). Cheap per write, but the session is a bearer credential: steal it and you inherit the operator's rights until the session timeout expires. DNP3 Secure Authentication v5 (IEEE 1815) instead challenges each critical control with a nonce and an HMAC, so a captured frame is useless without the update key. More round trips, no session to steal. Modbus/TCP has neither in the base spec; Modbus/TCP Security wraps it in TLS, which gives confidentiality and server authentication but no per-command authorization.

Sign vs SignAndEncrypt: signing alone protects integrity, and for a setpoint that's often enough, but recipe values and production rates are commercially sensitive, so encrypt.

Failure modes and how you catch them

  • Replay after expiry: a valid signed command re-sent later. Caught by issue/expiry plus a monotonic sequence; the server rejects stale sequence numbers.
  • Target substitution: right value, wrong loop. Caught only if the loop tag is inside the signed payload, not in the routing header.
  • Units: 50 means 50 % or 50 °C. Bind the engineering-unit code and the EU range to the command.
  • Rate walking: each step is in range, the series is not. Rate-limit at the controller: e.g. 5 °C/s on a 0-200 °C loop.
  • Compromised operator account: authorization is per-action, so a stolen account still issues in-range commands. Dual authorization for safety-relevant setpoints, and out-of-band confirmation for mode changes.
  • Partition: decide hold-last vs revert-to-safe per loop, and write it down.

Worked trace: OPC UA Write of TIC-101 setpoint, range 0-200 °C, current 150 °C, new 165 °C.

  1. Client opens the secure channel, Basic256Sha256/SignAndEncrypt. Channel sequence starts at 1 and increments; the server drops any message with seq ≤ last.
  2. CreateSession with the client certificate; the server checks it against the trust list. Session timeout negotiated, say 3600000 ms.
  3. ActivateSession with an X.509 user token; the server maps the user to a role.
  4. Write ns=2;s=TIC101.SP = 165.0 with SourceTimestamp.
  5. Server checks: session active, role authorized for that NodeId, 165.0 inside EU range 0-200, rate ≤ 5 °C/s, permissive TIC101_HH not active. Applies.
  6. Server returns Good and the applied value; the client reads back ServerTimestamp and the process measurement to confirm the loop actually moved.

If step 5 fails, the write is rejected and the loop holds its last setpoint: the fail-closed default for a setpoint. That is the wrong default for a mode change to manual during a trip, so define per-command which way it fails.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Separate basic process control and protective functions.

Answer

Ask three things before you draw any boxes: what the hazard is and its process safety time, what the safe state is, and what SIL the LOPA credit requires. Then the answer. The BPCS and the protective function are two systems with two different jobs. The BPCS exists to hold the process at setpoint; it is allowed to fail, and when it fails it usually fails in the direction that creates the hazard. The protective function (the SIS, the interlock, the trip) exists only to move the process to the safe state after the BPCS has already failed. Because the BPCS is the initiating cause, it cannot also be the protection. IEC 61511 requires the SIS to be separate and independent from the BPCS, and that independence is what makes the LOPA credit valid.

What independence actually buys. Independence is a claim about failure correlation, not about wiring. If the trip and the control loop share a transmitter, an impulse line, a 24 V supply, a marshalling cabinet, a network switch, or the same final element, they share failure causes. A shared cause takes out both at once, and the protection you paid for delivers nothing.

The arithmetic shows how much. Worked example, hypothetical but with realistic numbers: one pressure transmitter, dangerous undetected failure rate λDU = 5×10⁻⁷/h, proof test interval 1 year (8760 h). PFDavg ≈ λDU·TI/2 = 2.2×10⁻³: SIL 2, barely. Add a second transmitter in 1oo2 with a common-cause beta of 5%:

PFDavg ≈ (λDU·TI)²/3 + β·λDU·TI/2 = 6.4×10⁻⁶ + 1.1×10⁻⁴ ≈ 1.2×10⁻⁴.

The second channel buys a factor of about 19, but 94% of what is left is common cause. That is the whole argument for separation: redundancy without independence is mostly decoration.

Trade-offs. Full separation (own sensors, own logic solver, own final element) is the highest integrity and the highest cost, and it is the only option when the LOPA credit needs SIL 2 or 3. A safety-rated logic solver inside the BPCS platform is acceptable only if it meets the SIS requirements for the target SIL; in practice you have just built a separate system in the same cabinet, and you still have to prove independence of the I/O and the power. A shared sensor with a separate trip amplifier is common at SIL 1, cheap, but the sensor is now a single point of common cause and the LOPA credit has to be reduced accordingly. A shared final element, one control valve with a solenoid, is usually the weakest link; a separate shutdown valve is the honest answer. Deciding criteria: target SIL, the LOPA credit you are claiming, spurious trip cost, and whether the process can tolerate a full shutdown.

Failure modes and detection. Common cause is the failure mode that matters: impulse lines that plug, one UPS feeding both systems, one engineering workstation that can write to both, a firmware update pushed to both, a shared network. Detect it with a CCF checklist and a beta factor in the reliability model, staggered proof tests so a common fault shows up in one channel before the other, and diagnostic coverage figures from the vendor. Response time is its own failure mode: the SIF must complete inside the process safety time. Sensor, logic solver scan, and valve stroke. A large ball valve can take several seconds to close; if the process safety time is 5 s, that budget is gone before the logic solver has finished.

When full separation is not required. For low-demand SIL 1 functions, or where a non-instrumented layer (relief valve, rupture disc, dike) already carries the risk reduction, the BPCS can carry the function, but only if it meets the SIS requirements for that SIL, which usually means it is not a BPCS any more. The operator is a protection layer too, but with a response time measured in minutes, so it only counts for slow hazards.

Monitoring without override. Read-only links from the SIS to the DCS are fine and useful: you want trip status on the operator screen. What must not exist is a write path from the BPCS to the SIS. Bypasses are managed by the SIS itself: authorized, time-limited, logged, and alarmed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design observability for control-loop diagnosis.

Answer

Clarify, then assume. First question: is the loop oscillating, sluggish, or tripping? Assume a DCS PID on a flow loop, 100 ms scan, and the goal is to reconstruct a bad hour after the fact. If it's a safety loop, the answer changes: you don't bolt logging onto an SIS.

Core. Loop observability means reconstructing the controller's own arithmetic, not just the process value. A PV trend tells you it oscillated; it can't tell you whether the cause was tuning, a sticky valve, or a bad measurement. Capture, time-aligned at scan rate (≈40 tags; the categories that matter):

SignalWhy it earns its bytes
SP + source (operator / cascade / program)separates an operator move from a cascade setpoint move
PV raw, quality flag, timestamp agebad measurement vs real deviation
Error (SP − PV)the controller's actual input
P, I, D terms separatelyseparates gain-too-high from integral windup
Feedforwardexplains output moves at zero error
OP unconstrained vs OP appliedshows clamping
Saturation + rate-limit flagswhen the clamp was active
Integrator statewindup and unwind
Mode + ownerthe loop that was in manual during the incident
Active gains + filter constantstuning changed mid-incident
Actuator feedback (valve position)stiction, dead band
Interlocks + reset causetrips

Rate and retention. Sample at scan rate, not historian rate. A loop oscillating at 0.5 Hz is invisible in a 1 s trend: that's aliasing, and you'll diagnose a phantom. 40 signals × 8 bytes × 10 Hz = 3.2 kB/s ≈ 276 MB/day; 7 days ≈ 1.9 GB. Cheap enough to keep always-on in a ring buffer. Python 3.12, persist path only: this runs beside the control task, not in it:

Python
from collections import deque
import queue

SCAN_HZ = 10
PRE_TRIGGER_S = 60
buf = deque(maxlen=SCAN_HZ * PRE_TRIGGER_S)   # 600 samples ≈ 60 s
out = queue.Queue()

def on_scan(sample):                 # called from the control task
    buf.append(sample)               # O(1), no allocation
    if trigger(sample):
        out.put_nowait(list(buf))    # writer thread drains; scan never blocks

Trade-off: always-on vs triggered. Triggered capture saves storage, but you must name the trigger, and the trigger is usually the thing you're hunting. Decision: always-on ring buffer at scan rate; on a trigger (saturation, mode change, deviation alarm) persist the buffer plus 60 s pre-trigger. The run-up is where the cause lives.

Trade-off: in-band vs out-of-band. Logging inside the control task perturbs the scan. Push to a separate historian over OPC UA or EtherNet/IP, accept the added latency, keep the control task clean.

Worked trace: stiction. Flow loop, SP = 100 m³/h, Kc = 1.0, Ti = 4 s, 100 ms scan, valve stiction band 2% of output span. Figures illustrative. At t = 0 a load step drops PV to 99.0.

t (s)SPPVePIOPZ (valve %)
0.0100.099.0+1.0+1.050.00051.00050.0
1.0100.099.0+1.0+1.050.25051.25050.0
2.0100.099.0+1.0+1.050.50051.50050.0
3.0100.099.0+1.0+1.050.75051.75050.0
4.0100.099.0+1.0+1.051.00052.00052.0
5.0100.0100.5−0.5−0.550.87550.37552.0
6.0100.0100.5−0.5−0.550.75050.25052.0
7.0100.0100.5−0.5−0.550.62550.12552.0
8.0100.0100.5−0.5−0.550.50050.00050.0

Read it: OP ramps linearly at 0.25%/s while PV and valve position Z are both flat. The controller is winding the integral up against a valve that isn't moving. At t = 4.0 s OP reaches 52.0, exactly the 2% band, and Z slips to 52.0; PV follows to 100.5. Error flips sign, the integral unwinds at 0.125%/s, and at t = 8.0 s OP hits 50.0 and Z slips back. Period 8 s. The P term is constant through the stuck phase: the whole ramp is integral, which is what the P/I split is for. A tuning problem looks different: PV tracks OP continuously, no flat phase.

Failure modes. (1) Logging in the control task stretches scan time and produces a derivative kick; detect via a scan-time high-water mark. (2) Clock skew between controller and historian misaligns SP and PV; detect via NTP offset monitoring. (3) A trigger storm overflows the buffer; cap the persist rate. (4) Sensitive process data: restrict historian access, don't ship raw values to a shared dashboard.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Review and validate a PID-controlled system end to end.

Answer

Core answer. Assume one temperature loop: heater 0–100 %, thermocouple input, first-order-plus-dead-time plant, K = 2.5 °C/%, τ = 40 s, θ = 6 s, Ts = 0.5 s. Validation is a ladder (model simulation, hardware-in-the-loop, staged plant tests) with numeric exit criteria agreed before each rung runs. You are not reviewing "the PID"; you are proving the loop meets a spec and fails safe. State the spec, walk the signal path once to find where it breaks, then climb.

Pin these first. Controller form (positional PI here; derivative on measurement if used), sample time and jitter budget, actuator range and rate limit, sensor range and accuracy, and the safe state (heater off, output 0 %).

The ladder.

StageCatchesCostExit criteria
Model simTuning, mode logic, windup, limit handlingMinutesStep overshoot ≤ 5 %, settle ±0.5 °C in 90 s
HILReal controller code, ADC quantization, scheduling jitter, I/O timingHoursSame response with Ts jitter ≤ 10 %
Plant, stagedActuator nonlinearity, real noise, thermal lag, wearDays, riskyDisturbance recovery ≤ 60 s; trip reaches safe state

Tuning. IMC-PI with λ = θ: Kc = τ/(K(λ+θ)) = 40/(2.5·12) = 1.333 %/°C, Ti = τ = 40 s, Ki = Kc/Ti = 0.0333 %/(°C·s). Sampling: θ/Ts = 12 samples; rules of thumb put Ts at θ/10 to θ/4, and θ/4 = 1.5 s, so 0.5 s has 3× margin. Acceptance for a 10 °C step: overshoot ≤ 0.5 °C, settle to ±0.5 °C within 90 s, steady-state error ≤ 0.2 °C.

Discrete PI with back-calculation anti-windup.

Python
Ts, Kc, Ti, Tt = 0.5, 1.333, 40.0, 40.0
u_min, u_max = 0.0, 100.0
I = 0.0
def step(sp, y):
    global I
    e = sp - y
    I += Kc * Ts / Ti * e
    u_unsat = Kc * e + I
    u = min(max(u_unsat, u_min), u_max)
    I += (Ts / Tt) * (u - u_unsat)   # back-calculation
    return u

Kc·Ts/Ti = 0.01666, Ts/Tt = 0.0125. Trace sp = 10, y = 0, I = 0, first-order plant only (dead time omitted so the arithmetic is checkable; with θ = 6 s the first 12 samples return y = 0):

  • Step 1: e = 10. I = 0 + 0.01666·10 = 0.1666. u_unsat = 1.333·10 + 0.1666 = 13.50. In range, so u = 13.50 % and the anti-windup term adds 0. Plant: Δy = (2.5·13.50 − 0)/40 · 0.5 = 0.42 °C.
  • Step 2: y = 0.42, e = 9.58. I = 0.1666 + 0.01666·9.58 = 0.3262. u_unsat = 1.333·9.58 + 0.3262 = 13.09 %. Plant: Δy = (2.5·13.09 − 0.42)/40 · 0.5 = 0.40 °C, y = 0.83.
  • Step 3: e = 9.17. I = 0.3262 + 0.01666·9.17 = 0.4791. u_unsat = 1.333·9.17 + 0.4791 = 12.71 %. Plant: Δy = (2.5·12.71 − 0.83)/40 · 0.5 = 0.39 °C, y = 1.21.

The integral carries the load. P alone would give 13.3 % at step 1 and 12.8 % at step 2, and settle at y = 10·Kc·K/(1 + Kc·K) = 10·3.33/4.33 = 7.69 °C: 2.31 °C of offset.

Saturation. Same code, sp = 80, y = 0. Step 1: e = 80, I = 0.01666·80 = 1.333, u_unsat = 1.333·80 + 1.333 = 107.97 → u = 100. Back-calculation: I += 0.0125·(100 − 107.97) = −0.0996, so I = 1.233. Plant: Δy = 2.5·100/40 · 0.5 = 3.13 °C. Step 2: e = 76.88, I = 1.233 + 0.01666·76.88 = 2.514, u_unsat = 1.333·76.88 + 2.514 = 104.99 → u = 100, I += 0.0125·(−4.99) = −0.062, I = 2.452. The integrator still charges while saturated, just slower; Tt = Ti is deliberately gentle, and halving Tt doubles the pull-back per step. Without the correction I would be 2.614 at step 2 and climbing.

Failure modes and detection.

  • Windup on startup: log u_unsat against u; a widening gap means the integrator is charging while saturated. With θ = 6 s the loop is blind for 12 samples, so this is where it happens.
  • Derivative kick on setpoint steps: derivative on measurement, or filter with N = 8–10.
  • Stuck sensor: flag when |dy/dt| < 0.05 °C/s while u > 20 % for more than 10 s; a frozen reading with a live output is the classic runaway. Add a redundant element on the trip path.
  • Network loss in cascade: hold last good setpoint or drop to local auto; never let the outer loop drive a stale value.
  • Trip: verify the safe state is reached and latched, not just commanded.

Trade-offs. Simulation is cheap and catches tuning and logic but misses actuator nonlinearity, noise and timing jitter. HIL adds real code and I/O timing at moderate cost, not real wear. Plant testing catches everything and is the only stage that can hurt hardware, so it runs last with limits enabled and an abort path. Stop when the riskiest path meets its criteria and residual risk is written down, not when the test list is exhausted.

Curated: · Written: · Reviewed:

Difficulty: Hard