The sample time is inside the gains
The factors
A pump pressure loop that was steady on a panel controller is moved to a small microcontroller board. The same gain and the same integral time are typed in, and the pressure now swings after every change in demand. Nothing is wrong with the settings. The new code runs the calculation once every two seconds, between other tasks, and the sample time is a part of the control equation that the old controller never showed. A wire that comes loose from the transmitter then sends the pump to full speed, because the code reads zero current as a pressure below zero. This lesson turns the PID equation into firmware that keeps its tuning, its limits and its safe behaviour. #DigitalControl #PIDController #EmbeddedSystems
By the end of this lesson, you will be able to:
The booster pump of this course holds 4.0 bar in a water line. A pressure transmitter sends 4 to 20 mA. A resistor turns the current into a voltage, an analog-to-digital converter (ADC) turns the voltage into a number, and the firmware turns the number into bar. The PID calculation gives a speed in percent, and an analog output or a serial link passes it to the variable speed drive.
Each step in this chain can damage the loop without any error message. A wrong scaling constant changes the effective gain. A calculation that runs at irregular times changes the integral and the derivative. A missing check on the input turns a broken wire into a full-speed pump.
The process responds in a few seconds, so the loop must run every fraction of a second, every time, with or without a network. That requirement decides where the code lives.
A digital controller reads the measurement at fixed instants,
The hold has a cost. An output calculated at one instant is used for the whole of the next interval, so on average it is
The extra delay costs phase margin. At the crossover frequency
Two working guides follow from this.
Faster is not always better. A very short sample time makes the difference
A sampled signal cannot show a frequency above half the sample rate. A faster signal does not disappear: it appears as a slow one. Pressure pulsation at 47 Hz, read 20 times per second, appears in the data as a 7 Hz wave (the distance from 47 Hz to the nearest multiple of 20 Hz), and the controller responds to a wave that does not exist at that frequency. This is aliasing. No calculation after sampling can remove it. The protection must come before the sample is used: a resistor and capacitor filter in front of the ADC, or reading the ADC much faster than the loop and averaging the readings in firmware.
The ISA standard form is
with controller gain
Proportional.
Integral. The integral becomes a running sum. The backward rectangle rule adds one rectangle of width
The trapezoidal rule uses the mean of the last two errors,
Derivative. The filtered derivative on the measurement obeys
This form is stable for every positive
The sample time is inside the gains
The factors
The position form calculates the whole output at every sample:
The integral
The velocity (incremental) form calculates the change of the output:
and then
The output limits are part of the algorithm. After the sum, the output is limited to the range the final element accepts. With clamp anti-windup, the integral step of this sample is kept only if it does not push the output further past a limit.
In manual mode the operator sets the output. If the controller ignores this, the stored integral has an arbitrary value at the moment of the change to automatic, and the output jumps. Bumpless transfer avoids the jump. While in manual, the code sets
at every sample, so that
The controller is one header file. It uses no dynamic memory and no library call, so it runs on any microcontroller with a C compiler. The type pid_real is double for testing on a computer and float for a small processor.
/* pid.h : discrete PID, ISA standard form. * u = Kc * ( e + (1/Ti) * integral(e) - Td * d(y)/dt filtered ) * Call pid_update() or pid_track() exactly once every ts seconds. */#ifndef PID_H#define PID_H
#ifdef PID_USE_FLOATtypedef float pid_real; /* single precision, for a small MCU with an FPU */#elsetypedef double pid_real;#endif
typedef struct { pid_real kc; /* controller gain, output units per PV unit. Positive = reverse acting, negative = direct acting */ pid_real ti; /* integral time, s (0 switches the integral off) */ pid_real td; /* derivative time, s (0 switches the derivative off) */ pid_real n; /* derivative filter divisor: Tf = td / n */ pid_real ts; /* sample time, s */ pid_real out_min; /* lower output limit */ pid_real out_max; /* upper output limit */ pid_real integ; /* integral term, in output units */ pid_real deriv; /* filtered derivative term, in output units */ pid_real y_prev; /* measurement at the previous sample */} pid_ctrl;
static inline pid_real pid_clamp(pid_real v, pid_real lo, pid_real hi){ return (v > hi) ? hi : (v < lo) ? lo : v;}
/* Set the tuning and the limits, and clear the stored state. */static inline void pid_init(pid_ctrl *c, pid_real kc, pid_real ti, pid_real td, pid_real n, pid_real ts, pid_real out_min, pid_real out_max){ c->kc = kc; c->ti = ti; c->td = td; c->n = n; c->ts = ts; c->out_min = out_min; c->out_max = out_max; c->integ = 0; c->deriv = 0; c->y_prev = 0;}
/* Manual mode: call every sample with the output the operator has set. * The integral follows, so the first automatic output equals u_manual. */static inline pid_real pid_track(pid_ctrl *c, pid_real r, pid_real y, pid_real u_manual){ pid_real u = pid_clamp(u_manual, c->out_min, c->out_max); c->integ = (c->ti > 0) ? u - c->kc * (r - y) : 0; c->deriv = 0; c->y_prev = y; return u;}
/* Automatic mode: one control step. r = setpoint, y = measurement. */static inline pid_real pid_update(pid_ctrl *c, pid_real r, pid_real y){ pid_real e = r - y; pid_real p = c->kc * e;
/* Integral: backward rectangle. di is the change proposed for this sample. */ pid_real di = (c->ti > 0) ? c->kc * c->ts / c->ti * e : 0; pid_real i_new = c->integ + di;
/* Derivative on measurement, first-order filter Tf = td/n, * backward difference. With td = 0 this term stays at zero. */ pid_real tf = (c->n > 0) ? c->td / c->n : 0; c->deriv = (tf * c->deriv - c->kc * c->td * (y - c->y_prev)) / (tf + c->ts); c->y_prev = y;
pid_real v = p + i_new + c->deriv; /* output before limits */ pid_real u = pid_clamp(v, c->out_min, c->out_max);
/* Clamp anti-windup: refuse an integral change that pushes the * output further past a limit. Accept every other change. */ if (!((v > c->out_max && di > 0) || (v < c->out_min && di < 0))) c->integ = i_new;
return u;}
#endif /* PID_H */The test program below connects the controller to a model of the booster pump. The model advances in steps of 0.01 s with the exact first-order update, and the controller runs once every ts seconds. For the first 2 s the controller is in manual at 60 percent, then it changes to automatic with a setpoint of 4.5 bar.
/* pid_test.c : run the PID against a model of the booster pump (plant B). * Build: gcc -Wall -Wextra -std=c11 pid_test.c -o pid_test -lm * Use: ./pid_test 0.1 > trace_0.1.txt (argument = sample time, s) */#include <stdio.h>#include <stdlib.h>#include <math.h>#include "pid.h"
#define H 0.01 /* plant step, s */#define NDEAD 50 /* dead time 0.5 s = 50 plant steps */#define NSTEP 4000 /* 40 s in total */
int main(int argc, char **argv){ double ts = (argc > 1) ? atof(argv[1]) : 0.1; int sub = (int)lround(ts / H); /* plant steps per sample */ const double K = 0.10, tau = 3.0; /* bar per percent, s */ const double y0 = 4.0, u0 = 60.0; /* operating point */ const double a = exp(-H / tau); double x = 0.0, u = u0, buf[NDEAD]; pid_ctrl c;
pid_init(&c, 15.0, 3.0, 0.0, 10.0, (pid_real)ts, 0.0, 100.0); for (int i = 0; i < NDEAD; i++) buf[i] = u0;
for (int j = 0; j < NSTEP; j++) { double t = j * H, y = y0 + x; if (j % sub == 0) { /* the timer tick */ if (t < 2.0) u = pid_track(&c, 4.0, y, u0); /* manual */ else u = pid_update(&c, 4.5, y); /* auto */ printf("%.2f %.17g %.17g\n", t, y, u); } double ud = buf[j % NDEAD]; /* output from 0.5 s ago */ buf[j % NDEAD] = u; x = a * x + K * (1.0 - a) * (ud - u0); /* exact for a held input */ } return 0;}The integral and the derivative assume that samples are exactly
The standard pattern uses a hardware timer. The timer interrupt only sets a flag. The main loop waits for the flag and then does three things in a fixed order: read the input, compute, write the output. Reading first, at the start of the tick, keeps the sample instant regular even when the calculation time varies.
The pattern below shows the pieces together, with the scaling and the wire check from Application 2. The four extern functions belong to the board, so this file compiles but does not link without them.
/* main_loop.c : how the pieces fit on the microcontroller (pattern). * The four extern functions belong to the board support code. */#include <stdbool.h>#include "pid.h"
extern unsigned read_adc_counts(void); /* 0 to 4095 */extern void write_speed_percent(pid_real u);extern bool auto_requested(void); /* operator switch */extern pid_real manual_output(void); /* operator value, % */
static volatile bool tick = false;void timer_isr(void) { tick = true; } /* hardware timer, every 100 ms */
int main(void){ pid_ctrl c; pid_real r = 4.0f, y = 4.0f, u = 0; pid_init(&c, 15.0f, 3.0f, 0, 10.0f, 0.1f, 0, 100.0f);
for (;;) { if (!tick) continue; /* wait for the timer; no delay() */ tick = false;
unsigned n = read_adc_counts(); /* 1. read at a fixed instant */ bool ok = (n >= 670u && n <= 3910u); /* 3.6 mA to 21 mA */ if (ok) y = ((pid_real)n - 744.7f) * 0.0033569f; /* counts to bar */
if (ok && auto_requested()) /* 2. compute */ u = pid_update(&c, r, y); else /* manual, or hold on a fault */ u = pid_track(&c, r, y, ok ? manual_output() : u);
write_speed_percent(u); /* 3. write */ }}A microcontroller with a floating-point unit runs this controller in single precision in a few microseconds. A part without one does the same arithmetic in software, which is slower but usually acceptable at ten samples per second. Fixed-point integer arithmetic is for loops that run thousands of times per second on a small part, and it needs care with scaling and overflow at every line.
Single precision carries about seven significant digits. That is enough for the output, but the integral adds a small step to a large stored value. For the hot water tank (
Keep the controller in engineering units: bar or °C for the setpoint and the measurement, percent for the output. Convert at the two edges only. Then
The control loop belongs in the controller or in the firmware beside the process. A network adds a delay that changes from one message to the next and sometimes loses a message, and both act as dead time that the tuning cannot know. A loop that depends on a remote server stops when the link stops.
A remote platform has a different task. It can record the setpoint, the measurement and the output, raise an alert when the output stays at a limit, compare many sites, and send a new setpoint or new settings that the local controller checks before it accepts them. If the link fails, the local loop continues with the last accepted setpoint.
Tuning.
Integral step per sample. The factor
Bumpless start. In manual the error is zero and the output is 60 percent, so the stored integral is 60 percent. ✅
First automatic output. The error is 0.5 bar. The proportional term is
Loop. With
Add half a sample to the dead time:
Results.
Near-continuous reference (
Longer still. At
| Overshoot (percent) | Settling time (s) | IAE (bar s) | Peak output (percent) | Estimated margin (degrees) | |
|---|---|---|---|---|---|
| 0.01 | 0.00 | 6.08 | 1.000 | 68.77 | 75.5 |
| 0.1 | 0.00 | 5.96 | 0.977 | 69.00 | 74.2 |
| 0.5 | 0.00 | 5.30 | 0.874 | 70.00 | 68.5 |
| 2 | 21.65 | 9.25 | 0.965 | 72.50 | 47.0 |
Build and run. gcc -Wall -Wextra -std=c11 pid_test.c -o pid_test -lm gives no warning. The program is run three times, with arguments 0.1, 0.5 and 2, and each output is saved as trace_0.1.txt, trace_0.5.txt and trace_2.txt. ✅
Compare. The Python script runs the same loop and subtracts the two results at every sample: 400, 80 and 20 samples. The largest absolute difference is 0.00 in the pressure and 0.00 in the output. The two programs agree to the last bit, because both use double precision and do the arithmetic in the same order. ✅
Single precision. Built with -DPID_USE_FLOAT, the controller differs from the Python result by at most
Error area from theory. For a loop with one integrator, the area under the error after a setpoint step
Compare. The reference response has no overshoot, so the error never changes sign and the IAE equals this area. The simulation gives 1.000 bar s. ✅
First output. The trace for
Voltage at 4 mA:
Voltage at 20 mA:
Count at 4 mA:
Count at 20 mA:
Span in counts:
Formula. A straight line through the two end points:
Resolution:
What one count does to the pump. With
Signal with an open circuit. No current flows, the resistor holds the input at 0 V, and the count is 0 (in practice a few counts of noise). ✅
What the formula does with it.
Fault limits. A healthy transmitter never sends less than 4 mA. A widely used convention (the NAMUR NE 43 recommendation) treats a current of 3.6 mA or less, or 21 mA or more, as a failure signal. In counts:
Rule for the firmware. A count below 670 or above 3910 is not a pressure. The code must stop using the reading, go to the agreed safe output and raise an alarm. A count of 0 indicates a broken wire or a transmitter without power. ✅
End points.
Middle. 12 mA is the middle of the signal, so it must read 5 bar. It gives 1.8 V and 2234 counts, and the formula returns 4.999 bar. ✅
The script holds the same algorithm as pid.h, line for line. It runs the loop at each sample time, prints the measures, compares its trajectory with the C trace files when they are present in the same folder, and then repeats the scaling of Application 2.
"""Discrete PID (same algorithm as pid.h) on the booster pump, plant B.
Runs the loop at several sample times, measures overshoot, settling timeand IAE, compares with the C trace files if they are present, and scalesa 4 to 20 mA pressure signal read by a 12-bit converter."""import osimport numpy as npimport matplotlib.pyplot as plt
K, TAU, THETA = 0.10, 3.0, 0.5 # bar per percent, s, sY0, U0 = 4.0, 60.0 # operating point: bar, percentKC, TI, TD, N = 15.0, 3.0, 0.0, 10.0 # PI, ISA formH, NDEAD, NSTEP = 0.01, 50, 4000 # plant step, dead-time steps, 40 sT_STEP, R0, R1 = 2.0, 4.0, 4.5 # setpoint step at 2 s
class PID: """Line for line the same arithmetic as pid.h."""
def __init__(self, kc, ti, td, n, ts, out_min, out_max): self.kc, self.ti, self.td, self.n, self.ts = kc, ti, td, n, ts self.out_min, self.out_max = out_min, out_max self.integ = self.deriv = self.y_prev = 0.0
def clamp(self, v): return self.out_max if v > self.out_max else self.out_min if v < self.out_min else v
def track(self, r, y, u_manual): u = self.clamp(u_manual) self.integ = u - self.kc * (r - y) if self.ti > 0 else 0.0 self.deriv = 0.0 self.y_prev = y return u
def update(self, r, y): e = r - y p = self.kc * e di = self.kc * self.ts / self.ti * e if self.ti > 0 else 0.0 i_new = self.integ + di tf = self.td / self.n if self.n > 0 else 0.0 self.deriv = (tf * self.deriv - self.kc * self.td * (y - self.y_prev)) / (tf + self.ts) self.y_prev = y v = p + i_new + self.deriv u = self.clamp(v) if not ((v > self.out_max and di > 0) or (v < self.out_min and di < 0)): self.integ = i_new return u
def run(ts, nstep=NSTEP): """Return fine-step t, y, u and the array of (t, y, u) at each sample.""" sub = int(round(ts / H)) a = np.exp(-H / TAU) c = PID(KC, TI, TD, N, ts, 0.0, 100.0) buf = [U0] * NDEAD x, u = 0.0, U0 t_all, y_all, u_all, samples = [], [], [], [] for j in range(nstep): t, y = j * H, Y0 + x if j % sub == 0: u = c.track(R0, y, U0) if t < T_STEP else c.update(R1, y) samples.append((t, y, u)) t_all.append(t); y_all.append(y); u_all.append(u) ud = buf[j % NDEAD] buf[j % NDEAD] = u x = a * x + K * (1.0 - a) * (ud - U0) return np.array(t_all), np.array(y_all), np.array(u_all), np.array(samples)
def measures(t, y): step = R1 - R0 m = t >= T_STEP over = 100.0 * (y[m].max() - R1) / step outside = np.where(m & (np.abs(y - R1) > 0.02 * step))[0] settle = t[outside[-1] + 1] - T_STEP iae = np.sum(np.abs(R1 - y[m])) * H return max(over, 0.0), settle, iae
print("Plant B, PI: Kc = %.1f percent per bar, Ti = %.1f s" % (KC, TI))print(" Ts (s) overshoot (%) settling (s) IAE (bar s) u peak (%) PM est (deg)")fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7, 6), sharex=True)for ts in (0.01, 0.1, 0.5, 2.0): t, y, u, s = run(ts) over, settle, iae = measures(t, y) pm = 90.0 - np.degrees(0.5 * (THETA + ts / 2.0)) print(" %5.2f %10.2f %10.2f %10.3f %9.2f %10.1f" % (ts, over, settle, iae, u.max(), pm)) ax1.plot(t, y, label="Ts = %g s" % ts) ax2.step(t, u, where="post")ax1.axhline(R1, color="gray", lw=0.8, ls="--")ax1.set_ylabel("pressure (bar)"); ax1.legend(); ax1.grid(alpha=0.3)ax2.set_ylabel("drive speed (%)"); ax2.set_xlabel("time (s)"); ax2.grid(alpha=0.3)ax1.set_title("Booster pump: the same PI settings at four sample times")fig.tight_layout(); fig.savefig("sample_time_comparison.png", dpi=120)
for ts in (3.0, 4.0): # is the loop still stable? t, y, u, s = run(ts, 20000) early, late = np.abs(y[2000:8000] - R1).max(), np.abs(y[14000:] - R1).max() print(" Ts = %.0f s: largest error %.3f bar at 20 to 80 s, %.3f bar at 140 to 200 s" % (ts, early, late))
print("\nC against Python (largest absolute difference)")for name in ("0.1", "0.5", "2"): path = "trace_%s.txt" % name if not os.path.exists(path): print(" %s not found, comparison skipped" % path) continue c_tr = np.loadtxt(path) py_tr = run(float(name))[3] d = np.abs(c_tr - py_tr) print(" Ts = %-3s s %4d samples y: %.2e bar u: %.2e percent" % (name, len(c_tr), d[:, 1].max(), d[:, 2].max()))
print("\n4 to 20 mA transmitter, 0 to 10 bar, 150 ohm, 12 bit, 3.3 V")R_SENSE, VREF, FULL = 150.0, 3.3, 4096counts = lambda mA: mA * 1e-3 * R_SENSE / VREF * FULLn4, n20 = counts(4.0), counts(20.0)print(" 4 mA : %.2f V %7.1f counts" % (4e-3 * R_SENSE, n4))print(" 20 mA: %.2f V %7.1f counts" % (20e-3 * R_SENSE, n20))print(" span : %.1f counts, %.5f bar per count" % (n20 - n4, 10.0 / (n20 - n4)))print(" 3.6 mA (fault below): %.1f counts, 21 mA (fault above): %.1f counts" % (counts(3.6), counts(21.0)))print(" 0 counts scaled without a check: %.2f bar" % ((0 - n4) * 10.0 / (n20 - n4)))for n in (745, 2234, 3724): print(" %4d counts -> %.3f bar" % (n, (n - n4) * 10.0 / (n20 - n4)))Expected output
Plant B, PI: Kc = 15.0 percent per bar, Ti = 3.0 s Ts (s) overshoot (%) settling (s) IAE (bar s) u peak (%) PM est (deg) 0.01 0.00 6.08 1.000 68.77 75.5 0.10 0.00 5.96 0.977 69.00 74.2 0.50 0.00 5.30 0.874 70.00 68.5 2.00 21.65 9.25 0.965 72.50 47.0 Ts = 3 s: largest error 0.030 bar at 20 to 80 s, 0.000 bar at 140 to 200 s Ts = 4 s: largest error 4.414 bar at 20 to 80 s, 4.414 bar at 140 to 200 s
C against Python (largest absolute difference) Ts = 0.1 s 400 samples y: 0.00e+00 bar u: 0.00e+00 percent Ts = 0.5 s 80 samples y: 0.00e+00 bar u: 0.00e+00 percent Ts = 2 s 20 samples y: 0.00e+00 bar u: 0.00e+00 percent
4 to 20 mA transmitter, 0 to 10 bar, 150 ohm, 12 bit, 3.3 V 4 mA : 0.60 V 744.7 counts 20 mA: 3.00 V 3723.6 counts span : 2978.9 counts, 0.00336 bar per count 3.6 mA (fault below): 670.3 counts, 21 mA (fault above): 3909.8 counts 0 counts scaled without a check: -2.50 bar 745 counts -> 0.001 bar 2234 counts -> 4.999 bar 3724 counts -> 10.001 barThe script also saves sample_time_comparison.png, with the pressure and the drive speed for the four sample times.
A sampled controller with a held output adds about half a sample of dead time, and costs about
A sample time near one tenth of the closed-loop time constant leaves the tuning intact. On the booster pump, 0.1 s and 0.5 s gave no overshoot, and 2 s gave 21.65 percent overshoot.
The C controller in this lesson includes output limits, clamp anti-windup, derivative on the measurement and bumpless transfer, and it matched the Python model exactly over all tested samples.
A 4 to 20 mA input across 150 Ω into a 12-bit, 3.3 V converter gives 0.00336 bar per count on a 10 bar range, and any count below 670 is a fault and not a pressure.
The loop runs in the controller or firmware. A remote platform supervises and records.
The hot water tank loop has
A PI controller in velocity form has
A PID controller has
A 4 to 20 mA transmitter with a range of 0 to 16 bar is read across a 220 Ω resistor by a 10-bit ADC (1024 codes) with a 5.0 V reference. Find the counts at 4 mA and at 20 mA, the resolution in bar per count, and the pressure for a count of 512.
0.88 V gives 180.2 counts and 4.40 V gives 901.1 counts. The span is 720.9 counts, so the resolution is
The hot water tank controller (
The step is
The pump PI loop works well when the firmware runs it every 0.1 s. To save processor time someone changes it to every 2 s. The pump takes about 3 s to respond. What happens after a setpoint step?
The loop is the lesson's: K = 0.10 bar per percent, τ = 3 s, θ = 0.5 s, PI with Kc = 15 percent per bar and Ti = 3 s. The controller is in manual at 60 percent until 2 s, then the setpoint becomes 4.5 bar. The pump is simulated in steps of 0.01 s; the controller acts only once per sample and holds its output in between.
Three questions. Each wrong choice is a mistake people really make, so read the note after you answer.
1. The pump loop has a crossover of 0.5 rad/s and a dead time of 0.5 s. The firmware samples every 1 s. About what phase margin is left?
2. The 4 to 20 mA transmitter reads 0 to 10 bar. It drives 150 Ω into a 12 bit ADC with a 3.3 V reference. What count does the ADC give at 5 bar?
3. The pump loop is tuned with λ = 1.5 s and has a dead time θ = 0.5 s. Which sample time meets both guides of the lesson?
No comments yet. Questions, results from your own build, a better way to explain it: all welcome.
Kept on this device only. Nothing is sent anywhere.
Tip: select words in the lesson, or tap a figure or an equation, to put a note right there.
The lesson has changed and these words are no longer in it. Your notes are kept, with the words you chose.