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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
use embedded_flight_core::filter::alpha;

mod slew_limiter;
pub use slew_limiter::SlewLimiter;

pub struct Info {
    pub target: f32,
    pub actual: f32,
    pub error: f32,
    pub p: f32,
    pub i: f32,
    pub d: f32,
    pub ff: f32,
    pub d_mod: f32,
    pub slew_rate: f32,
    pub limit: bool,
}

pub struct PID {
    pub reset_filter: bool,
    pub target: f32,
    pub error: f32,
    pub derivative: f32,
    // Timestep in seconds
    pub dt: f32,
    pub info: Info,
    pub slew_limiter: SlewLimiter<2>,
    pub slew_limit_scale: f32,
    pub integrator: f32,
    pub kp: f32,
    pub ki: f32,
    pub kd: f32,
    pub ki_max: f32,
    pub kff: f32,
    pub filter_t_hz: f32,
    pub filter_e_hz: f32,
    pub filter_d_hz: f32,
}

impl PID {
    pub fn new(
        initial_p: f32,
        initial_i: f32,
        initial_d: f32,
        initial_ff: f32,
        initial_imax: f32,
        initial_filt_T_hz: f32,
        initial_filt_E_hz: f32,
        initial_filt_D_hz: f32,
        dt: f32,
    ) -> Self {
        Self::with_slew_rate(
            initial_p,
            initial_i,
            initial_d,
            initial_ff,
            initial_imax,
            initial_filt_T_hz,
            initial_filt_E_hz,
            initial_filt_D_hz,
            dt,
            0.,
            1.,
        )
    }

    pub fn with_slew_rate(
        initial_p: f32,
        initial_i: f32,
        initial_d: f32,
        initial_ff: f32,
        initial_imax: f32,
        initial_filt_T_hz: f32,
        initial_filt_E_hz: f32,
        initial_filt_D_hz: f32,
        dt: f32,
        initial_srmax: f32,
        initial_srtau: f32,
    ) -> Self {
        Self {
            reset_filter: true,
            target: 0.,
            error: 0.,
            derivative: 0.,
            dt,
            info: Info {
                target: 0.,
                actual: 0.,
                error: 0.,
                p: 0.,
                i: 0.,
                d: 0.,
                ff: 0.,
                d_mod: 0.,
                slew_rate: 0.,
                limit: false,
            },
            slew_limiter: SlewLimiter::new(initial_srmax, initial_srtau),
            slew_limit_scale: initial_srtau,
            integrator: 0.,
            kp: initial_p,
            ki: initial_i,
            kd: initial_d,
            ki_max: initial_imax,
            kff: initial_ff,
            filter_t_hz: initial_filt_T_hz,
            filter_e_hz: initial_filt_E_hz,
            filter_d_hz: initial_filt_D_hz,
        }
    }
}

impl PID {
    pub fn target_filter_alpha(&self) -> f32 {
        self.alpha(self.filter_t_hz)
    }

    pub fn error_filter_alpha(&self) -> f32 {
        self.alpha(self.filter_e_hz)
    }

    pub fn derivative_filter_alpha(&self) -> f32 {
        self.alpha(self.filter_d_hz)
    }

    fn alpha(&self, cutoff_freq: f32) -> f32 {
        alpha(self.dt, cutoff_freq)
    }

    pub fn feed_forward(&self) -> f32 {
        self.target * self.kff
    }

    /// Update the integral part of this PID.
    /// If the limit flag is set the integral is only allowed to shrink.
    pub fn update_integral(&mut self, limit: bool) {
        if self.ki != 0. && self.dt > -0. {
            // Ensure that integrator can only be reduced if the output is saturated
            if !limit
                || (self.integrator >= 0. && self.error < 0.)
                || self.integrator < 0. && self.error >= 0.
            {
                self.integrator += self.error * self.ki * self.dt;
                self.integrator = self.integrator.max(-self.ki_max).min(self.ki_max);
            }
        } else {
            self.integrator = 0.;
        }
        self.info.i = self.integrator;
        self.info.limit = limit;
    }

    /// Update target and measured inputs to the PID controller and calculate output.
    /// Target and error are filtered,
    /// then derivative is calculated and filtered,
    /// then the integral is then updated based on the setting of the limit flag
    pub fn update(&mut self, target: f32, measurement: f32, limit: bool, now_ms: u32) -> f32 {
        // don't process inf or NaN
        if target.is_infinite() || measurement.is_infinite() {
            return 0.;
        }

        // reset input filter to value received
        if self.reset_filter {
            self.reset_filter = false;
            self.target = target;
            self.error = self.target - measurement;
            self.derivative = 0.;
        } else {
            let error_last = self.error;
            self.target += self.target_filter_alpha() * (target - self.target);
            self.error += self.error_filter_alpha() * ((self.target - measurement) - self.error);

            // calculate and filter derivative
            if self.dt > 0. {
                let derivative = (self.error - error_last) / self.dt;
                self.derivative += self.derivative_filter_alpha() * (derivative - self.derivative);
            }
        }

        // update I term
        self.update_integral(limit);

        let mut p_out = self.error * self.kp;
        let mut d_out = self.derivative * self.kd;

        // calculate slew limit modifier for P+D
        self.info.d_mod = self.slew_limiter.modifier(
            (self.info.p + self.info.d) * self.slew_limit_scale,
            self.dt,
            now_ms,
        );
        self.info.slew_rate = self.slew_limiter.output_slew_rate;

        p_out *= self.info.d_mod;
        d_out *= self.info.d_mod;

        self.info.target = self.target;
        self.info.actual = measurement;
        self.info.error = self.error;
        self.info.p = p_out;
        self.info.d = d_out;

        p_out + self.integrator + d_out
    }
}