forked from matthew-t-watson/Picopter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPID.cpp
More file actions
73 lines (57 loc) · 1.38 KB
/
PID.cpp
File metadata and controls
73 lines (57 loc) · 1.38 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
66
67
68
69
70
71
72
73
/*
* File: PID.cpp
* Author: matt
*
* Created on 17 February 2013, 11:19
*/
#include "PID.h"
#include <iostream>
PIDClass::PIDClass() {
}
PIDClass::PIDClass(const PIDClass& orig) {
}
PIDClass::~PIDClass() {
}
void PIDClass::initialise(float KP, float KI, float KD, float ILIM, float LIM){
kp = KP;
ki = KI;
kd = KD;
ilim = ILIM;
lim = LIM;
}
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, double* setpoint, float* dt){
prevError = error;
error = setpoint - position;
p = error;
i += error * *dt;
d = (error - prevError) / *dt;
//Anti-windup
constrain_(&i, ilim);
output = p*kp + i*ki + d*kd;
//Anti-saturation
constrain_(&output, lim);
}
void PIDClass::calculate(double* position, float* setpoint, float* dt){
prevError = error;
error = *setpoint - *position;
p = error;
i += error * *dt;
d = (error - prevError) / *dt;
//Anti-windup
constrain_(&i, ilim);
output = p*kp + i*ki + d*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;
}