-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpidthread.cpp
62 lines (55 loc) · 1.24 KB
/
pidthread.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
#include "pidthread.h"
PIDThread::PIDThread() :
QThread()
{
// init errors
error_this_time = 0;
error_last_time = 0;
error_integral = 0;
finalStateCount = 0;
}
void PIDThread::run()
{
while(1)
{
usleep(10000); // 10 ms
error_last_time = error_this_time;
error_this_time = targetPosition - currentPosition;
error_integral += error_this_time;
double speed = calculateSpeed();
if (checkEnd(speed)) this->terminate();
emit updatePosition(RND((currentPosition + speed) * 10));
}
}
void PIDThread::setPIDParameters(double p, double i, double d)
{
proportion = p / 10;
integral = i / 10;
derivative = d / 10;
}
double PIDThread::calculateSpeed()
{
double speed = proportion * error_this_time + integral * error_integral
+ derivative * (error_this_time - error_last_time);
return speed / 10.0;
}
void PIDThread::clearData()
{
error_integral = 0;
error_last_time = 0;
error_this_time = 0;
}
bool PIDThread::checkEnd(double speed)
{
if (speed < 0.05 && speed > -0.05)
{
finalStateCount++;
}
else
{
finalStateCount = 0;
}
if (finalStateCount >= 100)
return true;
return false;
}