stable_flight/controllers/gyro.rs
1//! The copter's gyro filter chain, a notch then a low-pass: see [`GyroFilters`].
2
3use nalgebra::Complex;
4
5use super::NotchConfig;
6use super::low_pass::LowPass;
7use super::notch::Notch;
8
9/// The filters the body rates pass through before the rate loop, as
10/// [`CopterStabilizerConfig`](crate::stabilizers::copter::CopterStabilizerConfig) sets them:
11/// a notch for one vibration tone, then the low-pass. The low-pass after the notch cleans up
12/// what it leaves, as ArduPilot and PX4 order them (`apply_gyro_filters`,
13/// `FilterAngularVelocity`). The autotune's design models both, since the rate loop's P and
14/// D act through them.
15///
16/// # Examples
17///
18/// ```
19/// use stable_flight::controllers::GyroFilters;
20///
21/// let filters = GyroFilters::low_pass(40.0);
22/// assert!(!filters.notch.is_on());
23/// ```
24#[derive(Clone, Copy, Debug, PartialEq)]
25pub struct GyroFilters {
26 /// The low-pass cutoff, in Hz; 0, or at or past Nyquist, passes the rates through.
27 pub cutoff_hz: f32,
28 /// The notch; off when its center is 0.
29 pub notch: NotchConfig,
30}
31
32impl GyroFilters {
33 /// A low-pass at `cutoff_hz` alone, the notch off.
34 pub fn low_pass(cutoff_hz: f32) -> Self {
35 Self {
36 cutoff_hz,
37 notch: NotchConfig::default(),
38 }
39 }
40
41 /// The chain's response at `unit_delay` for samples `dt_s` apart: the notch's times the
42 /// low-pass's.
43 pub fn response(&self, dt_s: f32, unit_delay: Complex<f32>) -> Complex<f32> {
44 self.notch.response(dt_s, unit_delay) * LowPass::response(self.cutoff_hz, dt_s, unit_delay)
45 }
46}
47
48/// One axis's [`GyroFilters`] state.
49#[derive(Clone, Copy, Debug, Default, PartialEq)]
50pub(crate) struct GyroFilter {
51 notch: Notch,
52 low_pass: LowPass,
53}
54
55impl GyroFilter {
56 /// `rate_radps`, sampled `dt` s after the last, through `filters`' notch, then its
57 /// low-pass.
58 pub(crate) fn apply(&mut self, rate_radps: f32, dt: f32, filters: &GyroFilters) -> f32 {
59 let notched = self.notch.apply(rate_radps, dt, &filters.notch);
60 self.low_pass.apply(notched, dt, filters.cutoff_hz)
61 }
62}
63
64#[cfg(test)]
65mod tests;