stable_flight/stabilizers/copter.rs
1//! Basic controller for a vehicle that does not transition between different flight modes such as copter and plane.
2//!
3//! A reference model for such a vehicle is the QuadCopter X.
4//! Reference model: <https://github.com/ArduPilot/SITL_Models/tree/master/RealFlight/Released_Models/Multicopters/QuadCopterX>
5//!
6//! # Control Architecture
7//!
8//! This implements a modular cascaded control system with configurable control loops:
9//!
10//! 1. **Inner Loop: Rate Control**
11//! - Controls angular rates (roll rate, pitch rate, yaw rate)
12//! - Fast update frequency (typically 400-1000Hz)
13//! - PID controllers with feed-forward terms for each axis
14//! - Flies the gyro rates through a low-pass (`STAB_GYRO_FLT`), D on the measured rate
15//! - Directly commands motor mixing algorithm
16//! - Always active as the core control layer
17//!
18//! 2. **Middle Loop: Attitude Control (Optional)**
19//! - Controls orientation angles (roll angle, pitch angle, yaw angle)
20//! - Moderate update frequency (typically 100-250Hz)
21//! - Outputs desired angular rates to inner loop
22//! - Implements angle limiting for safety
23//! - Can be used without outer position loops for manual flight modes
24//!
25//! The outer position loops (altitude and lateral position) are guidance, not stabilization:
26//! they live in [`CopterGuidance`](crate::guidance::copter::CopterGuidance), which turns
27//! commands into the [`Setpoint`] this stabilizer tracks.
28//!
29//! # Setpoints
30//!
31//! - [`Setpoint::Rate`]: rate loop only (acro), at stick fractions of
32//! [`full_scale_rates_radps`](CopterStabilizerConfig::full_scale_rates_radps); the idle
33//! attitude and heading loops are cleared, so attitude flight resumes from fresh state.
34//! - [`Setpoint::BodyRate`]: the same, at absolute rates saturated to the full-scale rates
35//! (maneuvers, offboard rates).
36//! - [`Setpoint::Plane`], [`Setpoint::PlaneRate`]: a plane stabilizer's; [`Setpoint::Blend`]: a
37//! lift+cruise VTOL's; neutral output.
38//! - [`Setpoint::Attitude`]: attitude and heading loops feeding the rate loop. They act on the
39//! body-frame error from the attitude quaternion: the shortest tilt of the thrust axis onto
40//! the setpoint's (roll and pitch relative to the current heading), then the heading error,
41//! weighted by the cosine of the tilt (PX4 `mc_att_control`, reduced attitude). Near level
42//! that is the per-axis Euler difference; far over (a tailsitter's view in transition) it
43//! stays defined and gives body rates. Roll and pitch saturate to
44//! [`max_angles_rad`](AttitudeControllerConfig::max_angles_rad), pitch to ±π/2 for a
45//! [`transition`](crate::AttitudeSetpoint::transition) ramp.
46//!
47//! An [`idle`](Setpoint::idle) setpoint (guidance's ground idle) clears every loop's integral
48//! after the tick: on the ground there's nothing for the I terms to hold, and they'd wind up
49//! against the resting attitude. Zero thrust alone doesn't: in the air it is the altitude loop
50//! shedding a climb, and the I terms hold the trim.
51//!
52//! # Tuning
53//!
54//! An autotune stage ([`start_probe`](crate::tuning::Tunable::start_probe)) hands one loop to a
55//! [`Probe`](crate::tuning::Probe). Every controller still runs each tick; before
56//! the loop's controller runs, the probe sees its
57//! [`LoopSignals`](crate::tuning::LoopSignals) and replaces the loop's setpoint (a step, or an
58//! identification's square wave).
59//!
60//! | [`TunedLoop`] | Setpoint, error |
61//! |---|---|
62//! | `RollRate`, `PitchRate`, `YawRate` | desired body rate; desired − measured |
63//! | `Roll`, `Pitch` | saturated desired angle; that − estimated angle |
64//! | `Heading` | desired heading; wrapped heading error |
65//!
66//! The signals' `saturated` is the last tick's clip on the loop's path: the axis's moment, and
67//! for an angle or heading loop also its rate setpoint.
68//!
69//! - **Rate stages** replace the rate setpoint the angle loop sets, so the angle loop around
70//! the tested axis has no say while a step runs. An identification adds its square wave to
71//! that setpoint instead, so the angle loop still holds the attitude.
72//! - **Handoff:** when the probe finishes, on [`stop_probe`](crate::tuning::Tunable::stop_probe),
73//! or when a [`Setpoint::Rate`] tick idles the angle or heading loop under test
74//! ([`ProbeStatus::Interrupted`](crate::tuning::ProbeStatus::Interrupted)), the loop
75//! restarts with no derivative history and keeps its I term, which a retune with the tuned
76//! gains rescales like any other (`architecture.md#config-ownership`). On an interrupt the
77//! rate tick then clears the idle angle loops, so their I terms are dropped. An angle
78//! stage's identification runs on the rate loop under it, so a rate tick doesn't interrupt
79//! it.
80//! - The stage is runtime state, not config; [`prime`](crate::Stabilizer::prime) ends it.
81
82use crate::{Vec2, Vec3};
83
84use crate::{
85 AttitudeSetpoint, Configurable, ControlOutput, Saturation, Setpoint, Stabilizer, VehicleState,
86};
87
88use crate::controllers::low_pass::LowPass;
89use crate::controllers::*;
90use crate::controllers::{check_limit, check_positive};
91use crate::math::{
92 assert_dt, attitude_error, pitch_limit_rad, saturate_rates, saturate_unit, thrust_curve,
93};
94
95mod params;
96#[cfg(test)]
97mod tests;
98mod tuning;
99
100pub use tuning::TunedLoop;
101
102/// Configuration for the [CopterStabilizer]: gains and limits for the inner control loops and
103/// the thrust mapping.
104///
105/// Plain data: [`CopterStabilizer::new`] validates it, and the stabilizer passes it to its
106/// controllers every tick.
107#[derive(Clone, Copy, Debug, PartialEq)]
108pub struct CopterStabilizerConfig {
109 /// Body-rate (inner) loop.
110 pub body_rate: BodyRateControllerConfig,
111 /// Roll/pitch attitude loop ([`Setpoint::Attitude`] only).
112 pub attitude: AttitudeControllerConfig,
113 /// Heading-hold loop ([`Setpoint::Attitude`] only).
114 pub yaw: YawControllerConfig,
115 /// Body rates (roll, pitch, yaw) in rad/s that a full-scale [`RateSetpoint`](crate::RateSetpoint) maps to. Each
116 /// component must be non-negative and finite: an infinite or NaN scale makes even a neutral
117 /// stick a non-finite rate, which zeroes that axis's moment.
118 pub full_scale_rates_radps: Vec3,
119 /// Exponent of the thrust curve applied to the linear thrust setpoint. Must be positive
120 /// and finite: a negative exponent maps zero throttle to full thrust.
121 pub thrust_curve_exponent: f32,
122 /// Cutoff of the low-pass on the body rates the rate loop flies, in Hz; 0 turns it off,
123 /// and so does one at or past Nyquist. Non-negative and finite. Lower: less gyro noise
124 /// and vibration in the moments, more lag in the loop (about 5.6 ms at 40 Hz). The
125 /// default is PX4's `IMU_GYRO_CUTOFF`; on the sim's 0.1 rad/s vibration at 90 Hz, 40 Hz
126 /// passed the most robustness rows, 20 Hz (ArduPilot's `INS_GYRO_FILTER`) and 50 Hz and up
127 /// lost clean rows (#373).
128 pub gyro_cutoff_hz: f32,
129}
130
131/// [`CopterStabilizerConfig::gyro_cutoff_hz`]'s default, in Hz.
132pub const DEFAULT_GYRO_CUTOFF_HZ: f32 = 40.0;
133
134impl Default for CopterStabilizerConfig {
135 /// Untuned starting values; airframes override them with flight-checked sets.
136 fn default() -> Self {
137 CopterStabilizerConfig {
138 body_rate: BodyRateControllerConfig::default(),
139 attitude: AttitudeControllerConfig::default(),
140 yaw: YawControllerConfig::default(),
141 full_scale_rates_radps: Vec3::new(3.0, 3.0, 3.0),
142 thrust_curve_exponent: 2.0,
143 gyro_cutoff_hz: DEFAULT_GYRO_CUTOFF_HZ,
144 }
145 }
146}
147
148impl CopterStabilizerConfig {
149 /// Checks every controller config ([`BodyRateControllerConfig::validate`],
150 /// [`AttitudeControllerConfig::validate`], [`YawControllerConfig::validate`]; errors carry
151 /// the loop as their `section`), that each `full_scale_rates_radps` component is
152 /// non-negative and finite, that `thrust_curve_exponent` is positive and finite, and that
153 /// `gyro_cutoff_hz` is non-negative and finite.
154 ///
155 /// # Examples
156 ///
157 /// ```
158 /// use stable_flight::stabilizers::copter::CopterStabilizerConfig;
159 ///
160 /// let mut config = CopterStabilizerConfig::default();
161 /// assert!(config.validate().is_ok());
162 /// config.yaw.max_rate_radps = -1.0;
163 /// assert!(config.validate().is_err());
164 /// ```
165 pub fn validate(&self) -> Result<(), InvalidConfig> {
166 self.body_rate
167 .validate()
168 .map_err(|e| e.in_section("body_rate"))?;
169 self.attitude
170 .validate()
171 .map_err(|e| e.in_section("attitude"))?;
172 self.yaw.validate().map_err(|e| e.in_section("yaw"))?;
173 let scales = &self.full_scale_rates_radps;
174 check_limit("full_scale_rates_radps.x", scales.x)?;
175 check_limit("full_scale_rates_radps.y", scales.y)?;
176 check_limit("full_scale_rates_radps.z", scales.z)?;
177 check_positive("thrust_curve_exponent", self.thrust_curve_exponent)?;
178 check_limit("gyro_cutoff_hz", self.gyro_cutoff_hz)
179 }
180}
181
182/// The inner loop for vehicles like quadcopters, implementing a cascaded control system.
183///
184/// This controller supports rate and attitude control loops, with configurable gains for
185/// each loop. It tracks a [`Setpoint`] ([`RateSetpoint`](crate::RateSetpoint) or [`AttitudeSetpoint`]) and
186/// generates motor control outputs ([`ControlOutput`]).
187///
188/// # Examples
189///
190/// ```
191/// use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
192/// use stable_flight::{AttitudeSetpoint, Setpoint, Stabilizer, VehicleState};
193///
194/// let mut stabilizer = CopterStabilizer::new(CopterStabilizerConfig::default());
195/// let hover = Setpoint::Attitude(AttitudeSetpoint { thrust: 0.5, ..Default::default() });
196///
197/// let output = stabilizer.stabilize(0.004, &hover, &VehicleState::default());
198/// assert_eq!(output.thrust, 0.25); // 0.5 through the default quadratic thrust curve
199/// ```
200pub struct CopterStabilizer {
201 /// Gains and limits, passed into each controller every tick.
202 config: CopterStabilizerConfig,
203
204 body_rate: BodyRateController,
205 attitude: AttitudeController,
206 yaw: YawController,
207
208 /// What the last `stabilize` call clipped.
209 saturation: Saturation,
210
211 /// The autotune stage, if one was started and not yet stopped.
212 stage: Option<tuning::Stage>,
213
214 /// What the last `stabilize` call clipped per axis, for a probe's
215 /// [`LoopSignals::saturated`](crate::tuning::LoopSignals::saturated).
216 clipped: Clipped,
217
218 /// The moments the last `stabilize` call commanded (roll, pitch, yaw), for a probe's
219 /// [`LoopSignals::last_moment`](crate::tuning::LoopSignals::last_moment).
220 last_moments: Vec3,
221
222 /// The low-pass per body rate (roll, pitch, yaw) at
223 /// [`gyro_cutoff_hz`](CopterStabilizerConfig::gyro_cutoff_hz).
224 gyro_filters: [LowPass; 3],
225}
226
227/// Per-axis clips (roll, pitch, yaw) of one tick.
228#[derive(Clone, Copy, Debug, Default, PartialEq)]
229struct Clipped {
230 /// The rate loop's moment hit ±1.
231 moments: [bool; 3],
232 /// The attitude or heading loop's rate setpoint hit its `max_rate_radps`.
233 rates: [bool; 3],
234}
235
236impl CopterStabilizer {
237 /// Creates a new [CopterStabilizer] with the specified configuration.
238 ///
239 /// # Arguments
240 ///
241 /// * `config` - Configuration for the controller, including PID gains and thrust curve exponent.
242 ///
243 /// # Panics
244 ///
245 /// If `config` is invalid ([`CopterStabilizerConfig::validate`]).
246 pub fn new(config: CopterStabilizerConfig) -> Self {
247 if let Err(error) = config.validate() {
248 panic!("invalid CopterStabilizerConfig: {error}");
249 }
250 CopterStabilizer {
251 config,
252 body_rate: BodyRateController::default(),
253 attitude: AttitudeController::default(),
254 yaw: YawController::default(),
255 saturation: Saturation::default(),
256 stage: None,
257 clipped: Clipped::default(),
258 last_moments: Vec3::zeros(),
259 gyro_filters: Default::default(),
260 }
261 }
262}
263
264impl Configurable for CopterStabilizer {
265 type Config = CopterStabilizerConfig;
266
267 fn config(&self) -> &CopterStabilizerConfig {
268 &self.config
269 }
270
271 /// Validates with [`CopterStabilizerConfig::validate`].
272 fn set_config(&mut self, config: CopterStabilizerConfig) -> Result<(), InvalidConfig> {
273 config.validate()?;
274 let old = &self.config;
275 self.body_rate
276 .rescale_integral(&old.body_rate, &config.body_rate);
277 self.attitude
278 .rescale_integral(&old.attitude, &config.attitude);
279 self.yaw.rescale_integral(&old.yaw, &config.yaw);
280 self.config = config;
281 Ok(())
282 }
283}
284
285impl Stabilizer for CopterStabilizer {
286 /// Tracks a setpoint and generates motor control outputs based on the current vehicle state.
287 ///
288 /// # Arguments
289 ///
290 /// * `dt` - Time step since the last update in seconds (must be positive and finite).
291 /// * `setpoint` - The attitude or rate target.
292 /// * `estimated_state` - The current state of the vehicle (attitude, angular rates, etc.).
293 ///
294 /// # Returns
295 ///
296 /// A [ControlOutput] containing the normalized thrust (0.0 to 1.0) and moments (roll, pitch, yaw) in N·m.
297 fn stabilize(
298 &mut self,
299 dt: f32,
300 setpoint: &Setpoint,
301 estimated_state: &VehicleState,
302 ) -> ControlOutput {
303 assert_dt(dt);
304 self.saturation = Saturation::default();
305
306 let output = match setpoint {
307 Setpoint::Attitude(attitude) => self.track_attitude(dt, attitude, estimated_state),
308 Setpoint::Rate(rates) => {
309 // Per-component saturation: `clamp` alone passes NaN, which would zero that
310 // axis's moment (no damping) instead of meaning "hold zero rate".
311 let fractions = Vec3::new(
312 saturate_unit(rates.roll_rate),
313 saturate_unit(rates.pitch_rate),
314 saturate_unit(rates.yaw_rate),
315 );
316 let desired = fractions.component_mul(&self.config.full_scale_rates_radps);
317 self.track_rates(dt, desired, rates.thrust, estimated_state)
318 }
319 Setpoint::BodyRate(rates) => {
320 let desired = saturate_rates(
321 Vec3::new(rates.roll_radps, rates.pitch_radps, rates.yaw_radps),
322 self.config.full_scale_rates_radps,
323 );
324 self.track_rates(dt, desired, rates.thrust, estimated_state)
325 }
326 // A plane stabilizer's setpoints: neutral (the trait's rule for unsupported ones).
327 Setpoint::Plane(_) | Setpoint::PlaneRate(_) | Setpoint::Blend(_) => {
328 ControlOutput::default()
329 }
330 };
331
332 // At ground idle the I terms can't act on anything and would wind up against a
333 // resting attitude, to kick at liftoff; clear them every such tick. ArduPilot decays
334 // its rate I terms at GROUND_IDLE instead (`ArduCopter/mode_stabilize.cpp:36`); which
335 // to follow is #397.
336 if setpoint.idle() {
337 self.body_rate.clear_integral();
338 self.attitude.clear_integral();
339 self.yaw.clear_integral();
340 }
341
342 // The rate loop clamps each moment to [-1, 1]; landing on a bound means it clipped.
343 self.saturation.moments = output.moments.map(|m| m.abs() >= 1.0).into();
344 self.clipped.moments = self.saturation.moments;
345 self.last_moments = output.moments;
346 self.finish_stage();
347 output
348 }
349
350 /// Clears the body-rate, attitude, and yaw controller state (integrals and derivative
351 /// history) and the gyro filters, so control after arming starts from zero, and ends any
352 /// tuning stage.
353 fn prime(&mut self, _state: &VehicleState) {
354 self.stage = None;
355 self.clipped = Clipped::default();
356 self.last_moments = Vec3::zeros();
357 self.gyro_filters = Default::default();
358 self.body_rate = BodyRateController::default();
359 self.attitude = AttitudeController::default();
360 self.yaw = YawController::default();
361 self.saturation = Saturation::default();
362 }
363
364 /// `tilt` when an attitude setpoint's roll or pitch was beyond
365 /// [`max_angles_rad`](AttitudeControllerConfig::max_angles_rad), `thrust` when the
366 /// setpoint's thrust was outside `[0, 1]`, and `moments` per axis when the rate loop's
367 /// output hit ±1.
368 fn saturation(&self) -> Saturation {
369 self.saturation
370 }
371}
372
373impl CopterStabilizer {
374 /// Tracks an [AttitudeSetpoint].
375 ///
376 /// Converts the desired roll, pitch, and heading into angular rates using the attitude and
377 /// yaw controllers, then passes the rates to the rate controller to generate moments.
378 ///
379 /// # Arguments
380 ///
381 /// * `dt` - Time step since the last update in seconds (must be positive and finite).
382 /// * `setpoint` - The desired roll, pitch, and heading (radians), and linear thrust.
383 /// * `estimated_state` - The current state of the vehicle (attitude, angular rates, etc.).
384 ///
385 /// # Returns
386 ///
387 /// A `ControlOutput` containing the normalized thrust (0.0 to 1.0) and moments (roll, pitch, yaw) in N·m.
388 fn track_attitude(
389 &mut self,
390 dt: f32,
391 setpoint: &AttitudeSetpoint,
392 estimated_state: &VehicleState,
393 ) -> ControlOutput {
394 // Roll/pitch saturate inside the attitude controller, thrust in the thrust curve (see
395 // `crate::math`).
396 let max_angles_rad = self.max_angles_rad(setpoint);
397 // `>` is false for NaN, which saturates to level.
398 self.saturation.tilt = setpoint.roll_rad.abs() > max_angles_rad.x
399 || setpoint.pitch_rad.abs() > max_angles_rad.y;
400 let attitude = &estimated_state.attitude;
401 let saturate_tilt = |roll_rad: f32, pitch_rad: f32, heading_rad: f32| {
402 let tilt = AttitudeController::saturate_setpoint(
403 max_angles_rad,
404 Vec2::new(roll_rad, pitch_rad),
405 );
406 Vec3::new(tilt.x, tilt.y, heading_rad)
407 };
408
409 // Roll, pitch, and heading setpoints; a probe on one of these loops may replace one.
410 // A NaN heading gives a NaN yaw error, which the yaw loop holds on (no yaw rate).
411 let mut desired =
412 saturate_tilt(setpoint.roll_rad, setpoint.pitch_rad, setpoint.heading_rad);
413 let error_for = |angles: &Vec3| attitude_error(attitude, angles.x, angles.y, angles.z);
414 let mut error = error_for(&desired);
415 let probed = desired;
416 // The raw rates: the identify fit models the airframe, without the gyro filter's lag.
417 self.probe_attitude(
418 dt,
419 &mut desired,
420 &error,
421 &estimated_state.angular_velocity_radps,
422 );
423 // `!=` is true for a NaN heading too; recomputing is harmless.
424 if desired != probed {
425 desired = saturate_tilt(desired.x, desired.y, desired.z);
426 error = error_for(&desired);
427 }
428
429 // The loops act on the body-frame rotation to the setpoint, so their outputs are body
430 // rates at any attitude (a tailsitter's view pitches far over in transition).
431 let config = &self.config;
432 let desired_rates = self
433 .attitude
434 .control_error(&config.attitude, dt, error.xy());
435 let desired_yaw_rate = self.yaw.control_error(&config.yaw, dt, error.z);
436 // The controllers clamp their rate outputs; landing on a bound means they clipped.
437 let max_rates = config.attitude.max_rate_radps;
438 self.clipped.rates = [
439 desired_rates.x.abs() >= max_rates.x,
440 desired_rates.y.abs() >= max_rates.y,
441 desired_yaw_rate.abs() >= config.yaw.max_rate_radps,
442 ];
443
444 let desired_rates = Vec3::new(desired_rates.x, desired_rates.y, desired_yaw_rate);
445 let moments = self.track_body_rates(dt, desired_rates, estimated_state);
446
447 ControlOutput {
448 thrust: self.fit_to_thrust_curve(setpoint.thrust),
449 moments,
450 cruise: None,
451 }
452 }
453
454 /// The roll and pitch limits for `setpoint`: `max_angles_rad`, with pitch lifted to ±π/2
455 /// for a transition ramp.
456 fn max_angles_rad(&self, setpoint: &AttitudeSetpoint) -> Vec2 {
457 let limits_rad = self.config.attitude.max_angles_rad;
458 Vec2::new(
459 limits_rad.x,
460 pitch_limit_rad(limits_rad.y, setpoint.transition),
461 )
462 }
463
464 /// Tracks body rates in rad/s with linear `thrust`, bypassing the attitude controller.
465 fn track_rates(
466 &mut self,
467 dt: f32,
468 desired_rates_radps: Vec3,
469 thrust: f32,
470 estimated_state: &VehicleState,
471 ) -> ControlOutput {
472 // The attitude and heading loops are idle: a stage on one of them ends, and they are
473 // cleared so a switch back to attitude flight carries no stale integral or derivative
474 // history.
475 self.interrupt_attitude_stage();
476 self.attitude = AttitudeController::default();
477 self.yaw = YawController::default();
478 self.clipped.rates = [false; 3];
479
480 let moments = self.track_body_rates(dt, desired_rates_radps, estimated_state);
481 ControlOutput {
482 thrust: self.fit_to_thrust_curve(thrust),
483 moments,
484 cruise: None,
485 }
486 }
487
488 /// Runs the body-rate loop toward `desired_rates_radps` on the gyro-filtered rates; a stage
489 /// on a rate loop replaces that axis's rate setpoint.
490 fn track_body_rates(
491 &mut self,
492 dt: f32,
493 desired_rates_radps: Vec3,
494 estimated_state: &VehicleState,
495 ) -> Vec3 {
496 let current_rates = self.filter_rates(dt, estimated_state.angular_velocity_radps);
497 let mut desired_rates_radps = desired_rates_radps;
498 self.probe_rates(
499 dt,
500 &mut desired_rates_radps,
501 ¤t_rates,
502 &estimated_state.angular_velocity_radps,
503 );
504 self.body_rate.control(
505 &self.config.body_rate,
506 dt,
507 desired_rates_radps,
508 current_rates,
509 )
510 }
511
512 /// `rates_radps` (body frame, roll, pitch, yaw) through the gyro low-pass, per axis.
513 fn filter_rates(&mut self, dt: f32, rates_radps: Vec3) -> Vec3 {
514 let cutoff_hz = self.config.gyro_cutoff_hz;
515 Vec3::from_fn(|axis, _| self.gyro_filters[axis].apply(rates_radps[axis], dt, cutoff_hz))
516 }
517
518 /// Applies a nonlinear thrust curve to a linear thrust command.
519 ///
520 /// Maps a linear thrust value (0.0 to 1.0) to a nonlinear output using the configured thrust curve exponent.
521 /// This compensates for nonlinear motor responses. Out-of-range input saturates (flagging
522 /// `thrust`) and NaN becomes 0 (motors off), per the input policy.
523 ///
524 /// # Arguments
525 ///
526 /// * `linear_thrust` - Linear thrust command (0.0 to 1.0).
527 ///
528 /// # Returns
529 ///
530 /// Nonlinear thrust command (0.0 to 1.0).
531 fn fit_to_thrust_curve(&mut self, linear_thrust: f32) -> f32 {
532 self.saturation.thrust = !(0.0..=1.0).contains(&linear_thrust) && !linear_thrust.is_nan();
533 thrust_curve(linear_thrust, self.config.thrust_curve_exponent)
534 }
535}