I have to use the PID algorithm that I describe below, obtained from a PLC in the company where I work, so I want to understand it. This is used for control a valve that opens to let gas pass and reach a certain pressure (SetPoint).
There is a Timer with a preset value of "Tsample", with an output "Tsample.Q" in low level, and it become high for an scan cycle each a time "Tsample".
I have a variable that store current error value ($e_n$), other for the error a time Tsample before ($e_{n-1}$) and other to store the error 2*Tsample before ($e_{n-2}$). This and the next parts of algorithm are executed once every time equal to Tsample: $$e_{n-2}=e_{n-1}$$ $$e_{n-1}=e_n$$ $$e_n=SetPoint-ProcessValue$$
Aditionally, I have a variable that store the current change in the error respect the last , and the same Tsample before.
$$P_n=e_n-e_{n-1}$$ $$P_{n-1}=e_{n-1}-e_{n-2}$$
Finally a variable that store the variation of the change of the error:
$$Q_{n}=P_n-P_{n-1}=(e_n-e_{n-1})-(e_{n-1}-e_{n-2})$$
And the calculation of control signal, where $dP_n$ is the proportional part, $dI_n$ is the integral part, $dD_n$ is derivative part, $K_p$ is global gain, $R_p$ is proportional gain, $T_i$ integral time, $T_d$ derivative time, and $dU_n$ is the PID output:
$$dP_n=R_p*P_n$$ $$dI_n=T_i*e_n$$ $$dD_{n-1}=dD_{n}$$ $$dD_n=(Q_{n}*T_d+dD_{n-1})/2$$ $$dU_n=K_p*(dP_n+dI_n+dD_n)$$
After that, it calculate the direction of the correction, where PC (positive correction) is a variable with TRUE value if $dU_n>0$ and FALSE value if $dU_n<0$ and NC (negative correction) is TRUE if $dU_n<0$ and FALSE if $dU_n>0$.
After this PID algorithm is executed, the correction is made. If $U_n$ is current valve opening percentage and the PID output $dU_n$ is the change of the valve opening percentage; once every time equal to Tsample, the actual value of valve aperture is incremented or decremented:
If PC=TRUE then $U_n$=$U_{n-1}$+$dU_n$
If NC=TRUE then $U_n$=$U_{n-1}$-$dU_n$
I don't understand the reason to work with actuar error on integral control, change in the error ($P_n$) in proportional control, and change of the change of the error ($Q_n$) in the derivative control.
It is suposse that I shoud to take the integral of error to integral contror, for example, adding to the accumulated action the area of a rectangle with Tsampler width and average height of the previous and current error: $$I_n=I_{n-1}+ Ki * [ Tsampler*(e_{n-1}+e_{n})/2 ] $$ Current error $e_n$ to proportional, and finally an aproximation of derivate of error to derivative part, for example: $$D_n=K_d * (e_{n}-e_{n-1})/Tsampler$$ where Ki and Kd are representative.