-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimplePID.cpp
53 lines (41 loc) · 873 Bytes
/
SimplePID.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
#include "SimplePID.h"
#include <Arduino.h>
namespace SimplePID {
double timeSecs() {
return millis() / 1000.0;
}
void initPID(PID& pid, double p, double i, double d) {
pid.p = p;
pid.i = i;
pid.d = d;
pid.error = 0;
pid.sum = 0;
pid.sum_max = 0;
}
void initPID(PID& pid, double p, double i, double d, double sum_max) {
initPID(pid, p, i, d);
pid.sum_max = sum_max;
}
void resetPID(PID& pid) {
pid.error = 0;
pid.sum = 0;
}
double calcPID(PID& pid, const double error, const double dt) {
pid.sum += error * dt;
double p = pid.p * error;
double i = pid.i * pid.sum;
double d = pid.d * (pid.error - error) / dt;
if (pid.sum_max && pid.i) {
double max = pid.sum_max - p;
if (i > max ) {
pid.sum = max / pid.i;
i = max;
} else if (i < -max) {
pid.sum = -max / pid.i;
i = max;
}
}
pid.error = error;
return p + i - d;
}
}