Overview

This code is a working example of a PID (Proportional, Integral, Derivative) control. This type of a control is used when processes change due to inertia. (A car's cruise control is a PID controller.) The PID algorithm is surprisingly simple, and can be implemented in five lines of code. There are three constants that must be determined in order to shape the control's output. The three constants as well as the set point and sampling interval can be changed in real time. The resulting shape of the output will be displayed in a strip chart.

How are PID loops used?

Many real world processes build up over time. When you step on the accelerator, your car moves slowly, then faster, and faster still, until you let off the gas pedal. As you speed up, you press the gas pedal less, then a little less, then even less, until you reach the speed limit. Unlike the digital world where things are either “on” (1) or “off” (0), real processes have varying degrees of “on”. In the driving example, how much the accelerator is turned “on” depends on the car's current inertia and how different the car's speed is from the speed limit. Controlling such a process with inertia can be done with only five lines of code. But, just like learning to drive, it takes practice to know if you are starting too quickly, or if you'll overshoot the speed limit.

Cruise control is one example of a PID control loop. To calculate the output, it needs three factors. The first, (P), is the difference between the current speed and the desired speed. The second, (I), is the sum of the differences over time. And, the third, (D), is the rate of change between sampled differences. Each factor is scaled by a gain constant; they are refered to as Kp, Ki, and Kd. The value of these gain constants determines how responsive the output will be. If the Kp, Ki, and Kd values are too high, the output (car's speed) will far exceed the set point (speed limit). Set too low, the output may never reach the set point (like driving 40mph on the highway).

Code implementation

In the real world, a process updates constantly. In order to simulate this action, a timer is used to run an equation that models the process. From a second timer, the PID control algorithm samples the process value at a rate slower than the process model updates. The “Process Value” or PV timer should run at least twice as faster than the “PID control” timer. In the application, the PV timer runs every 17ms, and the PID timer runs every 100ms.

The PV timer (tmrPV) tick event handler runs the following code:

//This timer updates the process data. it needs to be the fastest// interval in the system.privatevoid tmrPV_Tick(object sender, EventArgs e)
{
/* this is my version of cruise control.
* PV = PV + (output * .2) - (PV*.10);
* The equation contains values for speed, efficiency,
* and wind resistance.
* Here 'PV' is the speed of the car.
* 'output' is the amount of gas supplied to the engine.
* (It is only 20% efficient in this example)
* And it looses energy at 10% of the speed. (The faster the
* car moves the more PV will be reduced.)
* Noise is added randomly if checked, otherwise noise is 0.0
* (Noise doesn't relate to the cruise control, but can be useful
* when modeling other processes.)
*/
PV = PV + (output * 0.20) - (PV * 0.10) + noise;
// change the above equation to fit your application.
}

Take a look at some typical output shapes

In the images below, the green line is the set point, the blue line is the input (or process value), and the red line is the output (or manipulated value).

Correct control signal. All three gain constants are set correctly.

Overshoot. Integral constant too high.

Undershoot. Integral constant too low.

Ringing. Integral and Proportional gain constants too low.

Noise (under control). All three constants are set correctly.

Noise (not controlled). Derivative gain constant too high.

Code modifications you might consider

This example works for modeling any process that has inertia. The process being modeled here is a car's cruise control. In order to adapt the code to model a process other than cruise control, the equation in the PV timer tick event handler should be changed.

I use PID loops for electric furnace control. In furnace control, thermal mass is measured by sampling temperature. Better PID loop tuning results in efficient energy use. The code currently in the PV timer tick event handler is pretty close to a furnace equation. You can modify the equation to fit the system you want to model. As a rule of thumb, use the following equation:

ProcessValue = ProcessValue + (output * efficiency) – loss

In a real cruise control, there are limits on how much the output can change from sample to sample. This example does not include any way to limit the output's magnitude of the change. Such code might look like:

The noise that can be added to the signal is not representative of anything your car might encounter. (It is really just a model of electrical noise.) Noise to a car's cruise control might be something like a hill, or a gust of wind. Both of those examples have a lower frequency than our noise. Since the noise is created in its own timer event handler, you can change the interval of the noise to change its frequency. You could also change the noise equation to model the effects of a hill, or even a chilling arctic blast.

Thanks for the code example, which I found via the wikipedia page for "PID Controller", reference #19 at this time.

I'm using this to control a temperature setpoint for an oven. When the oven is close to the setpoint, the logic works great. However, when I change the setpoint to a different value, the integral variable gets out of hand.

As a result, by the time the oven reaches temperature, had integral started at 0, it would now be a whopping 205. This large number times any reasonable Ki overwhelms all other factors and causes horrible overshoot of the temperature. During the initial stages of this overshoot, error is small and of the other sign, so it begins reducing the integral variable. However, the small error takes far too long to put a dent in the 205.

I've tried to fix this by making note of a stable "margin". When the temp first gets within the margin, I zap the integral value back to 0. This helps, but not perfectly well.

Otherwise, if I start near the setpoint, the code works great. So what am I missing here?

There is something that I don't get - why in method tmrPV_Tick it is Pv that is changed (the speed of the car)? As far I understand, it should not be the speed that has to be changed, but the amount of pressure to the gas pedal, in this case the output variable, that has to be changed and that way indirectly change the Pv (the speed).

In my project I use a physics framework that takes into account lots of variables, but the most important thing is, I use the following snippet of code:

I'm trying to find the formula for PV, in order to simulate a PID regulation on a HVAC system? is anyone have an idea of how I could determine this?

In Fact, I am trying to make a simulation of a HVAC at Heat Mode. The measures of the température is after a fan who's drowing mixed air through a hot-battery. Ideally I need the PV to equal the SP around 1 minute after SP change.

Often is it impossible to obtain a system or a process transfer function (= relation between the Process Value and the SetPoint) analytically due the components parts cant easily be identified etc.
I quess the easiest way to determine the relation between the Process Value and the SetPoint is measure the Output of the Process by a given setpoint( a Stepinput) FRom the response you can determine the time constant and the steady state value. From here you can calculate the transfer function. ( Assuming it is a first-order process)
TF = K/(s+a)
1/a = time constant and K/a = steady state value. Time constant is the time when the amplitude reaches 63% of the steady state value. The value of K can be calculated by substituting the value of a

Question though... can this be implemented without the use of floats do you think? Just fixed point math? If "no", then "no" is good enough... but if "yes", I'd appreciate some tips because I've been struggling with this for days.

www.ControlSoftInc.com has a good PID loop tuning guide that indicates what P, I, and D mean for each PLC manufacturer.

For this algorithm, you have to have 32 bit resolution. Then it's just a matter of multiplying. You can multiply Setpoint, PV, Kp, Ki, and Kd by 1000 in order for the output to keep its resolution. [Another way of looking at this is to say Kp, Ki and Kd need to be entered as values that are 1000x what you really want, then you don't need to multiply the constants by 1000. (Only the SP and PV would need x1000)]

Modify in tmrPID_Ctrl_Tick() in the following way to test the integers:

32 bit INT not a problem here so that seems the way to go. I can use floats too, its just bogging down things. Because of our functional range, a 32 bit in allows for an upscale of approx 65000X if necessary. 16 bit only gives me 128X - probably not enough. Too bad, I'd like to save the space.

Time is independent, and not scaled. If your smallest unit is seconds it's seconds everywhere. In the case of Dt, the timer's resolution is ms, so Dt is in ms.

Something else to think about...
... Some processes take seconds, to minutes before the PV changes. For example, if you are melting 18 lbs of metal (like lead) in a 500W(VA) 120VAC pot it will take 20 minutes to go from 75F to 675F. In this case 10 second is a good resolution. Why? There are 1200 seconds in 20 minutes, or 120 "10 second samples" from 75F to 675F (change of 600F). On average that's 5F per 10 seconds (600F / 120samples = 5F/sample). You should be able to control the temperature to +-5F of the setpoint. IF you need to keep the temperature to +-0.5F the sample time would need to be 1s. An AC solid state relay, or SCR, is used to convert the output into power for the melting pot. [Electrically the output would be scaled to a 0 - 10V signal that is sent to the SCR.]

Time is relative. I mean that in terms of my code has no idea if its running once a second or a thousand times a second or 40 million times a second. Externally, I (the human) know that it is running, in fact, 20 times per second in this case.

Let's give this some context. I came to this article, entitled "PID process control, a "Cruise Control" example" and in my case I am in fact coding a cruise control for an automotive application. Unfortunately, despite that being the title a lot of this article is more generic or even specific to temperature control (see comments in code surrounding, "Most PLC's have relatively slow data buses, and would sample temperatures on the order of 100's of milliseconds.") and the example application really has nothing to do specifically with automotive cruise control. But I am attempting to code for a cruise control.

The processor has the capability to sample the speed at 40Mhz but the car is producing a speed signal at only approximately 50hz. I can set my code arbitrarily to perform reliably from 20hz to about 1Mhz.

Just a note: the speed data is coming into the CPU already upscaled by 32X.

I *can* use floats, but I'm very much trying to use only integers. The processor can have variables declared at 8 bit, 16 bit or 32 bit.

There are two problems however. It ignores deceleration since output can't be negative, and Dt needs to be large enough that the change in PV is not truncated. So Dt needs to be at least 100ms, which will cause the gains to be re-tuned.

Let me get back to you with a solution.
Can you tell me the acceleration if output is equal to 52, 104, 156, and 208?

I'd say that "output" is the degree to which the pedal is being pushed because that is something you can control directly, not acceleration which you can only control indirectly (via output). There are problems with answering your question, "what is the acceleration if output = X?". It depends greatly on external factors, such as as terrain (how steep is the grade we're on) but it also depends on the PV and even that relationship isn't linear or even a curve because it also depends on what gear the car is in.

I'd say there is no possible way to predict an acceleration given a specific output. Think of a car that's already at its maximum PV for example. Or one going up a steep hill where it needs the full output puower to just maintain speed - or possibly not even be able to maintain speed. A car in 4th gear going 30 is going to accelerate a whole lot differently than one in 2nd gear at the same speed.

At low speeds all of your samples will accelerate violently. But at higher speeds, the first couple may be required just to maintain speed and as you approach the car's speed limits none of them will really do much of anything.

I think a lot of the factors that effect the PV can't be accounted for in an alogorithm but with program logic. For the most part, we can say that the higher the output that PV will attempt to grow (how responsive is difficult to predict) and for cases where it can't we'll handle with logic.

So I don't mind your original algorithm... I'm still confused on the concept of "time". The vehicle reports its speed in kph does that mean my unit of time measurements need to be in hours? Or because it is natively upscaled by 32X is my time in 1/32nd of an hour? And then why if I'm upscaling it to 4096X is my time not in 1/4096 of an hour? You said before not to scale the time but if you look at your equation, the factor of scaling is going to make Dt more or less significant which suggests an arbitrary effect and then why have time at all?