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
|
/*
* PID controller
*
* Copyright (c) 2015 Michael Buesch <m@bues.ch>
*
* This program 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 2 of the License, or
* (at your option) any later version.
*
* This program 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 this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "pid.h"
#include "util.h"
#include <string.h>
void pid_reset(struct pid *pid)
{
pid->prev_e = int_to_fixpt(0);
pid->integr = int_to_fixpt(0);
}
void pid_set_factors(struct pid *pid, const struct pid_k_set *k)
{
pid->k = *k;
pid_reset(pid);
}
fixpt_t pid_run(struct pid *pid, fixpt_t dt, fixpt_t r)
{
fixpt_t e, de;
fixpt_t kp, ki, kd;
fixpt_t p, i, d;
fixpt_t pid_result = int_to_fixpt(0);
fixpt_t y_neglim = pid->y_neglim;
fixpt_t y_poslim = pid->y_poslim;
/* Calculate the deviation. */
e = fixpt_sub(pid->setpoint, r);
/* P term */
kp = pid->k.kp;
if (kp != int_to_fixpt(0)) {
p = fixpt_mul(kp, e);
pid_result = fixpt_add(pid_result, p);
}
/* I term */
ki = pid->k.ki;
if (ki != int_to_fixpt(0)) {
i = fixpt_add(pid->integr, fixpt_mul(fixpt_mul(ki, e), dt));
i = clamp(i, y_neglim, y_poslim);
pid->integr = i;
pid_result = fixpt_add(pid_result, i);
}
/* D term */
kd = pid->k.kd;
if (kd != int_to_fixpt(0)) {
de = fixpt_sub(e, pid->prev_e);
if (dt) {
d = fixpt_mul_div(de, kd, dt);
} else {
if (de < 0)
d = y_neglim;
else
d = y_poslim;
}
pid->prev_e = fixpt_div(e, pid->k.d_decay_div);
pid_result = fixpt_add(pid_result, d);
}
pid_result = clamp(pid_result, y_neglim, y_poslim);
return pid_result;
}
void pid_init(struct pid *pid,
const struct pid_k_set *k,
fixpt_t y_neglim, fixpt_t y_poslim)
{
pid->y_neglim = y_neglim;
pid->y_poslim = y_poslim;
pid_set_factors(pid, k);
}
|