electronics engineering
Course handbook · Fifth year
Digital Control
- 8Topics
- 8Solved exercises
- 34Formula sheet
Free handbook generated from the lessons of the site and updated often, every time a lesson or an exercise changes: the latest version is always at www.electronics-engineering.com/handbook/digital-control. Links work in the PDF too.
1Sampled-data systems
Today almost every controller is a program: a microcontroller reads the measurements with an analogue-to-digital converter, computes the command and sends it to the actuator with a digital-to-analogue converter. The process, however, remains continuous. A system in which continuous signals and sequences of samples coexist is called sampled-data, and designing it requires a model that brings them together. In this lesson we look at the digital control loop, the discrete transfer function of the process as seen by the computer with its proof and three examples, the zeros introduced by sampling and what happens between one sample and the next.
The digital control loop

Every
seconds the A/D converter samples the output, the program computes
and the D/A converter holds it constant until the next update: this is the zero-order hold (ZOH), already seen in the Process Control lesson on digital control, where it was shown that at low frequencies it is equivalent to a delay of
and how
is chosen.
The computer sees only sequences:
going out and
coming in. The natural tools are therefore the z-transform and difference equations (Signal Theory and Systems Theory lessons on discrete-time systems). The controller is a transfer function
; what is needed is the discrete equivalent of the process, i.e. the function relating the sequence
to the sequence
.
The transfer function with the hold
Theorem. If the process has transfer function
and is preceded by a zero-order hold, the discrete transfer function from
to
is
![]()
where
is the z-transform of the samples
of the process step response
.
Proof. The system from
to
is linear and time-invariant in discrete time, so its transfer function is the z-transform of the response to the unit impulse
,
for
. With this input the hold produces a rectangle of height 1 and width
, i.e. a step at time 0 minus a step at time
. By linearity the process responds with
, and the samples are
. The second term is the first one delayed by one step, and a one-step delay in the z-transform is a multiplication by
. So the transform of the samples is
times the transform of
, and the Laplace transform of
is
. ∎
The model is exact at the sampling instants: there is no approximation, unlike the methods that approximate derivatives.
Three examples
First order. With
we have
, hence
and
![]()
Multiplying by
:
![]()
The continuous pole
has become the discrete pole
, and the static gain
is unchanged, as in exact state-space discretisation (Systems Theory lesson on discrete-time systems).
Integrator. With
the step response is the ramp
, with transform
. So
: the command accumulates, multiplied by the period.
Double integrator. With
(a mass pushed by a force, a rotating satellite) we have
, with transform
, and
![Rendered by QuickLaTeX.com \[ G(z) = \frac{T^2}{2}\cdot\frac{z + 1}{(z - 1)^2} \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-f484307cde716102cc905e54f6b3840a_l3.png)
Sampling zeros
The last example shows an important fact: the continuous process
has no zeros, but its discrete equivalent has a zero at
. Sampling creates zeros that the continuous process does not have. A process with
poles and no zeros generally becomes a discrete system with
zeros. For small periods these zeros tend to values that depend only on the relative degree, and from relative degree 3 upwards at least one lies outside the unit circle: the discrete model is non-minimum-phase even if the continuous process is not. So not all the zeros of the model can be cancelled by the controller’s poles, as we will see in the lesson on deadbeat control.
What happens between samples
The z-domain model describes the output only at the instants
. Between one sample and the next the output can do things the computer does not see:
- hidden oscillation (inter-sample ripple), typical of very aggressive controllers: the samples sit on the reference, but the continuous output oscillates;
- pathological sampling: if an oscillating mode of the process has frequency
with
a multiple of
, its samples make it look constant or alternating, and the sampled system can lose the reachability or observability that the continuous system had.
For this reason the design is always checked with a continuous simulation of the process too, and the period is chosen with a generous margin: from 10 to 30 samples per closed-loop rise time.
2Stability in the z-plane
In continuous control a system is stable if the poles have negative real part; in digital control the good region is the inside of the unit circle. The link between the two worlds is the exponential function
, which also explains why sampling makes stability harder. In this lesson we look at the correspondence between the s-plane and the z-plane, the Jury criterion for second order with its full proof, and two examples showing how sampling and computation delay limit the gain.
From the s-plane to the z-plane
A continuous mode
sampled with period
gives the sequence
, i.e. a discrete mode with pole
![]()
(Systems Theory lesson on discrete-time systems, where we saw that the eigenvalues of
are the exponentials of those of
).

Theorem. The point
has negative real part if and only if
lies inside the unit circle.
Proof.
, because
. And
if and only if
. ∎
The same proof says more: vertical lines
constant become circles of radius
, and horizontal lines
constant become rays at angle
. Points differing by
in
end up at the same
: this is aliasing (lesson on the sampling theorem), and the correspondence is one-to-one only in the strip
.
A linear discrete system is therefore asymptotically stable if and only if all the poles of the closed-loop transfer function have modulus less than 1. The closer the pole is to the origin, the faster the mode dies out; a pole at
corresponds to a mode that vanishes in a single step, with no continuous equivalent.
The Jury criterion for second order
For continuous polynomials there is the Routh criterion; for discrete ones there is the Jury criterion, which decides whether all the roots are inside the unit circle without computing them. For second order it has a very simple form.
Theorem. The roots of
, with real coefficients, both lie inside the unit circle if and only if
![]()
Proof. Let
be the roots:
and
.
Necessary conditions. If the roots are inside the circle,
. If they are complex conjugate,
and
. If they are real and in
, the factors
and
are positive, so
and
.
Sufficient conditions. If the roots are complex conjugate,
. If they are real,
is an upward parabola, positive at
and at
: the roots are both in
, or both greater than 1, or both less than
(if one were below
and the other above
,
would be negative). In the last two cases
, contradicting the hypothesis. ∎
For higher orders the Jury criterion builds a table similar to Routh’s. Alternatively the bilinear transformation
is used, which maps the inside of the unit circle onto the left half of the
-plane (lesson on discretisation), followed by the Routh criterion.
Example: sampling limits the gain
Let an integrator,
, be controlled with a proportional action
. In continuous time the closed loop has pole
, stable for any
. Digitally, with the hold,
(lesson on sampled-data systems), and the characteristic polynomial of
is
![]()
stable if and only if
, i.e.
. For
the pole is at zero and the error vanishes in one step; for
the response is stable but alternating, the sign of a controller that over-corrects; beyond 2 it diverges. The admissible gain is limited by the period: the controller acts “blindly” for a whole period before seeing the effect of its action.
Example: one step of computation delay
If the command computed with sample
is applied only at instant
(lesson on implementation), the loop also contains a delay
:
and the characteristic polynomial is
![]()
With
and
, the Jury criterion requires
,
and
: the maximum gain has halved, from
to
. At the limit
the roots are
, right on the unit circle: a sustained oscillation with six samples per period.
Frequency response
The Nyquist criterion also holds in discrete time (lesson on the Nyquist criterion):
is plotted for
from 0 to
, i.e. along the unit circle instead of the imaginary axis. Gain and phase margins have the same meaning, and are read on the Bode plots of the discrete loop function, which stop at the Nyquist frequency.
Stability and design in the z plane in depth: Jury, root locus, discrete Bode and Nyquist
This page goes deeper into the lessons on stability in the z plane and direct design of digital controllers. It extends the Jury criterion to higher orders, shows how to use the bilinear transformation and the Routh criterion, and studies a complete case in depth: a DC motor driven by a digital proportional controller. For this case we draw the discrete root locus and the discrete Bode and Nyquist plots, and see how the sampling period reduces the admissible gain and the phase margin. At the end are the examples in MATLAB and Python, with verified code.
The Jury criterion for every order
For
, with
, the necessary conditions (quick to check, and often enough to rule out stability) are
![]()
Why. If all the roots
are inside the circle,
: for real roots
, for complex pairs
. In the same way
. Finally
. ∎
For third order a single condition is added, which together with the others becomes necessary and sufficient:
![]()
and for higher orders the Jury table builds successive rows (each new row is a
determinant between the first and last coefficient of the previous row), with a magnitude condition for each.
Example.
:
;
;
;
. Stable: the roots have moduli 0.68, 0.38 and 0.38.
The bilinear transformation and Routh
With
the inside of the unit circle goes to the left half of the
plane (lesson on the Z transform). Multiplying
by
gives a polynomial in
to which Routh can be applied. For second order
:
![]()
and “all coefficients positive” gives back exactly the three Jury conditions. The advantage of the bilinear transformation is that for high orders a criterion already known is reused.
A complete case: the sampled motor
A DC motor, with position as output, has
(normalised constants). It is driven by a proportional controller
in a microcontroller with
s, through a D/A with hold. The exact model at the sampling instants (ZOH, lesson on sampled-data systems) is
![]()
The pole at 1 is the integrator, the one at
is the mechanical time constant; the zero at
does not exist in continuous time: sampling creates it.
Stability. Characteristic polynomial
. Jury:
gives
;
;
gives
. So
. In continuous time the closed loop
is stable for every
: sampling has introduced a limit.

The discrete root locus is drawn with the same rules as in continuous time (Control Systems lesson); only the stability boundary changes, which is the unit circle instead of the imaginary axis. At the limit
the polynomial is
, with roots
of modulus 1 and angle
: a sustained oscillation with
samples per period, i.e. a period of 3.3 s.
The maximum gain depends on the period. Repeating the calculation for other periods:
with
s, 4.36 with 0.5 s, 2.39 with 1 s, 1.46 with 2 s. As
the limit tends to infinity, as in continuous time.

Discrete Bode and Nyquist
The frequency response of a discrete system is
, from
to the Nyquist frequency
. The Nyquist criterion holds unchanged, with the contour along the unit circle (going round the pole at
) instead of the imaginary axis:
, with
the poles of
outside the circle.
The hold is half a sample of delay. The staircase signal produced by the D/A lags, on average, the sampled signal by
. In frequency, for small
,
: the magnitude hardly changes, the phase loses
. For the motor with
: continuous phase margin 51.8° at 0.786 rad/s; discrete 40.8°. The difference, 11°, is exactly
radians, i.e. 11.3°.


In time. With
the continuous system has
and an overshoot of 30 %; the one sampled with
s reaches 56 %, and its output is a staircase that follows the continuous curve with a visible lag.

An integrator with one step of computation delay
The case of the lesson,
: poles at 0 and 1, breakaway at
for
, then the branches rise along the vertical line
(constant sum of poles, equal to 1) and meet the unit circle at
for
: angle 60°, six samples per period.

The digital motor in MATLAB and Python
MATLAB:
G = tf(1, [1 1 0]); % motor G(s) = 1/(s(s+1))
Gd = c2d(G, 0.5, 'zoh') % discrete model with hold
rlocus(Gd); zgrid % locus with unit circle and damping spirals
[Gm, Pm] = margin(Gd) % discrete margins
step(feedback(2*G, 1), feedback(2*Gd, 1))Python (numpy and python-control):
import numpy as np
import control as ct
G = ct.tf([1], [1, 1, 0]) # motor G(s) = 1/(s(s+1))
for T in (0.1, 0.5, 1.0):
Gd = ct.sample_system(G, T, method='zoh')
gm, pm, wpc, wgc = ct.margin(Gd)
print(f"T = {T}: Kmax = {gm:.2f}, PM = {pm:.1f} degrees")
gm, pm, wpc, wgc = ct.margin(G)
print(f"continuous: PM = {pm:.1f} degrees at {wgc:.3f} rad/s")Running it prints
, 4.36 and 2.39 for the three periods, with phase margins (for
) of 49.6°, 40.8° and 30.4°, and 51.8° for the continuous system (the library may warn that, for numerical accuracy, it computes the margins on the frequency response: this is normal). The gain margin of
coincides with
because the controller is proportional.
Exercises with Jury, the discrete locus, maximum gains and margins are on the exercise page linked at the top.
Exercises
Exercises on the stability and design of digital control systems of the kind set in Digital Control courses, in three levels: basic, with the Jury criterion and the maximum gains of simple systems; intermediate, with the discrete root locus and the bilinear transformation; exam, with computation delay, the choice of the sampling period and the comparison between continuous and discrete. The result is given straight away; the full solution, with the graph, opens with a click. The proofs and the MATLAB and Python code are in the in-depth study linked at the top.
Basic level
Exercise 1. Jury at third order
Determine whether
has all its roots inside the unit circle, without computing them.
Exercise 2. A first-order process
The process
is controlled by a digital proportional controller with
s and hold. Find the maximum gain, the steady-state step error with
and the gain that puts the pole at
.
Exercise 3. The period sets the gain
An integrator
is controlled with a gain
; the controller applies the command with one step of computation delay. With
ms, what is the maximum gain? And the gain at which the poles break away?
Intermediate level
Exercise 4. Bilinear transformation and Routh
For which
is the system with characteristic polynomial
stable? Use the bilinear transformation and check with the root locus.
Exercise 5. The sampled motor
For the motor
sampled with
s (in-depth study), check
with Jury and find the frequency of the oscillation at the limit.
3Discretising continuous controllers
The most common way to obtain a digital controller is to design it in continuous time, with the tools of Automatic Control, and then translate it into a difference equation. This is called design by emulation. The translation is done by replacing
with a function of
that approximates the derivative, and the choice matters: one method can make a stable controller unstable, another shifts the frequencies. In this lesson we look at the Euler and Tustin methods, the proofs of how they transform the left half-plane, frequency warping with prewarping, and a discretised PI.
Three approximations of the derivative
A derivative can be approximated by the forward difference quotient, the backward one, or by integrating with the trapezoidal rule. In terms of the z-transform, where
is a one-step advance:
| Method | Substitution | Inverse |
|---|---|---|
| Forward Euler | ||
| Backward Euler | ||
| Tustin (trapezoidal, bilinear) |
Each method carries the poles of the continuous controller to points of the z-plane. The question is: does a stable pole stay stable?

What happens to stability
Theorem. With the Tustin method a point
has negative real part if and only if its image
lies inside the unit circle; the imaginary axis goes onto the circle.
Proof. With
and
,
:
![Rendered by QuickLaTeX.com \[ |z|^2 = \frac{|1 + a + jb|^2}{|1 - a - jb|^2} = \frac{(1 + a)^2 + b^2}{(1 - a)^2 + b^2} \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-1dca0371c3d18f177083222cdc5793dd_l3.png)
The numerator exceeds the denominator by
. So
if and only if
, i.e.
, and
if and only if
. ∎
A stable continuous controller thus becomes a stable digital controller, and an unstable one stays unstable: Tustin preserves stability exactly.
Theorem. With backward Euler the left half-plane goes into the circle centred at
with radius
.
Proof. From
:
![]()
and
if and only if the point
is closer to
than to
, i.e. if
. In that case
. ∎
The small circle lies inside the unit one: a stable controller stays stable, but some unstable controllers become stable too, and the dynamic behaviour is distorted.
With forward Euler, on the other hand, the stable pole
becomes
, which leaves the circle if
. A controller with a pole that is fast compared with the period becomes unstable: the method should only be used with periods much smaller than all time constants, and this is the same stability limit as explicit numerical integration (Numerical Calculus lesson on differential equations).
Frequency warping
Tustin preserves stability but not frequencies. To see where the imaginary axis ends up, compute the value of
corresponding to
:
![]()
(factoring
out of numerator and denominator). The digital controller at frequency
behaves like the continuous one at frequency
![]()
For small
,
and
; near the Nyquist frequency
the tangent goes to infinity, and the whole continuous frequency axis is compressed into the interval from 0 to
. It is the same frequency warping as in IIR filters (Digital Signal Processing lesson on IIR filters and the bilinear transform).
Example. With
ms, a lead network with its zero at 200 Hz (
rad/s) ends up, in the digital controller, at frequency
rad/s, i.e. about 179 Hz: a 10 % error.
Prewarping eliminates the error at a chosen frequency
, the most important one (the zero of the network, the crossover frequency, the frequency of a notch filter):
is replaced by
. At frequency
the two controllers coincide exactly.
Other methods
- Matched pole-zero: every pole and zero is mapped with
, and the static gain is adjusted. It preserves pole positions exactly. - Step invariance: the controller is discretised as if it were a process preceded by a hold (lesson on sampled-data systems).
Whatever method is used, emulation neglects the
delay of the hold and the computation delay, which reduce the phase margin (lesson on implementation). It works well if sampling is fast, 20 to 30 times the closed-loop bandwidth; with longer periods direct design in the z-plane is preferable.
Example: a PI with Tustin
The controller
with the Tustin substitution becomes
![]()
Multiplying by
and going back to the time domain (
is a one-step advance), we obtain the algorithm
![]()
It is already in incremental form (Process Control lesson on digital control): it computes the change of the command, and lends itself well to limiting the integral action against saturation.
4Implementation
A digital controller designed well on paper can work badly on the microcontroller. Computation takes time, converters have a finite number of levels, arithmetic has limited precision, and the program shares the processor with other tasks. In this lesson we look at computation delay and the proof of its cost in phase margin with an example, timing variability, the effects of quantisation with the proof of a steady-state error that integral action cannot remove, and the practical rules for a robust implementation.
Computation delay

Between sampling the measurement and updating the command, the computation time
elapses. There are two choices:
- update the command as soon as it is ready: the delay is
, but it varies from one cycle to the next; - update it at the next sampling instant: the delay is always a whole period
, larger but constant and easy to include in the model as a factor
(lesson on stability in the z-plane, where one step of delay halved the maximum gain).
Theorem. A pure delay
in the loop leaves the magnitude of the loop function unchanged and reduces its phase by
radians; the phase margin decreases by
, where
is the crossover frequency.
Proof. The delay has transfer function
, and in sinusoidal steady state
, with magnitude 1 and phase
. Multiplied by the loop function
, it does not change the frequency at which
and subtracts
from the phase at that point, hence from the margin. ∎
The computation delay adds to that of the hold, about
(Process Control lesson on digital control), and that of the anti-aliasing filter in front of the A/D.
Example. With
rad/s,
ms and update at the next sample (
), the margin loss is
rad, about 8.6°. With
ms it would be 86°: the system would almost certainly become unstable.
A simple rule reduces the delay: first compute and write the output, then update the controller state. In most algorithms the output depends on the new measurement through a single product and a sum; all the other computations (updating integrators, filters, diagnostics) are done afterwards, while waiting for the next sample.
Timing variability
If sampling does not happen at exactly regular intervals, or the computation time varies (interrupts, caches, other tasks), the delay fluctuates: this is jitter. The controller is designed for a fixed
, and large jitter is equivalent to an extra disturbance and a loss of margin. It is fought by triggering the A/D converter from a hardware timer, not from the program, updating the D/A the same way, and giving the control task the highest priority in a real-time operating system.
Quantisation
An
-bit A/D converter distinguishes
levels (Signal Theory lesson on quantisation); the D/A and the program’s internal numbers also have a minimum step. In the closed loop quantisation produces non-linear effects: dead zones and limit cycles, small permanent oscillations of one or two steps.
Theorem. Consider an integral action in incremental form
, with the command represented with step
and the increment rounded to the nearest step. Then a constant error with
is never corrected.
Proof. If
, rounding
to the nearest multiple of
gives 0: the command does not change, the output does not change and the error stays the same. The situation repeats identically at every step. ∎
Example. A 12-bit command normalised to full scale,
, and
(slow integral action, fast sampling): the error can remain up to
, i.e. 12 % of full scale, despite the integral action. The paradox is that sampling faster makes things worse, because it reduces
.
The remedy is to keep the integrator with more bits than the command (for instance 32 bits, or by accumulating the rounding remainder) and to quantise only at the output towards the D/A. The same problem affects the coefficients: with fast sampling the poles approach
(because
) and filter coefficients become numbers like 0.9995 that need many bits. Filter structures matter (Digital Signal Processing lesson on digital filter structures): cascades of second-order sections, or the delta operator
, which works on the difference between samples.
Other practical rules
- Saturation and anti-windup: the actuator has limits; when the command saturates, the integrator must be stopped or wound back (Automatic Control lesson on the PID controller). In incremental form it is enough to saturate the accumulated command.
- Bumpless transfer between manual and automatic: on engagement the controller is initialised with the current command.
- Fixed-point arithmetic with saturation instead of overflow, which would turn a large positive number into a large negative one.
- Anti-aliasing filter before the A/D, because a high-frequency disturbance, once sampled, folds back to low frequency and the controller tries to correct it.
- Watchdog and plausibility checks: if the program hangs or a measurement is absurd, the actuator must be brought to a safe condition.
From the Simulink model to ECU code: a digital controller with the Z transform, also in Python
This page shows how a digital controller goes from design to the code running in a microcontroller or in a car’s electronic control unit (ECU), following the workflow used in industry: the model in Simulink, discrete-time blocks based on the Z transform, simulation, automatic generation of C code and testing in several stages. The same control is then rebuilt in Python, with free libraries, and the code is verified. The example is the speed control of an electric motor, but the structure is identical for the idle speed of a combustion engine, turbo boost pressure, cruise control or the torque of a traction motor.
Why the Z transform is the language of ECUs
An ECU does not solve differential equations: at fixed intervals (for example every 10 ms) it reads the sensors, runs a piece of code and updates the outputs. The controller is therefore a discrete-time system, described by a difference equation, and its transfer function is in
(lesson and in-depth study on the Z transform). In Simulink this is visible directly: the blocks of the *Discrete* library (Unit Delay, which is exactly
, Discrete Transfer Fcn, Discrete-Time Integrator, Discrete PID Controller) all have a *Sample time* parameter and correspond one to one to lines of code. The physical process, on the other hand, stays continuous (*Transfer Fcn*, *Integrator* blocks), and the simulator integrates it with a fine step.
The model
The motor, driven by a voltage
, has speed
with transfer function
![]()
and the power driver can deliver at most
V. The controller is a PI running at
ms.

In Simulink the diagram is built like this:
- Step for the reference (0 → 200 rad/s at
s), Sum with signs
; - Discrete PID Controller in *Parallel* form,
,
, *Sample time*
, *Integrator method* Forward Euler (the default); - in the *Output Saturation* tab the limits
and, in the *Anti-windup* tab, the *clamping* method; - Transfer Fcn with numerator
20and denominator[0.5 1]for the motor; - the hold need not be drawn: a discrete block driving a continuous block keeps its output constant between samples, which is exactly the ZOH;
- in the model settings: a fixed-step solver (for example
ode4) with a 1 ms step, or a variable-step one for simulation only. Code generation needs a fixed step, and the controller rate must be a multiple of the base step.
Inside the PI block: difference equations
With forward Euler integration the PI is
![]()
i.e., in
,
. The state
is stored in a Unit Delay: it is the variable that “remembers” the value from the previous step.

Anti-windup. When the actuator is saturated, the error stays large and the integrator keeps growing: in the end, when the output approaches the reference, the accumulated integral causes a large overshoot. The *clamping* method stops integrating while the output is saturated. In the simulation below, without anti-windup the speed reaches 235 rad/s (17.5 % overshoot) and settles in 3.2 s; with anti-windup it does not exceed 200 rad/s and settles in 1.7 s.


From the model to the code
With Embedded Coder (MathWorks’ code generator for embedded systems) the discrete subsystem becomes C code. The typical structure, simplified, is this:
/* model states (DWork): one for each Unit Delay or integrator */
typedef struct { float I; } DW_motor_ctrl;
static DW_motor_ctrl dw;
void motor_ctrl_initialize(void) { dw.I = 0.0f; }
/* called by the scheduler every 10 ms */
float motor_ctrl_step(float ref, float w)
{
float e = ref - w;
float u_lib = 0.25f * e + dw.I;
float u = u_lib > 12.0f ? 12.0f : (u_lib < -12.0f ? -12.0f : u_lib);
if (u == u_lib) { /* anti-windup: clamping */
dw.I += 0.5f * 0.01f * e; /* I[k+1] = I[k] + Ki*T*e[k] */
}
return u;
}The generator also produces an example main program (ert_main.c) in which a function called by a timer, rt_OneStep(), runs model_step() at every period. In an automotive ECU the step function becomes an AUTOSAR runnable assigned to a periodic task of the operating system (for example the 10 ms task), which reads the signals from the CAN bus or the converters and writes the outputs.
Important details in practice:
- execution times: reading the A/D, computing and writing the D/A take part of the period; the command is applied with a delay
that adds to the half sample of the hold and removes phase margin (in-depth study on stability in the z plane); - arithmetic: many low-cost ECUs have no floating-point unit, and code is generated in fixed point, with scalings chosen so as not to lose resolution or overflow;
- multiple rates: fast controllers (current, 100 µs) and slow ones (temperature, 100 ms) coexist; *Rate Transition* blocks handle data passing between different tasks;
- functional safety: in automotive the development process follows ISO 26262, which requires traceability between requirements, model, code and tests.

Testing: MIL, SIL, PIL, HIL
The model is also the reference for verifying the code, in successive stages:
- MIL (*model in the loop*): the complete model, controller and process, is simulated on the PC;
- SIL (*software in the loop*): the generated C code, compiled for the PC, replaces the controller block and the results must match the MIL;
- PIL (*processor in the loop*): the same code runs on the real processor (or a simulator of it), connected to the process model on the PC: execution times and memory are measured;
- HIL (*hardware in the loop*): the complete ECU is connected to a real-time simulator that reproduces the vehicle and the sensors; faults can also be tested, without risk;
- finally the tests on the vehicle.

The same control in Python
Python has no complete equivalent of Simulink, with automatic generation of certifiable code for ECUs. For design and simulation, however, free libraries are enough: numpy and scipy for computation, python-control for transfer functions, matplotlib for plots. The controller loop is written explicitly, sample by sample, and it is exactly the same code that will end up in the microcontroller. The continuous process is simulated with its exact model with hold,
with
(exercise 8 on the Z transform):
import numpy as np
# process: motor, speed w [rad/s] driven by voltage u [V]
Km, tau = 20.0, 0.5 # gain [rad/s/V] and time constant [s]
T = 0.01 # controller period: 10 ms
a = np.exp(-T / tau) # exact model with hold (ZOH)
# discrete PI controller (forward Euler integrator, as in Simulink's
# Discrete PID Controller block with default settings)
Kp, Ki = 0.25, 0.5 # [V/(rad/s)], [V/(rad/s)/s]
Umax = 12.0 # maximum driver voltage
def simulate(antiwindup, t_end=4.0):
n = int(t_end / T)
w = 0.0 # process state
I = 0.0 # integrator state (Unit Delay)
out = []
for k in range(n):
t = k * T
ref = 200.0 if t >= 0.1 else 0.0
e = ref - w # sensor reading and error
u_free = Kp * e + I # PI output
u = min(max(u_free, -Umax), Umax) # saturation
if not antiwindup or u == u_free: # clamping anti-windup
I = I + Ki * T * e
w = a * w + (1 - a) * Km * u # the motor evolves for one period
out.append((t, ref, w, u))
return np.array(out)
for aw in (False, True):
r = simulate(aw)
t, w = r[:, 0], r[:, 2]
outside = np.where(abs(w - 200) > 4)[0] # samples outside the 2 % band
print(f"anti-windup={aw}: max {w.max():.1f} rad/s, "
f"overshoot {max(0.0, 100 * (w.max() - 200) / 200):.1f} %, "
f"2 % settling at t = {t[outside[-1] + 1]:.2f} s")Running it prints:
anti-windup=False: max 235.1 rad/s, overshoot 17.5 %, 2 % settling at t = 3.22 s
anti-windup=True: max 200.0 rad/s, overshoot 0.0 %, 2 % settling at t = 1.72 sand the plots on this page were drawn from exactly these data. For more complex systems, python-control allows continuous and discrete blocks to be connected with ct.interconnect and simulated with ct.input_output_response. Free alternatives to Simulink with a graphical block editor are Xcos (included in Scilab) and OpenModelica; the Python library bdsim allows block diagrams to be described in code.
How the parameters were chosen. The PI zero, at
rad/s, cancels the motor pole at
rad/s; what remains is a first-order loop
, with time constant
s. With
ms there are ten samples per time constant: the sampling delay costs about 3° of phase margin, which is negligible (in-depth study on stability in the z plane).
Exercises on stability, root locus and margins of digital systems are on the exercise page linked at the top.
5Direct design in the z-plane
Instead of designing in continuous time and translating, one can design directly on the discrete model of the process, which is exact at the sampling instants (lesson on sampled-data systems). The advantage is that the delay of the hold and the computation delay are already in the model, and longer sampling periods can be used. In this lesson we look at how response specifications become a region of the z-plane, with the proof of the constant-damping spiral, the discrete root locus with a complete example, steady-state error with the final value theorem, and frequency-domain design.
Specifications in the z-plane
Step-response specifications translate, as in Automatic Control, into conditions on the dominant poles
(lesson on time response): the damping
sets the overshoot, the real part
sets the settling time, about
at 2 %. With
they become conditions on the z-plane.

- Settling time:
, so the poles must lie inside the circle of radius
. - Damping: poles with constant
lie on a spiral.
Theorem. The discrete poles corresponding to a fixed damping
lie on the logarithmic spiral
![Rendered by QuickLaTeX.com \[ |z| = \exp\left(-\frac{\zeta}{\sqrt{1 - \zeta^2}}\,\theta\right) \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-fa3296f813cdcec5cf901dae2b0dd738_l3.png)
where
is the angle of the pole.
Proof. The pole is
: modulus
and angle
. Obtaining
from the angle and substituting it into the modulus gives the formula. As
varies,
grows and the modulus decreases exponentially: it is a logarithmic spiral starting from
. ∎
The angle also has a practical meaning:
is the number of samples per period of the oscillation. With small
, below
, there are at least eight samples per oscillation and the behaviour between samples is well represented.
Example. With
s and a settling time of 1 s:
s
and
. With maximum overshoot of 16 %, i.e.
, the spiral factor is
. The green region of the figure satisfies both.
The discrete root locus
The characteristic equation
has the same form as in the continuous case, and the root locus is drawn with the same rules (Automatic Control lesson on the root locus): it starts from the poles, ends at the zeros or at infinity, and on the real axis occupies the segments with an odd number of poles and zeros to the right. Only the interpretation changes: the stability boundary is the unit circle, and the good regions are those of the figure.
Example. An integrator with one step of computation delay has
, with poles at 0 and 1 and no zeros. The locus occupies the segment
; the two branches meet at the midpoint
, where the polynomial
has a double root, i.e. for
; then they go up and down along the vertical line
(the sum of the roots stays 1). They leave the unit circle when the product of the roots
equals 1, as found with the Jury criterion (lesson on stability in the z-plane). The choice
gives a double pole at
, equivalent to the continuous pole
: a fast, non-oscillating response that settles in a few samples.
Steady-state error
As in continuous time, the steady-state error depends on the number of integrators in the loop. In discrete time an integrator is a pole at
.
Final value theorem. If the sequence
converges, its limit is
![]()
Proof. The transform of the difference
is
. Evaluating the series that defines it as
(where the terms
tend to 1) gives the sum of all the differences, which is
. So
. ∎
With the step
and the error
, the steady-state error is
: zero if
has at least one pole at
, otherwise
. The rules on system type (lesson on steady-state errors) hold with
in place of
.
Frequency-domain design
To use Bode plots and continuous compensators (lesson on compensators) the discrete model is transformed with the w-transform:
![]()
which maps the unit circle onto the imaginary axis (lesson on discretisation). In the w-plane the process, already including the hold and delays, is treated as a continuous transfer function: the compensator is designed with margins and bandwidth, and brought back to
with the inverse substitution, without further approximations. The w-plane frequency
and the true one are related by the tangent,
, to be kept in mind in the specifications.
6Pole placement and deadbeat control
In state space, digital control has a possibility that does not exist in continuous time: bringing the state exactly to zero in a finite number of steps with a linear control law. This is deadbeat control. In this lesson we look at the discrete state model, pole placement with Ackermann’s formula, the proof that deadbeat control cancels the state in
steps, the complete example of the double integrator, the price paid in control effort and the addition of integral action.
The model and state feedback
The process
,
, with the command constant between samples, becomes exactly
![Rendered by QuickLaTeX.com \[ x(k+1) = \Phi x(k) + \Gamma u(k),\qquad \Phi = e^{AT},\quad \Gamma = \int_0^T e^{A\tau}d\tau\,B \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-c0066c17d330bf4f23bf0a27d8310cc1_l3.png)
(Systems Theory lesson on discrete-time systems). With state feedback
the closed loop is
. If the system is reachable (lesson on reachability), the eigenvalues of
can be placed anywhere (Automatic Control lesson on state space). For a single input, Ackermann’s formula gives the gain that achieves the desired characteristic polynomial
:
![]()
A natural choice of poles is
, where the
are the poles of a good continuous design.
Deadbeat control
All the poles are placed at
.
Theorem. If all the eigenvalues of
are zero, then
for any initial state, where
is the order of the system.
Proof. The characteristic polynomial of
is
. By the Cayley-Hamilton theorem every matrix annihilates its own characteristic polynomial, so
. Then
. ∎
No linear continuous system can do this: the solution is a combination of exponentials, which approach zero without ever reaching it. In discrete time, instead, the nilpotent matrix “switches off” the state in
steps, and then keeps it at zero.
Example: the double integrator
With
(a unit mass pushed by a force), state
:
![]()
The deadbeat gain is
. Check:
![]()
with trace 0 and determinant
: the characteristic polynomial is
.

With
and initial state
: the first command is
, leading to
; the second is
, leading to
. The mass is set moving with one push and stopped with an equal and opposite push: the “bang-bang” strategy one would use by hand.
The price
Deadbeat is the fastest possible controller, and there is a price to pay:
- control effort: in the double integrator the gain is proportional to
. Halving the period, i.e. asking to reach zero in half the time, quadruples the command: with real actuators saturation is reached immediately; - sensitivity: all the poles at the same point make the system very sensitive to model errors and measurement noise;
- inter-sample oscillations: a deadbeat controller designed on the output rather than on the state can have the samples on the reference while the continuous output oscillates (lesson on sampled-data systems), especially if it cancels model zeros close to
.
In practice deadbeat is used as a reference limit, or with a period chosen so that the command stays within limits; more often the poles are placed at points close to the origin but distinct, or chosen with optimal control (lesson on LQ and predictive control).
Integral action
State feedback does not cancel the steady-state error in the presence of constant disturbances or model errors. A state integrating the error is added:
![]()
and the feedback is designed on the augmented system
, of order
, with
. If the augmented system is reachable (the process must not have zeros at
), the poles are placed as before, and at steady state a constant
forces
.
7Observers
State feedback (lesson on deadbeat control) requires knowing the whole state, but usually only part of it is measured: the position and not the velocity, the temperature at one point and not in the whole furnace. The observer reconstructs the state from measurements and commands, using the model. In discrete time it is simply one more difference equation in the program. In this lesson we look at the prediction observer and the dynamics of its error, the deadbeat observer with an example, the current observer, the separation principle with its proof, disturbance estimation and the Kalman filter.
The prediction observer
The program knows the model
,
, the commands it has issued and the measurements. It simulates the model in parallel with the process and corrects it with the difference between the measurement and its prediction:
![]()
Theorem. The estimation error
evolves according to
![]()
regardless of the command.
Proof. Subtracting the observer equation from that of the process, the terms
cancel and what remains is
. ∎
If the eigenvalues of
are inside the unit circle, the estimate converges to the true state whatever the initial error. The problem of choosing
is the dual of state feedback: the eigenvalues of
are those of
, and they can be placed anywhere if the system is observable (Systems Theory lesson on observability). The same methods are used, including Ackermann’s formula applied to the pair
.
The deadbeat observer
Placing all the eigenvalues of
at zero, the error vanishes in
steps (by the same Cayley-Hamilton argument as in the previous lesson): after
measurements the state is known exactly, in the absence of noise.
Example. Double integrator with
, measuring position only,
. With
:
![]()
with trace
and determinant
. To get the polynomial
both must be zero:
,
. The matrix becomes
, and its square is the zero matrix. After two position samples the observer knows the velocity too: it is, essentially, the difference quotient between two positions corrected for the effect of the command.
With noisy measurements such a fast observer amplifies noise; usually the observer poles are chosen 2 to 4 times faster than those of the controller, a compromise between speed and filtering.
The current observer
The prediction observer uses measurement
to estimate
: the estimate of
does not exploit the measurement that has just arrived. The current observer first makes a prediction and then corrects it with the measurement at the same instant:
![]()
The command computed from
reacts without a one-step delay, at the cost of having to do the computation between sampling and updating (lesson on implementation). It is the same prediction-correction structure as the Kalman filter.
The separation principle

The estimate is used in place of the state:
. Is it legitimate to design
and
separately?
Theorem (separation principle). With
and the prediction observer, the closed-loop eigenvalues are the union of the eigenvalues of
and those of
.
Proof. Use as variables the state
and the error
. Since
:
![]()
and by the previous theorem
. In matrix form:
![]()
The matrix is block triangular, and its characteristic polynomial is the product of those of the diagonal blocks. ∎
The controller and the observer are thus designed independently. Beware, though: separation concerns the poles, not robustness. The stability margins of the whole can be much smaller than those of true state feedback, and must be checked.
Estimating disturbances
An unknown constant disturbance
at the input is modelled as an extra state that does not change,
, with
. If the augmented system is observable, the observer also estimates
, and the controller compensates it with
. The result is integral action obtained by another route, which extends to sinusoidal disturbances (with an oscillator in the disturbance model) and to other known shapes: this is the internal model principle.
The Kalman filter
When the process is subject to random disturbances and the measurements to noise, with known variances, there is an optimal gain
, which minimises the variance of the estimation error: the Kalman filter. The gain is obtained from a Riccati equation, dual to that of optimal control (lesson on LQ and predictive control), and automatically balances trust in the model and trust in the measurements: very noisy measurements give a small gain, an uncertain model gives a large gain. It is used everywhere: inertial and GPS navigation, battery state-of-charge estimation, target tracking.
8Optimal and predictive control
Pole placement leaves a question open: where to put the poles? Faster means larger commands, slower means errors that last longer. Optimal control answers by writing the trade-off as a cost to be minimised, and predictive control extends the idea to the constraints every real plant has: saturating actuators, temperatures and pressures not to be exceeded. In this lesson we look at the discrete linear quadratic (LQ) regulator with the derivation of the Riccati equation, a scalar example solved in closed form, and predictive control with the receding horizon, constraints and its applications.
The linear quadratic regulator
For the system
we look for the command sequence that minimises
![Rendered by QuickLaTeX.com \[ J = \sum_{k=0}^{\infty}\left(x(k)^TQx(k) + u(k)^TRu(k)\right) \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-fb604b82732d177fbf59699056ecc950_l3.png)
with
positive semidefinite (how much the error weighs) and
positive definite (how much the command weighs). Increasing
relative to
asks for a more “frugal” controller.
Theorem. The optimal solution is a state feedback
with
![]()
where
is the symmetric positive definite solution of the algebraic Riccati equation
![]()
and the minimum cost starting from
is
.
Proof (dynamic programming). Let
be the minimum cost starting from
. By Bellman’s principle of optimality, the optimal first step minimises the cost of the step plus the minimum cost from the next state:
![]()
Try
. The quantity in brackets is quadratic in
; its gradient with respect to
is
, and setting it to zero:
![]()
It is a minimum because the matrix
is positive definite. Substituting
, all the terms are of the form
, and the equality
holds for every
if and only if
satisfies the Riccati equation. ∎
If
is reachable and the state is “seen” by the cost (
observable), the solution exists, is unique and the closed loop is asymptotically stable. In practice the equation is solved numerically, with a single instruction in computing packages.
Example: an integrator
Take
, with
and
. With
the Riccati equation becomes
![]()
and
, with closed-loop pole
.
| pole | |||
|---|---|---|---|
| 0 | 1 | 1 | 0 (deadbeat) |
| 1 | 1.618 | 0.618 | 0.382 |
| 10 | 3.70 | 0.270 | 0.730 |
| 100 | 10.5 | 0.095 | 0.905 |
With a free command (
) the optimum is deadbeat (lesson on deadbeat control); with an expensive command the controller becomes slower and slower. For
the golden ratio appears,
. The designer no longer chooses the poles, but the weights, which have a direct physical meaning. Continuous LQ control also has guaranteed margins (infinite gain margin, at least 60° of phase); in discrete time the margins are somewhat smaller but remain good.
Together with the Kalman filter (lesson on observers) the LQ regulator forms LQG control, optimal when disturbances and noise are Gaussian, and thanks to the separation principle the two are designed independently.
Predictive control
The LQ regulator knows nothing about limits: if the optimal command exceeds the actuator’s saturation, it is simply clipped, and optimality and sometimes stability are lost. Predictive control (MPC, model predictive control) puts the constraints inside the problem.

At every sample the controller:
- measures (or estimates with an observer) the current state;
- using the model, predicts the evolution of the output over the next
steps as a function of the future command sequence
; - chooses the sequence that minimises a quadratic cost (error from the reference plus command effort) while respecting the constraints: limits on commands, on their rate of change, on outputs and on states;
- applies only the first command, discards the others, and at the next sample repeats everything with the new measurement.
Step 3 is a quadratic programming problem: quadratic cost, linear constraints, a unique solution that efficient algorithms find in microseconds or milliseconds. Step 4, the receding horizon, makes the scheme a true feedback: model errors and disturbances are corrected at every cycle.
Some properties:
- with no active constraints, predictive control is a fixed linear feedback; with an infinite horizon it coincides with the LQ regulator;
- stability is guaranteed by adding a terminal cost equal to the LQ cost
of the final state, and possibly a terminal constraint; - it knows reference changes and measurable disturbances in advance, and can start reacting before they occur;
- it naturally handles systems with many coupled inputs and outputs (Process Control lesson on multivariable systems).
Predictive control was born in the late 1970s in refineries, where processes are slow and there is time to compute, and today it is the standard for advanced process control. With modern processors it has reached fast systems: engine management and autonomous driving in cars, drones, power converters and traction electronics, where the “finite control set” version directly chooses the state of the switches (Power Electronics lessons).
✎Exam exercises
2. Stability in the z-plane
Exam level
Exercise 6. The price of computation delay
One step of computation delay is added to the sampled motor of exercise 5:
. How do the maximum gain and the phase margin with
change?
Exercise 7. Choosing the sampling period
A continuous control loop has crossover frequency
rad/s and a phase margin of 60°. Which sampling period guarantees losing no more than 5° of margin because of the hold? And if there is also one step of computation delay?
Exercise 8. Continuous versus discrete with the same gain
The motor
is controlled with
: compare the overshoot of the continuous system and of the one sampled with
s. Write the commands to check it.
✓Solutions
2. Stability in the z-plane · Exercise 1. Jury at third order
Result: yes: all the Jury conditions are satisfied (the roots have moduli 0.80, 0.80 and 0.62).
Coefficients:
,
,
,
.
1.
.
2.
.
3.
.
4.
.
Stable. The margin is small (
and condition 4 only just holds): the roots, computed afterwards, are
and
, with maximum modulus 0.80.

2. Stability in the z-plane · Exercise 2. A first-order process
Result:
; error
;
.
ZOH:
. Closed loop:
, pole
.
Stability:
requires
, i.e.
. In continuous time, for the same process, there is no limit.
Steady-state error:
, so
with
: the output goes to
. Without an integrator the error remains.
Pole at zero:
. The output reaches steady state in a single step (deadbeat response): a behaviour impossible in continuous time.
With
the pole is
, negative: the response oscillates slightly from sample to sample.

2. Stability in the z-plane · Exercise 3. The period sets the gain
Result:
s
; breakaway for
s
.
From the lesson, with the delay the polynomial is
and Jury gives
. With
:
.
The breakaway is halfway between the poles 0 and 1, where the polynomial has a double root: discriminant
,
,
. For
the response does not oscillate; between 25 and 100 it oscillates more and more; at the limit it has 6 samples per period.
To get more gain without losing stability one must sample faster:
is inversely proportional to
.

2. Stability in the z-plane · Exercise 4. Bilinear transformation and Routh
Result:
.
With
and
, the transformed polynomial (in-depth study) is
![]()
Routh for second order: all coefficients positive,
.
Locus. The polynomial is
: the locus of
, with poles at 1 and 0.5 and a zero at 0. It is a circle centred at the zero with radius
(continuous locus lesson: same geometry). The poles leave the unit circle on the real axis, at
, when
.

2. Stability in the z-plane · Exercise 5. The sampled motor
Result:
; oscillation with period 3.3 s (6.5 samples).
Polynomial
. The binding Jury condition is
:
,
(the others give
and
).
For
:
,
, angle
rad. The angular frequency of the oscillation is
rad/s, the period
s, i.e. 6.5 samples.
It is the same frequency
rad/s at which the phase of the discrete Bode plot is
: Jury, locus and Nyquist give the same information.

2. Stability in the z-plane · Exercise 6. The price of computation delay
Result:
falls from 4.36 to 1.49; the phase margin from 40.8° to 18.3°.
The characteristic polynomial becomes third order:
. With Jury, or by computing the roots as
varies (code of the in-depth study with
), one finds
.
In frequency,
has magnitude 1 and phase
: at the crossover frequency (about 0.78 rad/s) it removes
rad, i.e. 22.4°. The margin falls from 40.8° to 18.3°.
Remedies: sample faster (the delay, in seconds, gets shorter), or apply the command as soon as it is computed instead of at the next step, keeping the code between the A/D read and the D/A write to a minimum (lesson on implementation).

2. Stability in the z-plane · Exercise 7. Choosing the sampling period
Result:
ms; with the computation delay
ms.
The hold is equivalent to a delay of
: phase loss
. Requiring
rad:
ms.
With one more step of delay the total delay is
:
ms.
Equivalent rule of thumb: sample 20-40 times faster than the loop bandwidth (
Hz, so at least 30-60 Hz; at 170 Hz one is well on the safe side). In car ECUs fast controllers run at 1-10 ms, slow ones (temperature, level) at 100 ms.

2. Stability in the z-plane · Exercise 8. Continuous versus discrete with the same gain
Result: continuous 30.5 %; sampled 55.6 %.
Continuous:
,
,
, overshoot
%.
Sampled: polynomial
, roots
, modulus 0.887, angle 38.2°. The equivalent continuous pole
has
: much less damped, overshoot about 56 %.
MATLAB: G = tf(1,[1 1 0]); stepinfo(feedback(2*G,1)), stepinfo(feedback(2*c2d(G,0.5),1)). Python: ct.step_info(ct.feedback(2*G, 1)) and ct.step_info(ct.feedback(2*ct.sample_system(G, 0.5), 1)), which give 30.5 % and 55.6 %.
The lesson is general: a controller tuned in continuous time and placed in a slow processor loses damping. Either sample faster, or design directly in discrete time.

∑Formula sheet
Sampled-data systems
The transfer function with the hold
![]()
Three examples
![]()
![]()
![Rendered by QuickLaTeX.com \[ G(z) = \frac{T^2}{2}\cdot\frac{z + 1}{(z - 1)^2} \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-f484307cde716102cc905e54f6b3840a_l3.png)
Stability in the z-plane
From the s-plane to the z-plane
![]()
The Jury criterion for second order
![]()
Example: sampling limits the gain
![]()
Example: one step of computation delay
![]()
Discretising continuous controllers
What happens to stability
![Rendered by QuickLaTeX.com \[ |z|^2 = \frac{|1 + a + jb|^2}{|1 - a - jb|^2} = \frac{(1 + a)^2 + b^2}{(1 - a)^2 + b^2} \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-1dca0371c3d18f177083222cdc5793dd_l3.png)
![]()
Frequency warping
![]()
![]()
Example: a PI with Tustin
![]()
![]()
Direct design in the z-plane
Specifications in the z-plane
![Rendered by QuickLaTeX.com \[ |z| = \exp\left(-\frac{\zeta}{\sqrt{1 - \zeta^2}}\,\theta\right) \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-fa3296f813cdcec5cf901dae2b0dd738_l3.png)
Steady-state error
![]()
Frequency-domain design
![]()
Pole placement and deadbeat control
The model and state feedback
![Rendered by QuickLaTeX.com \[ x(k+1) = \Phi x(k) + \Gamma u(k),\qquad \Phi = e^{AT},\quad \Gamma = \int_0^T e^{A\tau}d\tau\,B \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-c0066c17d330bf4f23bf0a27d8310cc1_l3.png)
![]()
Example: the double integrator
![]()
![]()
Integral action
![]()
Observers
The prediction observer
![]()
![]()
The deadbeat observer
![]()
The current observer
![]()
The separation principle
![]()
![]()
Optimal and predictive control
The linear quadratic regulator
![Rendered by QuickLaTeX.com \[ J = \sum_{k=0}^{\infty}\left(x(k)^TQx(k) + u(k)^TRu(k)\right) \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-fb604b82732d177fbf59699056ecc950_l3.png)
![]()
![]()
![]()
![]()
Example: an integrator
![]()