-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPID_lib.cpp
More file actions
80 lines (64 loc) · 1.76 KB
/
Copy pathPID_lib.cpp
File metadata and controls
80 lines (64 loc) · 1.76 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
74
75
76
77
78
79
80
#include "Arduino.h"
#include "PID_lib.h"
PID::PID(int16_t kp, int16_t ki, int16_t kd,
int16_t outMin, int16_t outMax,
unsigned long period)
{
this->pidOutput = 0;
this->pidSetpoint = 0;
this->outMin = outMin;
this->outMax = outMax;
this->period = period;
this->k1 = kp + ki + kd;
this->k2 = -kp - 2 * kd;
this->k3 = kd;
this->e1 = 0;
this->e2 = 0;
this->e3 = 0;
this->prevTime = millis() - period;
this->enabled = false;
}
int16_t PID::compute(double input)
{
unsigned long currTime = millis();
unsigned long timeChange = currTime - prevTime;
if(timeChange >= this->period && this->enabled)
{
int16_t deltaOutput = 0;
e3 = e2;
e2 = e1;
e1 = this->pidSetpoint - (int16_t)(input * INT_RESOLUTION);
deltaOutput = (this->k1 * e1) + (this->k2 * e2) + (this->k3 * e3);
this->pidOutput += deltaOutput;
if (this->pidOutput > INT_RESOLUTION * this->outMax)
{
this->pidOutput = INT_RESOLUTION * this->outMax;
}
else if (this->pidOutput < INT_RESOLUTION * this->outMin)
{
this->pidOutput = INT_RESOLUTION * this->outMin;
}
}
return this->pidOutput / INT_RESOLUTION;
}
void PID::set(double target)
{
this->pidSetpoint = (int16_t)(target * INT_RESOLUTION);
}
void PID::start()
{
this->e1 = 0; // reset e terms
this->e2 = 0;
this->e3 = 0;
this->pidOutput = this->outMin;
this->enabled = true;
}
void PID::stop()
{
this->pidOutput = this->outMin; // disable the output
this->enabled = false;
}
bool PID::isEnabled()
{
return this->enabled;
}