-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPID.cpp
More file actions
35 lines (29 loc) · 873 Bytes
/
PID.cpp
File metadata and controls
35 lines (29 loc) · 873 Bytes
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
#include "PID.h"
PID::PID(float Kp, float Ki, float Kd) {
positiveLast = true;
errorLast = 0;
integralError = 0;
this->Kp = Kp;
this->Ki = Ki;
this->Kd = Kd;
}
float PID::compute(float currAngle, float targetAngle, float dt) {
float error = targetAngle - currAngle;
integralError += error*dt; // todo: solve integral windup later
// Reset integralError if the error switches sign
if ((positiveLast && error < 0) || (!positiveLast && error > 0)) {
integralError = 0;
positiveLast = !positiveLast;
}
float P = -Kp * error; //Simply proportional to error
float I = -Ki * integralError;
float D = -Kd * (error - errorLast) / dt;
errorLast = error;
int output = P + I + D;
if (output > 1) {
return 1;
} else if (output < -1) {
return -1;
}
return output;
}