Latest news

Digital PID Controller: One practical modeling for microcontrolers – Part 2

No comments

Continuing from the point at which we stopped in the first part of this series, we will now model a digital PID with a slightly different approach than the one used to design the compensator described in the previous article, the idea here is to provide a PID compensator that can be implementable in a way simple in a general purpose processor (as discussed in part I of this series, general purpose processor is meant any microcontroller that has at least the hardware multiplication instruction).

Shall we recap?

In part I of this series, it was explained what is a closed-loop control system, the reason of its use, as well as the PID (Proportional – Integral – Derivative) type compensator as a versatile type of controller applied in large control systems of the most varied types.

We still remember that its expression takes the form of an equation, as the one exemplified below:

  • Kp: Proportional action coefficient;
  • Ki: Coefficient of integral action;
  • Kd: Derivative action coefficient
  • t: State of the state to be processed;
  • u (t): System output signal at time t;
  • and (t): Error signal at controller input at time t.

From this equation followed by the use of the well – known Laplace transform, a much simpler equation was obtained than the one exemplified above, so that an electronic circuit could be designed to reproduce the behavior of a PID compensator.

In contrast, in order to implement a component of these software paths (in a microcontroller), both one equation and the other, are very difficult to implement, so, using an approach based on numerical methods, we were able to design an equation easily programmable on a processor:


Where, the parameters (constants) can be calculated as follows:

In addition we have:

ti = integration time

td = Time of differentiation.

Also adopted was a name called the rectangular approximation of the integral term, so it could translate this simple equation into a program that can be embedded in the processor to be used.

Problems with the rectangular approximation

Although the rectangular approximation algorithm of the integral term is versatile and serves a good range of applications, some problems begin to emerge as the complexity of the system being controlled increases.

The first and great problem is the convergence of the integral of the error function to the correct value when the previous value of this error function is equal to zero, or when the difference between the current and the previous error becomes very large, this problem could be corrected by increasing the number of iterations for calculating the integral term (and not based on two points), but at the expense of execution efficiency.

Another solution would be to approximate the integral only by accumulating its value, each time the PID is computed, this maintains the efficiency of the code execution, and causes the same effect of the increase of iterations, however the accumulation would occur only once in each value of the computed PID, returning the problem of slow convergence in the results of the integral in the first values ​​calculated by the PID, as the process advances this effect is being minimized.

The other big problem of this algorithm can be elucidated with a practical example, considering a system where the proportional gain is something high, and the accumulated error begins to grow or to decrease for long periods of time, this can fatally lead the system in control to have overshoot with high values, and in more severe cases, lead the system to a permanent oscillation. This phenomenon is known by the name of wind-up, and can be minimized using low values ​​for the integral gain, added to techniques of saturation of the integrator (accumulator in the case of integral approximation), but thus, we return to the problem of delay of convergence, since the saturation can be understood as zeroing the integrator (or accumulator).

We then have some drawbacks with this algorithm, so what can be done to minimize the effects of convergence and wind-up? There are several ways to model algorithms of digital compensators from analog circuits, or even from numerical expressions, the algorithm that we will describe here offers a digital PID type compensator with the best approximation.

Digital PID Compensator 2 poles / 2 zeros

Knowing the problems with the first algorithm we can proceed with the modeling of a more precise digital PID controller. For this we will need a mathematical tool well known to those who have studied digital control (or digital signal processing), the Z transform.

This tool allows us to translate equations of difference (in the domain of time), ie those in which two events are separated by an interval whose value is finite and numerically representable, and to obtain an expression that takes a form very similar to equations obtained by the Laplace transform for continuous time systems.

Its definition is exemplified in the equation below:


Equation 1.2 can intimidate at first, but observing with attention we can note that the Z transform by definition does nothing more than take a sequence of pulses whose capture instants are spaced by a time interval, the independent variable n denotes the instant of sampling, so that a discrete time signal can be described as the sequence below:

Thus, once passed to the domain Z each instant of the signal is accompanied by the complex operator (“z”), which denotes the displacement of that signal in time, simplistically the representation of the operator z serves to say if the sample is a value current, a future value (predictors and estimators) or an earlier value, the latter of our interest, let us see:

X (z) z-n: Sample delayed in time;

X (z) z0. ‘. X (z): Current sample;

X (z) zn: Future sample

Although the theory behind the Z transform involves much more concepts, if we look at it in a simplistic way, we can use this simple property (referred to as time shift) to realize a new digital PID controller with better performance than the previous article.

Now that we already know what z operators mean, let’s change a little subject and return to our problem, a way to better approximate the integral term. In addition to the accumulation, there are several numerical methods that allow us to solve integrals with considerable precision and much smaller convergence intervals. For this purpose, let’s select the rule of the trapezoids, with which we can solve an integral according to the following equation:


A much simpler expression to solve, in addition to the rule of trapezoids by approaching the difference between two values ​​of the function f (t) by a trapezoidal aspect, if the sampling rate of the system is well chosen, the convergence for the desired result is much faster and does not suffer from the problem presenting in the first algorithm developed.

We already have a new solution for our integral term, since the derivative does not need modifications, why use the Z-transform, why not go straight to the accounts? With the use of Z transform, we can further reduce the final equation, pre – compute its coefficients, and we can also use its Z – transfer function for analysis in a simulator such as MATLAB.

We know that numerical methods by nature work in a domain of discrete intervals, which is perfect for our application, means that we can take the Z-transform of equation 1.3? Yes we can, but first let’s change the notations to become more familiar:


The above equation is in a much more convenient notation for discrete time system. But now comes the question, how can this well-known rule be used for the purpose of this article? Let us consider the following case, we have the integral of a function, this is the value x [n], adding initial conditions or the integration constant we arrive at the following relation:

Taking the Laplace transform and then the Z transform on both sides of the equation we have (Note that we are computing two derivatives in the domain of continuous time):

Thus we can relate the complex variable s to the discrete time variable z. But before applying this to our PID control, let’s see how to do for the term derivative. Following the line of numerical reasoning to compute a derivative, we have:

As we did for the integral, let’s change the notation for the discrete time domain:

To facilitate computation we will delay both samples in one unit and representing x [n], thus we obtain:

Let us now take the Laplace’s transform then the Z transform in the same way as we did for the integral:

Algebra, algebra, algebra, eis that leads to:


Here we now have an approximation for the integral term, and another for the derivative term. But note that they are in the frequency domain, and our PID is in the time domain, we cover equation 1:

This is not a big problem, first, let’s modify the equation above to the form of a transfer function, ie the quotient of the output by the input of the controller, hence this leads to:


And finally we take the Laplace’s transform, from the above equation:


Our PID has a much friendlier equation but it still finds itself in the continuous time domain, we now need to translate this equation into the discrete time domain, but as was done in 1.5 and 1.6 we now have terms in Z that represent S , so we can take the Z-transform of equation 1.5 substituting the integral and derivative terms:

And it is done, a digital PID compessor, but to the reader I say, do not be scared, although the equation does not seem to make much sense, even more if it is the implementation in a processor, it will begin to make sense as we better order the terms, before anything, we will disappear with the two denominators that does not contain any z, this will help facilitate the accounts. I will add two operators, h1 and h2 where:

h1 = Δt / 2;

h2 = 1 / Δt.

Here the new transfer function becomes:

From this point I will make the necessary mathematical passages until we obtain the final transfer function of our compensator, I ask the reader to follow the passages calmly:

Here we have our transfer function, it is much more friendly, and allows to work on it to form an equation of differences. But before proceeding, let’s make it even more intuitive for the reader, let’s note:

We will replace these coefficients in the transfer function, and we will note that our digital PID is now nothing more than a special case of IIR filter, having two poles and two zeros, from which comes the origin of the algorithm name:


Look at how interesting math is, we start with a differential equation, we put a trapezoidal integral, a numerical derivative, we use two transforms, to find that our best approximated PID is a digital filter of infinite impulsive response. In other words, there are many ways to implement this in a microcontroller, this same equation may already be put into a simulator like MATLAB to evaluate the response of the system to be controlled.

Placing inside a microcontroller

We have the perfectly usable Z-transfer function to simulate its behavior in a MATLAB or any other system simulator, but this function of the form that it is is not very useful, to implement in any processor whatsoever, we must first compute a difference equation from the inverse transform Z, for this we will return to equation 1.7:

We have the input and output of the system, now let’s output according to the input:

It has improved, right? Let’s move a little bit by factoring U (z) and E (z) to “inside” the polynomials we will get:

But: a2 = 0, this simplifies the expression in:

In function of U (z) we obtain:

Interestingly, at this point we can take the inverse transform Z, and surprise the equation of differences becomes this simple expression:

As? Yes my friend, all that hassle of transforming here, transforming there, and using numeric method, will generate this trivial expression, proof that to get things done simple is necessary to think. Equation 1.8 is perfectly implementable, the coefficients are easily calculable, so we can translate this equation as, to compute a new compensator output, we need the previous output sample, and the last three calculated error values.

For the closer reader, this one must have realized that the full term windup problem does not even exist, one less worry, just choose whether to work with fixed or floating point and put it inside your processor.

Let’s test our example, we will ship a small firmware to control the brightness of an RGB LED by closed loop.

Example in test

And finally we come to the most fun session of the article, the practical implementation, we will ship our test firmware in the following development kit:

Figure 1: Led Booster Pack + Piccolo LaunchPad.

Again we will not go into details about the Kit or microcontroller, more information can be found on the Texas website, the link is available at the end of the article.

We will use our digital PID to control a string of LEDs, through the operation of the microcontroller in a DC-DC converter, in fact one of the most interesting parts of this kit in particular. As a simple example, I opted for the use of only the control of the chain of red LEDs, using the control only by the output voltage of the DC-DC converter (yes it is a boost), consulting the datasheet of these leds, arrived at the value for obtaining a current of 25 [mA], by means of experimental adjustment, the following coefficients were reached: Kp = 50, Ki = 15, Kd = 100, the sampling rate was placed at 58,000 samples per second and a carrier frequency of 150 [KHz] allows the PWM module of the microcontroller to operate at 9-bit resolution.

Let’s see the image below, we have the bus voltage perfectly controlled by the microcontroller, let’s see her stable behavior:

Figure 2: Voltage in the LED string bus.

Below we have a photo of the bench, where we have the LEDs being controlled by the microcontroller, one of the things that you write is more interesting is the possibility of the microcontroller itself become a digital control unit, flexible according to the application.

Figure 3: Microcontroller acting through DC-DC.

In spite of the simplicity of the example, the entire project is in a repository in GitHub, to you, reader, I leave the freedom to use in the C2000 itself or carry the PID.c and PID.c files for the microcontroller of your interest, I suggest only the alteration of the types according to the microcontroller used, in case of use of more compact platforms such as AVR, and microcontrollers based on the Cortex-M0 core. And for you most curious reader, why not explore the equation 1.7 and implement in your processor on your own? Writing code in assembly can also be an extremely pleasurable task.


So we come to the end of this small series of articles and hopefully have demystified some concepts on the implementation of digital compensators in microcontrollers of almost any nature. We also hope that the examples provided will be useful to those who wish to venture into the world of digital control. We have also been able to model a simple PID compensator using the Z transform in a simple way without worrying too much about the mathematics involved.

Supplement materials

Example Project:

Microcontrollers C2000 :

Led Booster Pack, Kit used in the example:


CRENSHAW, Jack W. : Math toolkit for real time programming, 2001

MEYRATH, Todd : Multipurpose analog PID controller, 2005

POLEY, Richard : Introduction to digital control using digital signal processors, 2003

STARR, Gregory P. : Introduction to applied digital control , 2006

FelipeDigital PID Controller: One practical modeling for microcontrolers – Part 2

Leave a Reply