Code associated with "How to Write a PID Algorithm" by Garth Gaddy, p. 62, May 1997
listing 1
Screw servo motion program.
01 While (True)
02 If (Auto_Mode = 1 )
03 If (First_PID_Execution = 0 OR First_PID_Execution = 1)
04 Error = (SP - PV) * (CV_Span / PV_Span)
05 Sum_Error = Sum_Error + Error
06 If (First_PID_Execution = 0)
07 Sum_Error = Manual_Command / KI
08 First_PID_Execution = 1
09 Initial_Error = Error
10 Endif
11 Pterm = 0
12 Iterm = KI * Sum_Error
13 Dterm = 0
14 If (Initial_Error > 0 and Error < 0)
15 First_PID_Execution = 2
16 Last_PV = PV
17 Endif
18 If (Initial_Error < 0 and Error > 0)
19 First_PID_Execution = 2
20 Last_PV = PV
21 Endif
22 Last_SP = SP
23 Else
24 If (SP = Last_SP)
25 Error = (SP - PV) * (CV_Span / PV_Span)
26 Pterm = KP * Error
27 Sum_Error = Sum_Error + Error
28 Iterm = KI * Sum_Error
29 d_PV = (Last_PV - PV) * (CV_Span / PV_Span)
30 Last_PV = PV
31 Dterm = KD * d_PV
32 Else
33 Error = (SP - PV) * (CV_Span / PV_Span)
34 Sum_Error = Sum_Error + Error
35 Pterm = 0
36 Iterm = KI * Sum_Error
37 Dterm = 0
38 If (SP > Last_SP and PV > SP)
39 Last_SP = SP
40 Last_PV = PV
41 Endif
42 If (SP < Last_SP and PV < SP)
43 Last_SP = SP
44 Last_PV = PV
45 Endif
46 Endif
47 Endif
48 CV = Pterm + Iterm + Dterm
49 Else
50 CV = Manual_Command
51 First_PID_Execution = 0
52 Endif
53 EndWhile