-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib_pid.ks
More file actions
65 lines (51 loc) · 1.4 KB
/
lib_pid.ks
File metadata and controls
65 lines (51 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
@LAZYGLOBAL OFF.
FUNCTION PID_Init { PARAMETER Kp, Ki, Kd, controlMin, controlMax.
LOCAL P IS 0.
LOCAL I IS 0.
LOCAL D IS 0.
LOCAL previousError IS 0.
LOCAL previousOutput IS 0.
LOCAL PID_Array IS LIST(Kp, Ki, Kd, controlMin, controlMax, P, I, D, previousError, previousOutput).
RETURN PID_Array.
}
FUNCTION PID_Seek { PARAMETER PID_Array, targetValue, currentValue.
// Fill LOCAL variables from input array.
LOCAL Kp IS PID_Array[0].
LOCAL Ki IS PID_Array[1].
LOCAL Kd IS PID_Array[2].
LOCAL controlMin IS PID_Array[3].
LOCAL controlMax IS PID_Array[4].
LOCAL P IS PID_Array[5].
LOCAL I IS PID_Array[6].
LOCAL D IS PID_Array[7].
LOCAL previousError IS PID_Array[8].
LOCAL previousOutput IS PID_Array[9].
LOCAL dT IS 0.1.
// Find new error.
LOCAL error IS targetValue - currentValue.
// Calculate integral.
SET I TO I + (error * dT).
IF I * Ki > controlMax {
SET I TO controlMax / Ki.
}
IF I * Ki < controlMin {
SET I TO controlMin / Ki.
}
// Calculate derivative.
SET D TO (error - previousError) / dT.
// Calculate new output.
LOCAL output IS (Kp * error) + (Ki * I) + (Kd * D).
IF output > controlMax {
SET output TO controlMax.
}
IF output < controlMin {
SET output TO controlMin.
}
// Update array with new values.
SET PID_Array[5] TO P.
SET PID_Array[6] TO I.
SET PID_Array[7] TO D.
SET PID_Array[8] TO error.
SET PID_Array[9] TO output.
RETURN output.
}