-
Notifications
You must be signed in to change notification settings - Fork 83
/
PID.cpp
93 lines (79 loc) · 1.96 KB
/
PID.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
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
/*
* File: PID.cpp
* Author: matt
*
* Created on 17 February 2013, 11:19
*/
#include "PID.h"
#include <iostream>
PIDClass::PIDClass() {
dFilK = 0;
}
PIDClass::PIDClass(const PIDClass& orig) {
}
PIDClass::~PIDClass() {
}
void PIDClass::initialise(float KP, float KI, float KD, float ILIM, float LIM, int DFILLEN, double* ALT_DERIV_SOURCE) {
kp = KP;
ki = KI;
kd = KD;
ilim = ILIM;
lim = LIM;
dFilLen = DFILLEN;
altDerivativeSource = ALT_DERIV_SOURCE;
}
void PIDClass::setPID(float KP, float KI, float KD) {
kp = KP;
ki = KI;
kd = KD;
}
void PIDClass::getPID() {
std::cout << kp << ", " << ki << ", " << kd << std::endl;
}
void PIDClass::calculate(double* position, float* setpoint, float* dt) {
prevError = error;
error = *setpoint - *position;
integral += error * *dt;
if(altDerivativeSource == NULL) {
//Derivative low pass filter
//Store current derivative value into history table
dHist[dFilK] = (error - prevError) / *dt;
dFilK++;
if(dFilK == dFilLen) {
dFilK = 0;
}
//Average history table
derivative = 0;
for(int k = 0; k < dFilLen; k++) {
derivative += dHist[k];
}
derivative /= dFilLen;
}
else{
derivative = -*altDerivativeSource;
}
//Anti-windup
constrain_(&integral, ilim);
output = error * kp + integral * ki + derivative*kd;
//Anti-saturation
constrain_(&output, lim);
}
//void PIDClass::calculate(double* position, float* setpoint, float* dt) {
// prevError = error;
// error = *setpoint - *position;
// proportional = error;
// integral += error * *dt;
// derivative = (error - prevError) / *dt;
//
// //Anti-windup
// constrain_(&integral, ilim);
//
// output = proportional * kp + integral * ki + derivative*kd;
//
// //Anti-saturation
// constrain_(&output, lim);
//}
inline void PIDClass::constrain_(float* value, float range) {
if(*value > range) *value = range;
else if(*value < -range) *value = -range;
}