-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpid.cpp
74 lines (58 loc) · 1.34 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
67
68
69
70
71
72
73
74
/*
* Copyright (C) 2016 Tolga Ceylan
*
* CopyPolicy: Released under the terms of the GNU GPL v3.0.
*/
#include "pid.h"
#include "timer.h"
#include "logger.h"
namespace robo {
void pid_init(Pid &pid, int id, double kp, double ki, double kd)
{
pid.Kp = kp;
pid.Ki = ki;
pid.Kd = kd;
pid.error = 0.0f;
pid.time = 0;
pid.integral = 0.0f;
pid.target = 0;
pid.output = 0.0f;
pid.actual = 0;
pid.id = id;
}
void pid_update(Pid &pid, uint64_t now)
{
const double error = pid.target - pid.actual;
if (pid.time == 0)
{
pid.time = now;
pid.error = error;
}
// WARNING: Code here is probably broken
// not enough time (none) has elapsed.
if (pid.time >= now)
return;
// msecs
const double dt = Timer::get_elapsed_usec(pid.time, now) / 1000.0l;
pid.integral += error * dt;
const double derivative = (error - pid.error) / dt;
pid.output =
pid.Kp * error +
pid.Ki * pid.integral +
pid.Kd * derivative;
pid.error = error;
pid.time = now;
return;
}
void pid_logger(const Pid &pid)
{
logger(LOG_INFO, "PID id=%d intg=%f err=%f target=%d actual=%d output=%f",
pid.id,
pid.integral,
pid.error,
pid.target,
pid.actual,
pid.output
);
}
} // namespace robo