Skip to content
You Start with one site
Amounts in Start with one site
Control, Measurement & Energy · Course

Digital Control: From Equation to Firmware

Lesson 10 of 11 25 min read
Found this useful?

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

Learning Objectives

By the end of this lesson, you will be able to:

  1. Choose a sample time from the closed-loop time constant and the dead time, and estimate the phase margin it costs
  2. Write the discrete PID in position form and in velocity form, with a filtered derivative on the measurement
  3. Implement the controller in C with clamp anti-windup and bumpless transfer, and test it against a model of the process
  4. Scale the counts of an analog-to-digital converter into engineering units and detect a broken transmitter wire
  5. Decide which parts of a control system belong in firmware and which belong on a remote platform

Real-World System Problem: A booster pump controlled by firmware



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.

PID, everyTs secondspressure150 ΩADCscaletransmitterresistor12 bitcounts to bar4to20mA0.6to3V0..4095ysetpoint r (bar)timer tick, every Tsu (0..100 %)pumpvariable speed driveoutput
Signal path of the firmware loop

Fundamental Theory: The discrete PID



Sampling and the hold

A digital controller reads the measurement at fixed instants, seconds apart. is the sample time. Between two instants the controller knows nothing new and its output stays constant. This constant output is called a zero-order hold.

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 old. To the loop, sampling looks like extra dead time of about half a sample:

uideal output (smooth)·······held output (steps)t0Ts2Ts3Ts4Ts5Ts6Tsthe steps follow the smooth curve Ts/2 later
A held output is half a sample late on average

Choosing the sample time

The extra delay costs phase margin. At the crossover frequency the loss is

Two working guides follow from this.

  • Sample about ten times in one closed-loop time constant: , where is the closed-loop time constant chosen in lambda tuning.
  • Check the half-sample delay against the dead time . If is more than about a quarter of , the loop no longer has the dead time it was tuned for. Retune with or sample faster.

Faster is not always better. A very short sample time makes the difference small compared with the noise, so the derivative becomes noisy, and it makes each integral step so small that it can be lost in single-precision arithmetic. The guides above are starting points, not laws.

Aliasing

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.

From the continuous equation to a sum

The ISA standard form is

with controller gain , integral time , derivative time and error . Index the samples by . Each term has a discrete version.

Proportional. .

Integral. The integral becomes a running sum. The backward rectangle rule adds one rectangle of width and height per sample:

The trapezoidal rule uses the mean of the last two errors, . It is a little more accurate, and at a sensible sample time the two give almost the same loop. The code in this lesson uses the backward rectangle.

Derivative. The filtered derivative on the measurement obeys , with filter time constant . Replace each rate by a backward difference, for example , and solve for :

This form is stable for every positive , which is why the backward difference is preferred here.

The sample time is inside the gains

The factors and contain . Code that was written for one sample time and is then called at another has a different integral action and a different derivative action, although the three settings on the screen did not change. Always pass the true sample time to the controller, and call it at that rate.

Position form and velocity form

The position form calculates the whole output at every sample:

The integral is stored between samples. This form needs explicit anti-windup, because the stored integral can grow while the output is at a limit. It is the form in the code below, since the stored integral is easy to inspect and to set for bumpless transfer.

Anti-windup and bumpless transfer in code

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 already equals the manual output. The first automatic output then continues from the manual value.

The complete controller in C

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
/* 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_FLOAT
typedef float pid_real; /* single precision, for a small MCU with an FPU */
#else
typedef 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
/* 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;
}

Fixed timing, jitter and the order of work

The integral and the derivative assume that samples are exactly apart. A loop that runs “when the processor is free” has a period that changes with every other task. This variation is called jitter, and it acts as noise in the derivative and as a changing gain in the integral.

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.

tick ktick k+1read ADCscale, PIDwriteread ...short and constantidleTs
One timer tick

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
/* 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 */
}
}

Float, integer and the size of a step

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 ( percent per °C, s) called every 0.001 s, the step for an error of 0.1 °C is percent. The stored integral near 60 percent cannot change by less than percent in single precision, so the step is rounded away and a small offset stays for ever. A slow loop should be called slowly.

Units and scaling

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 in the code is the from the tuning calculation. If the measurement is left in ADC counts, the same loop needs a gain in percent per count, which is multiplied by the bar per count, and every later change of the transmitter range silently changes the tuning.

Where the loop must live

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.

Application 1: The pump loop at three sample times



Step 1: Settings and the first output

Click to reveal the settings
  1. Tuning. percent per bar, and s. ✅

  2. Integral step per sample. The factor is 0.5, 2.5 and 10 percent per bar for = 0.1, 0.5 and 2 s. ✅

  3. Bumpless start. In manual the error is zero and the output is 60 percent, so the stored integral is 60 percent. ✅

  4. First automatic output. The error is 0.5 bar. The proportional term is percent, and the first integral step is 0.25, 1.25 and 5.0 percent. The first output is therefore 67.75, 68.75 and 72.5 percent. The output does not reach a limit in this test. ✅

Step 2: Predict the margin with the half-sample delay

Click to reveal the estimate
  1. Loop. With the loop is , so rad/s and the continuous phase margin is degrees. ✅

  2. Add half a sample to the dead time:

    ✅
  3. Results. s: 74.2 degrees. s: 68.5 degrees. s: the effective dead time is 1.5 s, three times the real one, and the margin falls to 47.0 degrees. ✅

Step 3: Simulate

Click to reveal the results
  1. Near-continuous reference ( s): no overshoot, settling time 6.08 s, IAE 1.000 bar s. ✅

  2. s and s: no overshoot, settling times 5.96 s and 5.30 s. The loop is still well damped. ✅

  3. s: overshoot 21.65 percent (the pressure peaks near 4.61 bar) and settling time 9.25 s. ✅

  4. Longer still. At s the oscillation decays slowly. At s it grows until the output swings between its limits: the loop is unstable. ✅

(s)Overshoot (percent)Settling time (s)IAE (bar s)Peak output (percent)Estimated margin (degrees)
0.010.006.081.00068.7775.5
0.10.005.960.97769.0074.2
0.50.005.300.87470.0068.5
221.659.250.96572.5047.0

Step 4: Compare the C code with the Python code

Click to reveal the comparison
  1. 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. ✅

  2. 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. ✅

  3. Single precision. Built with -DPID_USE_FLOAT, the controller differs from the Python result by at most percent in the output and bar in the pressure. This is rounding at the seventh digit, far below the resolution of the transmitter. ✅

Step 5: Check the reference a second way

Click to reveal the check
  1. Error area from theory. For a loop with one integrator, the area under the error after a setpoint step is divided by the loop gain factor :

    ✅
  2. 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. ✅

  3. First output. The trace for s shows 67.75 percent at s, and the trace for s shows 72.5 percent, as calculated in Step 1. ✅

Application 2: From ADC counts to bar



150+24 VtransmitterADC input4to20mA12bit,3.3VΩ0.6Vto3.0V0 VADC ground
Current loop input

Step 1: Voltages and counts at the two ends

Click to reveal the two end points
  1. Voltage at 4 mA: V. ✅

  2. Voltage at 20 mA: V. This is below the 3.3 V reference, so the top of the range is not cut off. The input would reach 3.3 V at 22 mA. ✅

  3. Count at 4 mA: . The converter returns 744 or 745. ✅

  4. Count at 20 mA: . The converter returns 3723 or 3724. ✅

Step 2: Scaling formula and resolution

Click to reveal the scaling
  1. Span in counts: counts for 10 bar. Only 73 percent of the 4096 codes carry pressure information. ✅

  2. Formula. A straight line through the two end points:

    ✅
  3. Resolution: bar per count (3.4 mbar, or 0.034 percent of the range). ✅

  4. What one count does to the pump. With percent per bar, a change of one count moves the output by percent. The steps are small enough for this loop. ✅

Step 3: The broken wire

Click to reveal the fault check
  1. 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). ✅

  2. What the formula does with it. bar. With a setpoint of 4.0 bar the controller sees an error of 6.5 bar and drives the pump to 100 percent. The real pressure then rises with nothing to limit it. ✅

  3. 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: and . ✅

  4. 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. ✅

Step 4: Check the formula at known points

Click to reveal the check
  1. End points. gives 0.001 bar and gives 10.001 bar. ✅

  2. 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. ✅

Verify It in Python



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.

digital_pid_check.py
"""Discrete PID (same algorithm as pid.h) on the booster pump, plant B.
Runs the loop at several sample times, measures overshoot, settling time
and IAE, compares with the C trace files if they are present, and scales
a 4 to 20 mA pressure signal read by a 12-bit converter.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
K, TAU, THETA = 0.10, 3.0, 0.5 # bar per percent, s, s
Y0, U0 = 4.0, 60.0 # operating point: bar, percent
KC, TI, TD, N = 15.0, 3.0, 0.0, 10.0 # PI, ISA form
H, NDEAD, NSTEP = 0.01, 50, 4000 # plant step, dead-time steps, 40 s
T_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, 4096
counts = lambda mA: mA * 1e-3 * R_SENSE / VREF * FULL
n4, 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 bar

The script also saves sample_time_comparison.png, with the pressure and the drive speed for the four sample times.

Common Mistakes



  • Timing the loop with a delay call in the main loop. The real period is then the delay plus the calculation time plus every other task, and it changes. Use a hardware timer and pass the true to the controller.
  • Changing the sample time without changing the code that depends on it. The integral and derivative factors contain , so the effective tuning changes.
  • Clamping the output but not protecting the integral. The output looks limited, and the stored integral still winds up behind the limit.
  • Leaving the measurement in ADC counts and entering a gain that was calculated in percent per bar. The loop gain is then wrong by the factor of bar per count.
  • Scaling a 4 to 20 mA input without checking for a count below the 4 mA point. A broken wire reads as a pressure below zero and drives the output to its limit.
  • Setting the stored integral to zero on the change from manual to automatic. The output jumps to the proportional term alone. Track the manual output so that the change is bumpless.

Summary



  • A sampled controller with a held output adds about half a sample of dead time, and costs about degrees of phase margin.

  • 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.

Exercises



  1. The hot water tank loop has s, s and rad/s. Choose a sample time by the guide and find the phase margin it costs.

    Answer

    s. The loss is degrees. The half-sample delay of 4 s is one tenth of the dead time, so the tuning is not disturbed.

  2. A PI controller in velocity form has percent per bar, s and s. The last two errors are bar and bar. Find the change of the output.

    Answer

    percent. The falling error reduces the output although the error is still positive.

  3. A PID controller has percent per °C, s, and s. The stored derivative term is zero and the temperature rises by 0.1 °C in one sample. Find and the new derivative term.

    Answer

    s. percent. The sign is negative because a rising measurement must reduce the output of a reverse acting controller.

  4. 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.

    Answer

    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 bar per count. At 512 counts, bar.

  5. The hot water tank controller ( percent per °C, s) runs in single precision with s. The stored integral is near 60 percent, where the spacing between neighbouring single-precision numbers is percent. A step smaller than half of this spacing is rounded away. What is the smallest error that still changes the integral? What is it at s?

    Answer

    The step is percent. It must exceed percent, so must exceed about 0.11 °C. Smaller errors are never integrated and remain as an offset. At s the step is 8,000 times larger and the limit is about °C, which does not matter.

References



  • K. J. Åström and T. Hägglund, Advanced PID Control, ISA, 2006.
  • K. J. Åström and B. Wittenmark, Computer-Controlled Systems: Theory and Design, 3rd edition, Prentice Hall, 1997.
  • K. J. Åström and R. M. Murray, Feedback Systems: An Introduction for Scientists and Engineers, 2nd edition, Princeton University Press, 2021.
  • D. E. Seborg, T. F. Edgar, D. A. Mellichamp and F. J. Doyle, Process Dynamics and Control, 3rd edition, Wiley, 2011.


© 2021-2026 SiliconWit®. All rights reserved.
Predict first

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?

smooth outputheld output one step = one sample, Ts
See it: the same PI loop, sampled more and more slowly

Overshoot
Estimated phase margin
Settling time, 0.01 bar
Error area, IAE

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.

Check yourself

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?

Watch it build: one tick of the pump controller
e = 4.50 − 4.00 = 0.50 bar 55 75 60 u, % stored Pump PI: Kc 15, Ti 3 s, Ts 0.1 sstored integral 60 % P = 15 × 0.50 = 7.5 P 7.5 I = 60 + 0.25 = 60.25 0.25 = 15 × 0.1 ÷ 3 × 0.50 D = 0 (PI) u = 67.75 % 67.75 +5.0 72.5 Ts 2 s: I = 60 + 5.0 u = 72.5 %
  1. First automatic tick of the pump PI: setpoint 4.50 bar, reading 4.00 bar, error 0.50 bar.
  2. Proportional: 15 × 0.50 = 7.5 percent, from this sample alone.
  3. Integral: one rectangle, 15 × 0.1 ÷ 3 × 0.50 = 0.25, added to the stored 60 percent.
  4. No derivative in this PI loop. The output is 7.5 + 60.25 = 67.75 percent.
  5. The same code called every 2 s adds 5.0 to the integral: 72.5 percent from the same settings.
Pressure transmitter 150 Ω resistor ADC 12 bit Scale counts to bar 4 to 20 mA 0.6 to 3 V 0 to 4095 PID, every Ts seconds y setpoint r (bar) timer tick, every Ts Output Variable speed drive Pump u (0 to 100 %)
Signal path of the firmware loop
u 0 Ts 2Ts 3Ts 4Ts 5Ts 6Ts 7Ts t ideal output (smooth) held output (steps) dashed: the smooth curve moved Ts/2 later the steps follow the smooth curve Ts/2 later
A held output is half a sample late on average (example curve)
tick k tick k+1 read ADC scale, PID write idle read ... short and constant Ts
One timer tick (not to scale)
+24 V Transmitter 4 to 20 mA 150 Ω 0.6 V to 3.0 V 0 V ADC 12 bit 3.3 V input ground
Current loop input
Found this useful?

Discussion

    Comments show your name. Be kind, stay on the topic.