-
Notifications
You must be signed in to change notification settings - Fork 88
/
pid.c
105 lines (82 loc) · 2.84 KB
/
pid.c
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
pid.c - An embedded CNC Controller with rs274/ngc (g-code) support
PID algorithm for closed loop control
NOTE: not referenced in the core grbl code
Part of grblHAL
Copyright (c) 2020-2021 Terje Io
Grbl is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Grbl is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Grbl. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include "pid.h"
// Fixed point version: TODO
// Float version
void pidf_init (pidf_t *pid, pid_values_t *config)
{
pidf_reset(pid);
memcpy(&pid->cfg, config, sizeof(pid_values_t));
}
bool pidf_config_changed (pidf_t *pid, pid_values_t *config)
{
return memcmp(&pid->cfg, config, sizeof(pid_values_t));
}
void pidf_reset (pidf_t *pid)
{
pid->error = 0.0f;
pid->i_error = 0.0f;
pid->d_error = 0.0f;
pid->sample_rate_prev = 1.0f;
}
float pidf (pidf_t *pid, float command, float actual, float sample_rate)
{
float error = command - actual;
/*
if(error > pid->deadband)
error -= pid->deadband;
else if (error < pid->deadband)
error += pid->deadband;
else
error = 0.0f;
*/
// calculate the proportional term
float pidres = pid->cfg.p_gain * error;
// calculate and add the integral term
pid->i_error += error * (pid->sample_rate_prev / sample_rate);
if(pid->cfg.i_max_error != 0.0f) {
if (pid->i_error > pid->cfg.i_max_error)
pid->i_error = pid->cfg.i_max_error;
else if (pid->i_error < -pid->cfg.i_max_error)
pid->i_error = -pid->cfg.i_max_error;
}
pidres += pid->cfg.i_gain * pid->i_error;
// calculate and add the derivative term
if(pid->cfg.d_gain != 0.0f) {
float p_error = (error - pid->d_error) * (sample_rate / pid->sample_rate_prev);
if(pid->cfg.d_max_error != 0.0f) {
if (p_error > pid->cfg.d_max_error)
p_error = pid->cfg.d_max_error;
else if (p_error < -pid->cfg.d_max_error)
p_error = -pid->cfg.d_max_error;
}
pidres += pid->cfg.d_gain * p_error;
pid->d_error = error;
}
pid->sample_rate_prev = sample_rate;
// limit error output
if(pid->cfg.max_error != 0.0f) {
if(pidres > pid->cfg.max_error)
pidres = pid->cfg.max_error;
else if(pidres < -pid->cfg.max_error)
pidres = -pid->cfg.max_error;
}
pid->error = pidres;
return pidres;
}