-
Notifications
You must be signed in to change notification settings - Fork 0
/
PIDController.cpp
64 lines (52 loc) · 1.26 KB
/
PIDController.cpp
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
//
//
//
#include "PIDController.h"
/**
* Constructor for PID
* @param debug enable or disable serial logging
*/
PID::PID(bool debug)
{
bDebug = debug;
// defaults
currentError = 0.0;
prevError = 0.0;
kpRes = 0.0;
kiRes = 0.0;
kdRes = 0.0;
}
/**
* call all methods to output a pid Error correction
* @param currentState the current smoothed input used to calculate error
* @param targetState the target used to calculate error
* @returns PID output
*/
double PID::calculatePID(double errIn)
{
currentError = errIn;
kpRes = KP * currentError;
// update total error
kiTotal += currentError;
// prevent windup
if (kiTotal > KI_LIMIT)
kiRes = KI * KI_LIMIT;
else
kiRes = KI * kiTotal;
kdRes = KD * (currentError - prevError);
// store error
prevError = currentError;
return (kpRes + kiRes + kdRes);
}
// output state to serial monitor
void PID::debug(char label[])
{
Serial.print(label);
Serial.print(" | curr error: "); Serial.print(currentError);
Serial.print(" | prev error: "); Serial.print(prevError);
Serial.print(" | P: "); Serial.print(kpRes);
Serial.print(" | I: "); Serial.print(kiRes);
Serial.print(" | D: "); Serial.print(kdRes);
Serial.print(" | gain : "); Serial.print(gain);
Serial.print("\n");
}