-
Notifications
You must be signed in to change notification settings - Fork 46
/
pid.cpp
66 lines (56 loc) · 1.73 KB
/
pid.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
63
64
65
66
#include<pid.h>
void pid_move::move()
{
while (1)
{
std::unique_lock<std::mutex> lock(data_mutex_);
data_cond_.wait(lock, [this] { return data_ready_; });
is_moving = true;
//std::cout << Type << " " << target_position << " " << Kp << " " << std::endl;
// 计算误差
error_x = target_position_x;
error_y = target_position_y;
// 计算积分项
integral_x += error_x;
integral_y += error_y;
// 计算微分项
derivative_x = error_x - last_error_x;
derivative_y = error_y - last_error_y;
// 更新上一次的误差
last_error_x = error_x;
last_error_y = error_y;
// 计算控制量
double control_x = Kp * error_x + Ki * integral_x + Kd * derivative_x;
double control_y = (Kp+0.05) * error_y + Ki * integral_y + Kd * derivative_y;
// 假设控制器的输出为移动的距离
move_distance_x = control_x;
move_distance_y = control_y;
mouse_event(MOUSEEVENTF_MOVE, move_distance_x, move_distance_y, 0, 0);
data_ready_ = false;
is_moving = false;
}
}
void pid_move::refresh()
{
integral_x = 0.0;
last_error_x = 0.0;
integral_y = 0.0;
last_error_y = 0.0;
move_distance_x = 0;
move_distance_y = 0;
}
void pid_move::init(double kp, double ki, double kd)
{
Kp = kp;
Ki = ki;
Kd = kd;
}
void pid_move::smooth()
{
while (1)
{
if (is_moving)
continue;
mouse_event(MOUSEEVENTF_MOVE, move_distance_x / sqrt((pow(move_distance_x, 2) + pow(move_distance_y, 2))), move_distance_y / sqrt((pow(move_distance_x, 2) + pow(move_distance_y, 2))), 0, 0);
}
}