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: https://github.com/uLipe/PID_Embarcados_C2000

Microcontrollers C2000 : http://www.ti.com/product/tms320f28027

Led Booster Pack, Kit used in the example: http://www.ti.com/tool/boostxl-c2kled


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

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

No comments

On this series we’ll show, in a practical and intuitive way, how to model one PID ( Proportional – Integral – Derivative) controller in a way that your final equation can be easy implemented in a general purpose microcontroller (general purpose here, meaning a processor with at least hardware multiplication instructions).


When we speak about system control, is hard when a PID compensator type is not mentioned. This kind of controller is largely implemented to control the output of different systems. Utilized in closed loop systems, one controller of this type can be set to offer the desired response and maintain the system’s output with a minimum amount of error only using three setup parameters.

Figure 1: Example of a closed loop system.

The Desired State signal is the desired value for which the system output should remain until it is changed again. At the system output (Actual Robot State sample signal) we have the signal of the current state of the system which may or may not be the same as desired. To do this, its current value is sent to the input and the difference between the desired state and the current state is computed, forming a third commonly called error variable, ie the difference between the desired state and the current state. The Robot Kinematics block represents the characteristic of the simulated system, usually described by differential equations, that is, the system to be controlled (an electric motor having its speed controlled, for example). Finally, we have the Controller block, which as its name suggests is a block to compensate for the (often undesirable) characteristics of the system response to be controlled. This is where the PID controller is “docked”. Now that we remember (or know) the aspect of a closed loop system, let us better understand what this PID compensator is.

The compensator PID

Knowing that a closed loop system is usually added by a compensator block to get the response and control over a variable, the reader should ask what these compensators are. In fact, there are several implementations of compensators ranging from a simple first order filter to complex arrangements with equations greater than or equal to 3. Among them we highlight the PID controller, which has up to three forms of actuation (up to three, since the others actions can be deactivated just by zeroing one of the coefficients) each with a different effect to the system, we can generalize these effects as follows:

  • The proportional action (P) will provide a faster response of the system under a variation in the input signal (desired state);
  • The integral action (I) aims to cancel a phenomenon known as steady state error, so that when reaching a steady state this value is what is desired in the input signal;
  • The derivative action (D) has an effect of anticipating the correction of the output value of the system so that it also improves the speed of response of the system and reduces the value of the envelope (value that refers to the quantity in which the signal output is higher than desired).

The combination of the quantity of each of these three actions will cause the controller together with the plant (a common way of referring to the system in control) to provide a suitable response to a given input variation. In this way we can write the output state of the PID controller as a function of its input by the equation:



  • Kp: Coefficient of proportional action;
  • Ki: Coefficient of the integral action;
  • Kd: Derivative action ratio;
  • t: Instant of the state to be processed;
  • u (t): System output signal at time t;
  • e (t): Error signal at controller input at time t.

The major problem for implementing such a compensator lies in the fact that it consists of an equation involving an integral and a differentiation of an unknown function, and it is difficult to estimate its behavior, much less the best values for the coefficients that provide an adequate response for this. So maybe it’s best to analyze your behavior in another right domain? Why not the frequency domain? Let’s resort to a mathematical resource well known to control engineers, the Laplace transform. With it we can modify this equation to a simpler form and solve using algebra instead of calculation. Due to the practical objective of this article we will not go into details of the mathematics involved for this resource, so we will look for the respective transformations of this equation using the basic table of transformations, which can be found in references such as OGATA (2010) and NISE (2010).

Let us return to equation 1:

“L” by transforming the equation above gives:


is a complex variable.

In the frequency domain (called for this case of Laplace domain) it is interesting to analyze the transfer function, ie the quotient between the output signal by the input signal, then we have:


It is done, with equation 1.1 we have what is necessary to integrate with the equations of the system to be controlled (previously also “L” – transformed) just to evaluate the characteristics of the plant and to determine Kp, Ki and Kd. After this process a circuit developed from operational amplifiers may provide a simple but efficient analogue PID controller as shown in figure 2:

Figure 2: Analogue PID (adapted from MEYRATH, 2005)

If we take the inverse path and obtain the transfer function of the circuit of figure 2, we arrive at an expression if not equal, very similar and of the same order as the equation obtained in 1.1. Thus, we have the analogue system ready to solve the problem (or complete) of the control system.

Okay, but how do you implement this in a microcontroller? Incidentally, in a general purpose microcontroller is it possible to implement? The answer is partly yes. Partially because a PID algorithm to have an acceptable performance the processor needs at least the hardware multiplication instruction in the next, we will derive from equation 1.1 an optimal quality approximation of a PID controller.

Implementing a numeric PID

We now know what a closed loop system is and how to perform a PID controller in the form of an electronic circuit based on operational amplifiers. Now we will understand how to turn all this theory into numbers so that our processor can execute a sequence of commands compatible with the same operation of the electronic circuit shown in figure 2.

We will observe Figure 3, which illustrates a control system where a processor (or microcontroller) takes the form of the control block responsible for performing the compensation and acting on the plant to be controlled:

Figure 3: Digital Control System (STARR, 2006)

Disregarding the other signals that appeared in comparison with figure 1, and looking at the controller, we saw that it takes the form of a general purpose processor, where the error signal arrives at it through an A / D conversion. The numerical value is then processed by generating another that is passed to a D / A (it can be a modulation method like PWM) where it returns to its analog form and controls the plant. Thus we know that to model a digital PID we will need to work with numerical processing.

Let’s start this session by deriving a very popular PID algorithm and using even 8-bit microcontrollers as demonstrated in ATMEL (2006). The basic idea as absurd as it may seem is to take the inverse Laplace transform and return to equation 1:

Yes, for this first demonstration to work in the time domain and with differential equations will facilitate the accounts well, observing the equation we have an integral and a derivative operation, remembering (or presenting) some classes of numerical calculation it is known that it is possible to approach both one operation over another using algebraic operations that behave similarly.

ATTENTION! From this session we will use a little more mathematics and will remember some concepts of differential and integral calculus. So we ask for a little patience from the reader (especially from the beginner) until we get to the first algorithm. It is worth the effort as a gift will come a great understanding of what are derived and integral in practice.

Starting with the proportional term, this is undoubtedly the most intuitive. Note that this can be computed only by taking the multiplication of the proportional constant by the error variable that arrives at an instant t:


Where n denotes the instant of sampling of the error variable received by the A / D converter. Note that we are still in the time domain, but now we are in a discrete domain where incoming samples are equally spaced by a difference of 1 new value. That is, we already have the hint from where to go to find the other terms of the equation. We now turn to the term derivative.

In order to approximate a derivative to a digital computer, we need to recall the concept of differentiation learned in the first calculation cells, so the derivative of a function with respect to t is defined as:


Forgetting the calculus classes now, let’s take a closer look at what this expression says, that is, a derivative is nothing more than the subtraction of a value from a function for a given value, and a previous value of this same t, where the difference between them is very close to zero or even zero. Mathematically this is not possible, but if we make this t small enough, we can get a very similar approximation to that derived by the definition, so if we want a small spacing, why not choose the sampling rate value of the A / D converter? So:

Thus, we now have an acceptable numerical value which allows us to develop the limit presented in 1.3:

We can now move to the discrete-time domain because we know that each A / D conversion result will already be spaced from one sample to another. Thus we have:


Adding the Kd gain to the equation, we finally arrive at:


And so we have just unraveled the great meaning of a derivative, in the domain of continuous or discrete time, this operation is reduced to a subtraction of the current value of the function by the previous one. What differentiates it from one to the other is that this subtraction is done when the spacing between instants is symbolically zero, and in the case of the discrete time is a value close to zero but known in time, the term t contained in the denominator has been suppressed, because in addition to the samples already being properly spaced with this time base, this value is computed at the moment we adjust the parameter Kd of our controller.

Equation 1.5 is easily implemented in any microcontroller, and actually calculates the term derivative or any other derivative. Now we have the integral term, that follows the same numerical principle, but inversely, if before we had a subtraction, in the case of the integrator we will have a summation. Let us now go to the definition of an integral, as done for the derivative, let us begin with the domain of continuous time, it is worth remembering that for this demonstration, the integral of interest only if it is defined, ie there are intervals whose values ​​are finite:


Although it seems more frightening at first glance, we can disaggregate the sum for only two samples, since for a control system the present and previous states of an interest concern, this leads to:

In the same way as we did for the derivative term, let us use the sampling time of the A / D converter as a sufficiently small value for t, this now transforms the integral into a fully calculable summation, which takes us straight to the discrete time domain:

Again with the term being suppressed because it is contained in Ki, so we have the integral term of the equation as:


Thus we have the integral term of the PID equation, and we simply add equations 1.2, 1.5 and 1.7 to obtain the state value that will be sent to the D / A converter as a function of the input e (t):


Comparing this equation obtained with equation 1, we now conclude that it is possible to compute a PID compensator digitally, right? A simple C program or even assembly if you want better performance could be easily implemented in a microcontroller.

Remembering that:

and that: ti = integration time, td = Time of differentiation.

We could already implement this code in C which is used even in some PID libraries used in Arduino, and thus we have a simple and efficient implementation of a digital PID capable of attending to the control of simple systems. We can call this digital PID approximation as a rectangular approximation given the approximation method used to calculate the integral term.

In this first part, we will stop here. In Github we have put a simple example of PID using the rectangular approximation, but in the next part we will discuss more about the limitations of this technique, as well as we will approach the design of a new digital PID using the dreaded (so far!) Transformed Z, as well as tips how to approach other analogue compensators for computational implementation.

Stay tuned for the second part of this article.


ATMEL – AVR221: Discrete PID Controller-2006, avaiable in: <http://www.atmel.com/images/doc2558.pdf>.

CRENSHAW, Jack W. – Math Toolkit for Real – Time Programming – 2000.

MEYRATH, Todd – Multipurpose Analog PID Controller – 2005.

NATIONAL INSTRUMENTS – Controls Law, (link deprecated by NI):

STARR, Gregory P. – Introduction to Applied Digital Control – 2006.

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

We are EtherCAT members!

No comments

I’m proud to announce that Overlay is an official member of EtherCAT Technology Group.

This is an important step, not just to enable Overlay to develop and sell EtherCAT based devices, but to allow Overlay to contribute with innovation on this open protocol standard.

I’m very excited from the outcomes that this alliance will bring to the industry. We have amazing projects coming in the near future, we can’t wait to make it public!

ViniciusWe are EtherCAT members!

Hello World from Overlay

No comments

Hey people!

This is our first post in our brand new blog, the days are busy, we are working hard to bring our first product line to sales very soon! 

This blog was created with the purpose to bring to our customers and followers high-quality technical content related to product development, robotics, software and hardware engineering.



ViniciusHello World from Overlay