Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

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. private void tmrPV_Tick(object sender, EventArgs e) { * 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:

Collapse | Copy Code /* 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; }

You might also like