15,798,592 members
Articles / Programming Languages / C#

PID process control, a “Cruise Control” example

Rate me:
14 May 2009CPOL4 min read 342.4K   23.8K   97   31
Example of a PID (Proportional, Integral, Derivative) control, used when processes change due to inertia.

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:

C#
```//This timer updates the process data. it needs to be the fastest
// interval in the system.
private void 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.
}```

The PID control timer (`tmrPID_Ctrl`) tick event handler runs:

C#
```/* This represents the speed at which electronics could actually
* sample the process values.. and do any work on them.
* [most industrial batching processes are SLOW, on the order of minutes.
* but were going to deal in times 10ms to 1 second.
* Most PLC's have relatively slow data buses, and would sample
* temperatures on the order of 100's of milliseconds. So our
* starting time interval is 100ms]
*/
private void tmrPID_Ctrl_Tick(object sender, EventArgs e)
{ /*
* Pseudo code (source Wikipedia)
*
previous_error = 0
integral = 0
start:
error = setpoint – PV [actual_position]
integral = integral + error*dt
derivative = (error - previous_error)/dt
output = Kp*error + Ki*integral + Kd*derivative
previous_error = error
wait(dt)
goto start
*/
// calculate the difference between
// the desired value and the actual value
error = setpoint - PV;
// track error over time, scaled to the timer interval
integral = integral + (error * Dt);
// determine the amount of change from the last time checked
derivative = (error - preError) / Dt;
// calculate how much to drive the output in order to get to the
// desired setpoint.
output = (Kp * error) + (Ki * integral) + (Kd * derivative);
// remember the error for the next time around.
preError = error;
}```

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:

C#
```if ( (output – outputLast) > maxChange)
output = outputLast + maxChange;
else if ( (outputLast – output) > maxChange)
output = outputLast – maxChange;
outputLast = output;```

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.

History

• 2009 - 05 - 14 - Article submitted.

Written By
United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

 First PrevNext
 Project has an issue with signing. Gives error "An error occurred while signing: Failed to sign..." Fishjd12-Nov-20 6:16 Fishjd 12-Nov-20 6:16
 Solution file Member 145026713-Feb-20 0:43 Member 14502671 3-Feb-20 0:43
 integral variable gets out of hand Member 872248315-Aug-13 4:09 Member 8722483 15-Aug-13 4:09
 integral variable gets out of hand Member 872248315-Aug-13 3:23 Member 8722483 15-Aug-13 3:23
 PID control for heater vebi100031-Jul-13 5:05 vebi1000 31-Jul-13 5:05
 Very neat application Sergey Chepurin25-Jun-13 23:13 Sergey Chepurin 25-Jun-13 23:13
 Just something that I don't understand Martin Asenov18-Mar-13 6:36 Martin Asenov 18-Mar-13 6:36
 My vote of 5 LeoBro24-Dec-12 4:01 LeoBro 24-Dec-12 4:01
 Using a negative SetPoint jnilson_9910-Oct-12 12:41 jnilson_99 10-Oct-12 12:41
 Re: Using a negative SetPoint jnilson_9910-Oct-12 13:00 jnilson_99 10-Oct-12 13:00
 My vote of 5 Member 944192519-Sep-12 8:22 Member 9441925 19-Sep-12 8:22
 PV Equation CRMATTHIEU18-Jan-12 7:01 CRMATTHIEU 18-Jan-12 7:01
 Re: PV Equation oswaldfig7-Feb-12 9:46 oswaldfig 7-Feb-12 9:46
 transfer function of the process ? oswaldfig29-Nov-11 12:49 oswaldfig 29-Nov-11 12:49
 My vote of 5 smurariu8-Feb-11 0:53 smurariu 8-Feb-11 0:53
 very good article mnch7817-Oct-09 8:40 mnch78 17-Oct-09 8:40
 Can this be done with fixed point math? s_mack8-Sep-09 15:53 s_mack 8-Sep-09 15:53
 Re: Can this be done with fixed point math? lcady8-Sep-09 19:29 lcady 8-Sep-09 19:29
 Re: Can this be done with fixed point math? [modified] s_mack8-Sep-09 20:07 s_mack 8-Sep-09 20:07
 Re: Can this be done with fixed point math? s_mack8-Sep-09 21:37 s_mack 8-Sep-09 21:37
 Re: Can this be done with fixed point math? lcady9-Sep-09 8:27 lcady 9-Sep-09 8:27
 Re: Can this be done with fixed point math? s_mack9-Sep-09 9:08 s_mack 9-Sep-09 9:08
 Re: Can this be done with fixed point math? lcady10-Sep-09 4:37 lcady 10-Sep-09 4:37
 Re: Can this be done with fixed point math? s_mack10-Sep-09 5:03 s_mack 10-Sep-09 5:03
 pid controller johngholton18-Aug-09 5:23 johngholton 18-Aug-09 5:23
 Last Visit: 31-Dec-99 19:00     Last Update: 10-Dec-23 11:15 Refresh 12 Next ᐅ