-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFTC_PID.c
143 lines (118 loc) · 2.5 KB
/
FTC_PID.c
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#ifndef FTC_PID_h
#define FTC_PID_h
typedef struct
{
int target;
int current;
float Kp;
float Ki;
float Kd;
int previousError;
float errorSum;
int maxIncrement;
float d;
bool enabled;
int acceptedRange;
int maxOutput;
int output;
int error;
int lastDUpdate;
bool isFirstCycle;
bool rawI;
bool continous;
int maxInput;
} PID;
void initPID(PID &pid, float Kp = 0, float Ki = 0, float Kd = 0)
{
pid.target = 0;
pid.current = 0;
pid.Kp = Kp;
pid.Ki = Ki;
pid.Kd = Kd;
pid.previousError = 0;
//pid.errorSum = 0;
pid.maxIncrement = 1;
pid.d = 0;
pid.enabled = true;
pid.error = 0;
pid.acceptedRange = 5;
pid.maxOutput = 100;
pid.output = 0;
pid.lastDUpdate = time1[T1];
pid.isFirstCycle = true;
pid.rawI = false;
pid.continous = false;
}
int calcPID(PID &pid, int input)
{
pid.current = input;
// P
float error = (float)pid.target - (float)pid.current;
if ( pid.continous )
{
if ( abs(error) > (pid.maxInput/2) )
{
if ( error > 0 )
error = error - pid.maxInput;
else
error = error + pid.maxInput;
}
}
// I
if ( pid.rawI )
pid.errorSum += error;
else
{
if ( error >= pid.acceptedRange )
{
if ( pid.errorSum < 0 )
pid.errorSum = 0;
if ( error < pid.maxIncrement )
pid.errorSum += error;
else
pid.errorSum += pid.maxIncrement;
}
else if ( error <= pid.acceptedRange )
{
if ( pid.errorSum > 0 )
pid.errorSum = 0;
if ( error > -pid.maxIncrement )
pid.errorSum += error;
else
pid.errorSum -= pid.maxIncrement;
}
else
pid.errorSum = 0;
}
// D - update every 20ms
if ( (pid.lastDUpdate+20) < time1[T1] && !pid.isFirstCycle )
{
pid.d = error-pid.previousError;
pid.previousError = error;
pid.lastDUpdate = time1[T1];
}
pid.output = (int)((pid.Kp*error) + (int)(pid.Ki*pid.errorSum) + (int)(pid.Kd*pid.d));
pid.isFirstCycle = false;
pid.error = error;
// pid.output = ( abs(pid.output) > pid.maxOutput ? 0 : pid.output );
return (pid.enabled ? pid.output : 0);
}
void setPIDConstants(float Kp, float Ki, float Kd, PID &pid)
{
pid.Kp = Kp;
pid.Ki = Ki;
pid.Kd = Kd;
}
bool atPIDTarget(PID &pid)
{
return (abs(pid.error) <= pid.acceptedRange);
}
void debugPID(PID &pid)
{
nxtDisplayString(0, "Cur: %i", pid.current);
nxtDisplayString(1, "Tar: %i", pid.target);
nxtDisplayString(2, "Err: %i", pid.error);
nxtDisplayString(3, "Out: %i", pid.output);
nxtDisplayString(4, "Pres: %2.4f", (float)pid.error*pid.Kp);
}
#endif