-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPID.cpp
More file actions
44 lines (35 loc) · 739 Bytes
/
PID.cpp
File metadata and controls
44 lines (35 loc) · 739 Bytes
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
#include "PID.h"
PID::PID()
{
pTerm = iTerm = dTerm = 0;
error = 0;
}
void PID::setPID(float p, float i, float d)
{
Kp = p;
Ki = i;
Kd = d;
}
float PID::Calculate(float Input, float Ref)
{
//计算采样时间,并把ms转换为s
long dt = millis() - prevTime;
float dt_float = dt*0.001;
float error = Input-Ref;
pTerm = Kp*error;
dTerm = - Kd*(Ref - prevRef)/dt_float;
iTerm += Ki*error*dt_float;
if(iTerm>30)
iTerm = 0;
if(abs(error)<10)
iTerm = 0;
output = pTerm + iTerm + dTerm;
//更新状态
prevTime = millis();
prevRef = Ref;
return output;
}
void PID::resetITerm()
{
iTerm = 0;
}