2 * This file is part of Cleanflight and Betaflight.
4 * Cleanflight and Betaflight are free software. You can redistribute
5 * this software and/or modify this software under the terms of the
6 * GNU General Public License as published by the Free Software
7 * Foundation, either version 3 of the License, or (at your option)
10 * Cleanflight and Betaflight are distributed in the hope that they
11 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
12 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this software.
18 * If not, see <http://www.gnu.org/licenses/>.
28 #include "build/build_config.h"
29 #include "build/debug.h"
31 #include "common/axis.h"
32 #include "common/filter.h"
34 #include "config/config_reset.h"
35 #include "config/simplified_tuning.h"
37 #include "drivers/pwm_output.h"
38 #include "drivers/sound_beeper.h"
39 #include "drivers/time.h"
41 #include "fc/controlrate_profile.h"
44 #include "fc/rc_controls.h"
45 #include "fc/runtime_config.h"
47 #include "flight/gps_rescue.h"
48 #include "flight/imu.h"
49 #include "flight/mixer.h"
50 #include "flight/rpm_filter.h"
51 #include "flight/feedforward.h"
56 #include "pg/pg_ids.h"
58 #include "sensors/acceleration.h"
59 #include "sensors/battery.h"
60 #include "sensors/gyro.h"
70 const char pidNames
[] =
77 FAST_DATA_ZERO_INIT
uint32_t targetPidLooptime
;
78 FAST_DATA_ZERO_INIT pidAxisData_t pidData
[XYZ_AXIS_COUNT
];
79 FAST_DATA_ZERO_INIT pidRuntime_t pidRuntime
;
81 #if defined(USE_ABSOLUTE_CONTROL)
82 STATIC_UNIT_TESTED FAST_DATA_ZERO_INIT
float axisError
[XYZ_AXIS_COUNT
];
85 #if defined(USE_THROTTLE_BOOST)
86 FAST_DATA_ZERO_INIT
float throttleBoost
;
87 pt1Filter_t throttleLpf
;
90 PG_REGISTER_WITH_RESET_TEMPLATE(pidConfig_t
, pidConfig
, PG_PID_CONFIG
, 2);
93 #define PID_PROCESS_DENOM_DEFAULT 8
94 #elif defined(STM32F3)
95 #define PID_PROCESS_DENOM_DEFAULT 4
96 #elif defined(STM32F411xE)
97 #define PID_PROCESS_DENOM_DEFAULT 2
99 #define PID_PROCESS_DENOM_DEFAULT 1
102 #ifdef USE_RUNAWAY_TAKEOFF
103 PG_RESET_TEMPLATE(pidConfig_t
, pidConfig
,
104 .pid_process_denom
= PID_PROCESS_DENOM_DEFAULT
,
105 .runaway_takeoff_prevention
= true,
106 .runaway_takeoff_deactivate_throttle
= 20, // throttle level % needed to accumulate deactivation time
107 .runaway_takeoff_deactivate_delay
= 500 // Accumulated time (in milliseconds) before deactivation in successful takeoff
110 PG_RESET_TEMPLATE(pidConfig_t
, pidConfig
,
111 .pid_process_denom
= PID_PROCESS_DENOM_DEFAULT
115 #ifdef USE_ACRO_TRAINER
116 #define ACRO_TRAINER_LOOKAHEAD_RATE_LIMIT 500.0f // Max gyro rate for lookahead time scaling
117 #define ACRO_TRAINER_SETPOINT_LIMIT 1000.0f // Limit the correcting setpoint
118 #endif // USE_ACRO_TRAINER
120 #define CRASH_RECOVERY_DETECTION_DELAY_US 1000000 // 1 second delay before crash recovery detection is active after entering a self-level mode
122 #define LAUNCH_CONTROL_YAW_ITERM_LIMIT 50 // yaw iterm windup limit when launch mode is "FULL" (all axes)
124 PG_REGISTER_ARRAY_WITH_RESET_FN(pidProfile_t
, PID_PROFILE_COUNT
, pidProfiles
, PG_PID_PROFILE
, 2);
126 void resetPidProfile(pidProfile_t
*pidProfile
)
128 RESET_CONFIG(pidProfile_t
, pidProfile
,
130 [PID_ROLL
] = PID_ROLL_DEFAULT
,
131 [PID_PITCH
] = PID_PITCH_DEFAULT
,
132 [PID_YAW
] = PID_YAW_DEFAULT
,
133 [PID_LEVEL
] = { 50, 50, 75, 0 },
134 [PID_MAG
] = { 40, 0, 0, 0 },
136 .pidSumLimit
= PIDSUM_LIMIT
,
137 .pidSumLimitYaw
= PIDSUM_LIMIT_YAW
,
140 .dterm_notch_cutoff
= 0,
141 .itermWindupPointPercent
= 100,
142 .pidAtMinThrottle
= PID_STABILISATION_ON
,
143 .levelAngleLimit
= 55,
144 .feedforwardTransition
= 0,
145 .yawRateAccelLimit
= 0,
147 .itermThrottleThreshold
= 250,
148 .itermAcceleratorGain
= 3500,
149 .crash_time
= 500, // ms
150 .crash_delay
= 0, // ms
151 .crash_recovery_angle
= 10, // degrees
152 .crash_recovery_rate
= 100, // degrees/second
153 .crash_dthreshold
= 50, // degrees/second/second
154 .crash_gthreshold
= 400, // degrees/second
155 .crash_setpoint_threshold
= 350, // degrees/second
156 .crash_recovery
= PID_CRASH_RECOVERY_OFF
, // off by default
157 .horizon_tilt_effect
= 75,
158 .horizon_tilt_expert_mode
= false,
159 .crash_limit_yaw
= 200,
162 .throttle_boost_cutoff
= 15,
163 .iterm_rotation
= false,
164 .iterm_relax
= ITERM_RELAX_RP
,
165 .iterm_relax_cutoff
= ITERM_RELAX_CUTOFF_DEFAULT
,
166 .iterm_relax_type
= ITERM_RELAX_SETPOINT
,
167 .acro_trainer_angle_limit
= 20,
168 .acro_trainer_lookahead_ms
= 50,
169 .acro_trainer_debug_axis
= FD_ROLL
,
170 .acro_trainer_gain
= 75,
171 .abs_control_gain
= 0,
172 .abs_control_limit
= 90,
173 .abs_control_error_limit
= 20,
174 .abs_control_cutoff
= 11,
175 .antiGravityMode
= ANTI_GRAVITY_SMOOTH
,
176 .dterm_lowpass_hz
= 150, // NOTE: dynamic lpf is enabled by default so this setting is actually
177 // overridden and the static lowpass 1 is disabled. We can't set this
178 // value to 0 otherwise Configurator versions 10.4 and earlier will also
179 // reset the lowpass filter type to PT1 overriding the desired BIQUAD setting.
180 .dterm_lowpass2_hz
= DTERM_LOWPASS_2_HZ_DEFAULT
, // second Dterm LPF ON by default
181 .dterm_filter_type
= FILTER_PT1
,
182 .dterm_filter2_type
= FILTER_PT1
,
183 .dyn_lpf_dterm_min_hz
= DYN_LPF_DTERM_MIN_HZ_DEFAULT
,
184 .dyn_lpf_dterm_max_hz
= DYN_LPF_DTERM_MAX_HZ_DEFAULT
,
185 .launchControlMode
= LAUNCH_CONTROL_MODE_NORMAL
,
186 .launchControlThrottlePercent
= 20,
187 .launchControlAngleLimit
= 0,
188 .launchControlGain
= 40,
189 .launchControlAllowTriggerReset
= true,
190 .use_integrated_yaw
= false,
191 .integrated_yaw_relax
= 200,
192 .thrustLinearization
= 0,
193 .d_min
= D_MIN_DEFAULT
,
196 .motor_output_limit
= 100,
197 .auto_profile_cell_count
= AUTO_PROFILE_CELL_COUNT_STAY
,
198 .transient_throttle_limit
= 0,
199 .profileName
= { 0 },
200 .dyn_idle_min_rpm
= 0,
201 .dyn_idle_p_gain
= 50,
202 .dyn_idle_i_gain
= 50,
203 .dyn_idle_d_gain
= 50,
204 .dyn_idle_max_increase
= 150,
205 .feedforward_averaging
= FEEDFORWARD_AVERAGING_OFF
,
206 .feedforward_max_rate_limit
= 100,
207 .feedforward_smooth_factor
= 37,
208 .feedforward_jitter_factor
= 7,
209 .feedforward_boost
= 15,
210 .dyn_lpf_curve_expo
= 5,
211 .level_race_mode
= false,
212 .vbat_sag_compensation
= 0,
213 .simplified_pids_mode
= PID_SIMPLIFIED_TUNING_OFF
,
214 .simplified_master_multiplier
= SIMPLIFIED_TUNING_DEFAULT
,
215 .simplified_roll_pitch_ratio
= SIMPLIFIED_TUNING_DEFAULT
,
216 .simplified_i_gain
= SIMPLIFIED_TUNING_DEFAULT
,
217 .simplified_pd_ratio
= SIMPLIFIED_TUNING_DEFAULT
,
218 .simplified_pd_gain
= SIMPLIFIED_TUNING_DEFAULT
,
219 .simplified_dmin_ratio
= SIMPLIFIED_TUNING_DEFAULT
,
220 .simplified_feedforward_gain
= SIMPLIFIED_TUNING_DEFAULT
,
221 .simplified_dterm_filter
= false,
222 .simplified_dterm_filter_multiplier
= SIMPLIFIED_TUNING_DEFAULT
,
225 pidProfile
->pid
[PID_ROLL
].D
= 30;
226 pidProfile
->pid
[PID_PITCH
].D
= 32;
230 void pgResetFn_pidProfiles(pidProfile_t
*pidProfiles
)
232 for (int i
= 0; i
< PID_PROFILE_COUNT
; i
++) {
233 resetPidProfile(&pidProfiles
[i
]);
237 // Scale factors to make best use of range with D_LPF debugging, aiming for max +/-16K as debug values are 16 bit
238 #define D_LPF_RAW_SCALE 25
239 #define D_LPF_FILT_SCALE 22
242 void pidSetItermAccelerator(float newItermAccelerator
)
244 pidRuntime
.itermAccelerator
= newItermAccelerator
;
247 bool pidOsdAntiGravityActive(void)
249 return (pidRuntime
.itermAccelerator
> pidRuntime
.antiGravityOsdCutoff
);
252 void pidStabilisationState(pidStabilisationState_e pidControllerState
)
254 pidRuntime
.pidStabilisationEnabled
= (pidControllerState
== PID_STABILISATION_ON
) ? true : false;
257 const angle_index_t rcAliasToAngleIndexMap
[] = { AI_ROLL
, AI_PITCH
};
259 float pidGetFfBoostFactor()
261 return pidRuntime
.ffBoostFactor
;
264 #ifdef USE_FEEDFORWARD
265 float pidGetFfSmoothFactor()
267 return pidRuntime
.ffSmoothFactor
;
270 float pidGetFfJitterFactor()
272 return pidRuntime
.ffJitterFactor
;
276 void pidResetIterm(void)
278 for (int axis
= 0; axis
< 3; axis
++) {
279 pidData
[axis
].I
= 0.0f
;
280 #if defined(USE_ABSOLUTE_CONTROL)
281 axisError
[axis
] = 0.0f
;
286 void pidUpdateAntiGravityThrottleFilter(float throttle
)
288 if (pidRuntime
.antiGravityMode
== ANTI_GRAVITY_SMOOTH
) {
289 // calculate a boost factor for P in the same way as for I when throttle changes quickly
290 const float antiGravityThrottleLpf
= pt1FilterApply(&pidRuntime
.antiGravityThrottleLpf
, throttle
);
291 // focus P boost on low throttle range only
292 if (throttle
< 0.5f
) {
293 pidRuntime
.antiGravityPBoost
= 0.5f
- throttle
;
295 pidRuntime
.antiGravityPBoost
= 0.0f
;
297 // use lowpass to identify start of a throttle up, use this to reduce boost at start by half
298 if (antiGravityThrottleLpf
< throttle
) {
299 pidRuntime
.antiGravityPBoost
*= 0.5f
;
301 // high-passed throttle focuses boost on faster throttle changes
302 pidRuntime
.antiGravityThrottleHpf
= fabsf(throttle
- antiGravityThrottleLpf
);
303 pidRuntime
.antiGravityPBoost
= pidRuntime
.antiGravityPBoost
* pidRuntime
.antiGravityThrottleHpf
;
304 // smooth the P boost at 3hz to remove the jagged edges and prolong the effect after throttle stops
305 pidRuntime
.antiGravityPBoost
= pt1FilterApply(&pidRuntime
.antiGravitySmoothLpf
, pidRuntime
.antiGravityPBoost
);
309 #ifdef USE_ACRO_TRAINER
310 void pidAcroTrainerInit(void)
312 pidRuntime
.acroTrainerAxisState
[FD_ROLL
] = 0;
313 pidRuntime
.acroTrainerAxisState
[FD_PITCH
] = 0;
315 #endif // USE_ACRO_TRAINER
317 #ifdef USE_THRUST_LINEARIZATION
318 float pidCompensateThrustLinearization(float throttle
)
320 if (pidRuntime
.thrustLinearization
!= 0.0f
) {
321 // for whoops where a lot of TL is needed, allow more throttle boost
322 const float throttleReversed
= (1.0f
- throttle
);
323 throttle
/= 1.0f
+ pidRuntime
.throttleCompensateAmount
* powf(throttleReversed
, 2);
328 float pidApplyThrustLinearization(float motorOutput
)
330 if (pidRuntime
.thrustLinearization
!= 0.0f
) {
331 if (motorOutput
> 0.0f
) {
332 const float motorOutputReversed
= (1.0f
- motorOutput
);
333 motorOutput
*= 1.0f
+ powf(motorOutputReversed
, 2) * pidRuntime
.thrustLinearization
;
341 // calculate the stick deflection while applying level mode expo
342 static float getLevelModeRcDeflection(uint8_t axis
)
344 const float stickDeflection
= getRcDeflection(axis
);
346 const float expof
= currentControlRateProfile
->levelExpo
[axis
] / 100.0f
;
347 return power3(stickDeflection
) * expof
+ stickDeflection
* (1 - expof
);
349 return stickDeflection
;
353 // calculates strength of horizon leveling; 0 = none, 1.0 = most leveling
354 STATIC_UNIT_TESTED
float calcHorizonLevelStrength(void)
356 // start with 1.0 at center stick, 0.0 at max stick deflection:
357 float horizonLevelStrength
= 1.0f
- MAX(fabsf(getLevelModeRcDeflection(FD_ROLL
)), fabsf(getLevelModeRcDeflection(FD_PITCH
)));
359 // 0 at level, 90 at vertical, 180 at inverted (degrees):
360 const float currentInclination
= MAX(ABS(attitude
.values
.roll
), ABS(attitude
.values
.pitch
)) / 10.0f
;
362 // horizonTiltExpertMode: 0 = leveling always active when sticks centered,
363 // 1 = leveling can be totally off when inverted
364 if (pidRuntime
.horizonTiltExpertMode
) {
365 if (pidRuntime
.horizonTransition
> 0 && pidRuntime
.horizonCutoffDegrees
> 0) {
366 // if d_level > 0 and horizonTiltEffect < 175
367 // horizonCutoffDegrees: 0 to 125 => 270 to 90 (represents where leveling goes to zero)
368 // inclinationLevelRatio (0.0 to 1.0) is smaller (less leveling)
369 // for larger inclinations; 0.0 at horizonCutoffDegrees value:
370 const float inclinationLevelRatio
= constrainf((pidRuntime
.horizonCutoffDegrees
-currentInclination
) / pidRuntime
.horizonCutoffDegrees
, 0, 1);
371 // apply configured horizon sensitivity:
372 // when stick is near center (horizonLevelStrength ~= 1.0)
373 // H_sensitivity value has little effect,
374 // when stick is deflected (horizonLevelStrength near 0.0)
375 // H_sensitivity value has more effect:
376 horizonLevelStrength
= (horizonLevelStrength
- 1) * 100 / pidRuntime
.horizonTransition
+ 1;
377 // apply inclination ratio, which may lower leveling
378 // to zero regardless of stick position:
379 horizonLevelStrength
*= inclinationLevelRatio
;
380 } else { // d_level=0 or horizon_tilt_effect>=175 means no leveling
381 horizonLevelStrength
= 0;
383 } else { // horizon_tilt_expert_mode = 0 (leveling always active when sticks centered)
385 if (pidRuntime
.horizonFactorRatio
< 1.01f
) { // if horizonTiltEffect > 0
386 // horizonFactorRatio: 1.0 to 0.0 (larger means more leveling)
387 // inclinationLevelRatio (0.0 to 1.0) is smaller (less leveling)
388 // for larger inclinations, goes to 1.0 at inclination==level:
389 const float inclinationLevelRatio
= (180 - currentInclination
) / 180 * (1.0f
- pidRuntime
.horizonFactorRatio
) + pidRuntime
.horizonFactorRatio
;
390 // apply ratio to configured horizon sensitivity:
391 sensitFact
= pidRuntime
.horizonTransition
* inclinationLevelRatio
;
392 } else { // horizonTiltEffect=0 for "old" functionality
393 sensitFact
= pidRuntime
.horizonTransition
;
396 if (sensitFact
<= 0) { // zero means no leveling
397 horizonLevelStrength
= 0;
399 // when stick is near center (horizonLevelStrength ~= 1.0)
400 // sensitFact value has little effect,
401 // when stick is deflected (horizonLevelStrength near 0.0)
402 // sensitFact value has more effect:
403 horizonLevelStrength
= ((horizonLevelStrength
- 1) * (100 / sensitFact
)) + 1;
406 return constrainf(horizonLevelStrength
, 0, 1);
409 // Use the FAST_CODE_NOINLINE directive to avoid this code from being inlined into ITCM RAM to avoid overflow.
410 // The impact is possibly slightly slower performance on F7/H7 but they have more than enough
411 // processing power that it should be a non-issue.
412 STATIC_UNIT_TESTED FAST_CODE_NOINLINE
float pidLevel(int axis
, const pidProfile_t
*pidProfile
, const rollAndPitchTrims_t
*angleTrim
, float currentPidSetpoint
) {
413 // calculate error angle and limit the angle to the max inclination
414 // rcDeflection is in range [-1.0, 1.0]
415 float angle
= pidProfile
->levelAngleLimit
* getLevelModeRcDeflection(axis
);
416 #ifdef USE_GPS_RESCUE
417 angle
+= gpsRescueAngle
[axis
] / 100; // ANGLE IS IN CENTIDEGREES
419 angle
= constrainf(angle
, -pidProfile
->levelAngleLimit
, pidProfile
->levelAngleLimit
);
420 const float errorAngle
= angle
- ((attitude
.raw
[axis
] - angleTrim
->raw
[axis
]) / 10.0f
);
421 if (FLIGHT_MODE(ANGLE_MODE
) || FLIGHT_MODE(GPS_RESCUE_MODE
)) {
422 // ANGLE mode - control is angle based
423 currentPidSetpoint
= errorAngle
* pidRuntime
.levelGain
;
425 // HORIZON mode - mix of ANGLE and ACRO modes
426 // mix in errorAngle to currentPidSetpoint to add a little auto-level feel
427 const float horizonLevelStrength
= calcHorizonLevelStrength();
428 currentPidSetpoint
= currentPidSetpoint
+ (errorAngle
* pidRuntime
.horizonGain
* horizonLevelStrength
);
430 return currentPidSetpoint
;
433 static void handleCrashRecovery(
434 const pidCrashRecovery_e crash_recovery
, const rollAndPitchTrims_t
*angleTrim
,
435 const int axis
, const timeUs_t currentTimeUs
, const float gyroRate
, float *currentPidSetpoint
, float *errorRate
)
437 if (pidRuntime
.inCrashRecoveryMode
&& cmpTimeUs(currentTimeUs
, pidRuntime
.crashDetectedAtUs
) > pidRuntime
.crashTimeDelayUs
) {
438 if (crash_recovery
== PID_CRASH_RECOVERY_BEEP
) {
441 if (axis
== FD_YAW
) {
442 *errorRate
= constrainf(*errorRate
, -pidRuntime
.crashLimitYaw
, pidRuntime
.crashLimitYaw
);
444 // on roll and pitch axes calculate currentPidSetpoint and errorRate to level the aircraft to recover from crash
445 if (sensors(SENSOR_ACC
)) {
446 // errorAngle is deviation from horizontal
447 const float errorAngle
= -(attitude
.raw
[axis
] - angleTrim
->raw
[axis
]) / 10.0f
;
448 *currentPidSetpoint
= errorAngle
* pidRuntime
.levelGain
;
449 *errorRate
= *currentPidSetpoint
- gyroRate
;
452 // reset iterm, since accumulated error before crash is now meaningless
453 // and iterm windup during crash recovery can be extreme, especially on yaw axis
454 pidData
[axis
].I
= 0.0f
;
455 if (cmpTimeUs(currentTimeUs
, pidRuntime
.crashDetectedAtUs
) > pidRuntime
.crashTimeLimitUs
456 || (getMotorMixRange() < 1.0f
457 && fabsf(gyro
.gyroADCf
[FD_ROLL
]) < pidRuntime
.crashRecoveryRate
458 && fabsf(gyro
.gyroADCf
[FD_PITCH
]) < pidRuntime
.crashRecoveryRate
459 && fabsf(gyro
.gyroADCf
[FD_YAW
]) < pidRuntime
.crashRecoveryRate
)) {
460 if (sensors(SENSOR_ACC
)) {
461 // check aircraft nearly level
462 if (ABS(attitude
.raw
[FD_ROLL
] - angleTrim
->raw
[FD_ROLL
]) < pidRuntime
.crashRecoveryAngleDeciDegrees
463 && ABS(attitude
.raw
[FD_PITCH
] - angleTrim
->raw
[FD_PITCH
]) < pidRuntime
.crashRecoveryAngleDeciDegrees
) {
464 pidRuntime
.inCrashRecoveryMode
= false;
468 pidRuntime
.inCrashRecoveryMode
= false;
475 static void detectAndSetCrashRecovery(
476 const pidCrashRecovery_e crash_recovery
, const int axis
,
477 const timeUs_t currentTimeUs
, const float delta
, const float errorRate
)
479 // if crash recovery is on and accelerometer enabled and there is no gyro overflow, then check for a crash
480 // no point in trying to recover if the crash is so severe that the gyro overflows
481 if ((crash_recovery
|| FLIGHT_MODE(GPS_RESCUE_MODE
)) && !gyroOverflowDetected()) {
482 if (ARMING_FLAG(ARMED
)) {
483 if (getMotorMixRange() >= 1.0f
&& !pidRuntime
.inCrashRecoveryMode
484 && fabsf(delta
) > pidRuntime
.crashDtermThreshold
485 && fabsf(errorRate
) > pidRuntime
.crashGyroThreshold
486 && fabsf(getSetpointRate(axis
)) < pidRuntime
.crashSetpointThreshold
) {
487 if (crash_recovery
== PID_CRASH_RECOVERY_DISARM
) {
488 setArmingDisabled(ARMING_DISABLED_CRASH_DETECTED
);
489 disarm(DISARM_REASON_CRASH_PROTECTION
);
491 pidRuntime
.inCrashRecoveryMode
= true;
492 pidRuntime
.crashDetectedAtUs
= currentTimeUs
;
495 if (pidRuntime
.inCrashRecoveryMode
&& cmpTimeUs(currentTimeUs
, pidRuntime
.crashDetectedAtUs
) < pidRuntime
.crashTimeDelayUs
&& (fabsf(errorRate
) < pidRuntime
.crashGyroThreshold
496 || fabsf(getSetpointRate(axis
)) > pidRuntime
.crashSetpointThreshold
)) {
497 pidRuntime
.inCrashRecoveryMode
= false;
500 } else if (pidRuntime
.inCrashRecoveryMode
) {
501 pidRuntime
.inCrashRecoveryMode
= false;
508 #ifdef USE_ACRO_TRAINER
510 int acroTrainerSign(float x
)
512 return x
> 0 ? 1 : -1;
515 // Acro Trainer - Manipulate the setPoint to limit axis angle while in acro mode
516 // There are three states:
517 // 1. Current angle has exceeded limit
518 // Apply correction to return to limit (similar to pidLevel)
519 // 2. Future overflow has been projected based on current angle and gyro rate
520 // Manage the setPoint to control the gyro rate as the actual angle approaches the limit (try to prevent overshoot)
521 // 3. If no potential overflow is detected, then return the original setPoint
523 // Use the FAST_CODE_NOINLINE directive to avoid this code from being inlined into ITCM RAM. We accept the
524 // performance decrease when Acro Trainer mode is active under the assumption that user is unlikely to be
525 // expecting ultimate flight performance at very high loop rates when in this mode.
526 static FAST_CODE_NOINLINE
float applyAcroTrainer(int axis
, const rollAndPitchTrims_t
*angleTrim
, float setPoint
)
528 float ret
= setPoint
;
530 if (!FLIGHT_MODE(ANGLE_MODE
) && !FLIGHT_MODE(HORIZON_MODE
) && !FLIGHT_MODE(GPS_RESCUE_MODE
)) {
531 bool resetIterm
= false;
532 float projectedAngle
= 0;
533 const int setpointSign
= acroTrainerSign(setPoint
);
534 const float currentAngle
= (attitude
.raw
[axis
] - angleTrim
->raw
[axis
]) / 10.0f
;
535 const int angleSign
= acroTrainerSign(currentAngle
);
537 if ((pidRuntime
.acroTrainerAxisState
[axis
] != 0) && (pidRuntime
.acroTrainerAxisState
[axis
] != setpointSign
)) { // stick has reversed - stop limiting
538 pidRuntime
.acroTrainerAxisState
[axis
] = 0;
541 // Limit and correct the angle when it exceeds the limit
542 if ((fabsf(currentAngle
) > pidRuntime
.acroTrainerAngleLimit
) && (pidRuntime
.acroTrainerAxisState
[axis
] == 0)) {
543 if (angleSign
== setpointSign
) {
544 pidRuntime
.acroTrainerAxisState
[axis
] = angleSign
;
549 if (pidRuntime
.acroTrainerAxisState
[axis
] != 0) {
550 ret
= constrainf(((pidRuntime
.acroTrainerAngleLimit
* angleSign
) - currentAngle
) * pidRuntime
.acroTrainerGain
, -ACRO_TRAINER_SETPOINT_LIMIT
, ACRO_TRAINER_SETPOINT_LIMIT
);
553 // Not currently over the limit so project the angle based on current angle and
554 // gyro angular rate using a sliding window based on gyro rate (faster rotation means larger window.
555 // If the projected angle exceeds the limit then apply limiting to minimize overshoot.
556 // Calculate the lookahead window by scaling proportionally with gyro rate from 0-500dps
557 float checkInterval
= constrainf(fabsf(gyro
.gyroADCf
[axis
]) / ACRO_TRAINER_LOOKAHEAD_RATE_LIMIT
, 0.0f
, 1.0f
) * pidRuntime
.acroTrainerLookaheadTime
;
558 projectedAngle
= (gyro
.gyroADCf
[axis
] * checkInterval
) + currentAngle
;
559 const int projectedAngleSign
= acroTrainerSign(projectedAngle
);
560 if ((fabsf(projectedAngle
) > pidRuntime
.acroTrainerAngleLimit
) && (projectedAngleSign
== setpointSign
)) {
561 ret
= ((pidRuntime
.acroTrainerAngleLimit
* projectedAngleSign
) - projectedAngle
) * pidRuntime
.acroTrainerGain
;
570 if (axis
== pidRuntime
.acroTrainerDebugAxis
) {
571 DEBUG_SET(DEBUG_ACRO_TRAINER
, 0, lrintf(currentAngle
* 10.0f
));
572 DEBUG_SET(DEBUG_ACRO_TRAINER
, 1, pidRuntime
.acroTrainerAxisState
[axis
]);
573 DEBUG_SET(DEBUG_ACRO_TRAINER
, 2, lrintf(ret
));
574 DEBUG_SET(DEBUG_ACRO_TRAINER
, 3, lrintf(projectedAngle
* 10.0f
));
580 #endif // USE_ACRO_TRAINER
582 static float accelerationLimit(int axis
, float currentPidSetpoint
)
584 static float previousSetpoint
[XYZ_AXIS_COUNT
];
585 const float currentVelocity
= currentPidSetpoint
- previousSetpoint
[axis
];
587 if (fabsf(currentVelocity
) > pidRuntime
.maxVelocity
[axis
]) {
588 currentPidSetpoint
= (currentVelocity
> 0) ? previousSetpoint
[axis
] + pidRuntime
.maxVelocity
[axis
] : previousSetpoint
[axis
] - pidRuntime
.maxVelocity
[axis
];
591 previousSetpoint
[axis
] = currentPidSetpoint
;
592 return currentPidSetpoint
;
595 static void rotateVector(float v
[XYZ_AXIS_COUNT
], float rotation
[XYZ_AXIS_COUNT
])
597 // rotate v around rotation vector rotation
598 // rotation in radians, all elements must be small
599 for (int i
= 0; i
< XYZ_AXIS_COUNT
; i
++) {
600 int i_1
= (i
+ 1) % 3;
601 int i_2
= (i
+ 2) % 3;
602 float newV
= v
[i_1
] + v
[i_2
] * rotation
[i
];
603 v
[i_2
] -= v
[i_1
] * rotation
[i
];
608 STATIC_UNIT_TESTED
void rotateItermAndAxisError()
610 if (pidRuntime
.itermRotation
611 #if defined(USE_ABSOLUTE_CONTROL)
612 || pidRuntime
.acGain
> 0 || debugMode
== DEBUG_AC_ERROR
615 const float gyroToAngle
= pidRuntime
.dT
* RAD
;
616 float rotationRads
[XYZ_AXIS_COUNT
];
617 for (int i
= FD_ROLL
; i
<= FD_YAW
; i
++) {
618 rotationRads
[i
] = gyro
.gyroADCf
[i
] * gyroToAngle
;
620 #if defined(USE_ABSOLUTE_CONTROL)
621 if (pidRuntime
.acGain
> 0 || debugMode
== DEBUG_AC_ERROR
) {
622 rotateVector(axisError
, rotationRads
);
625 if (pidRuntime
.itermRotation
) {
626 float v
[XYZ_AXIS_COUNT
];
627 for (int i
= 0; i
< XYZ_AXIS_COUNT
; i
++) {
630 rotateVector(v
, rotationRads
);
631 for (int i
= 0; i
< XYZ_AXIS_COUNT
; i
++) {
638 #ifdef USE_RC_SMOOTHING_FILTER
639 float FAST_CODE
applyRcSmoothingFeedforwardFilter(int axis
, float pidSetpointDelta
)
641 float ret
= pidSetpointDelta
;
642 if (axis
== pidRuntime
.rcSmoothingDebugAxis
) {
643 DEBUG_SET(DEBUG_RC_SMOOTHING
, 1, lrintf(pidSetpointDelta
* 100.0f
));
645 if (pidRuntime
.feedforwardLpfInitialized
) {
646 ret
= pt3FilterApply(&pidRuntime
.feedforwardPt3
[axis
], pidSetpointDelta
);
647 if (axis
== pidRuntime
.rcSmoothingDebugAxis
) {
648 DEBUG_SET(DEBUG_RC_SMOOTHING
, 2, lrintf(ret
* 100.0f
));
653 #endif // USE_RC_SMOOTHING_FILTER
655 #if defined(USE_ITERM_RELAX)
656 #if defined(USE_ABSOLUTE_CONTROL)
657 STATIC_UNIT_TESTED
void applyAbsoluteControl(const int axis
, const float gyroRate
, float *currentPidSetpoint
, float *itermErrorRate
)
659 if (pidRuntime
.acGain
> 0 || debugMode
== DEBUG_AC_ERROR
) {
660 const float setpointLpf
= pt1FilterApply(&pidRuntime
.acLpf
[axis
], *currentPidSetpoint
);
661 const float setpointHpf
= fabsf(*currentPidSetpoint
- setpointLpf
);
662 float acErrorRate
= 0;
663 const float gmaxac
= setpointLpf
+ 2 * setpointHpf
;
664 const float gminac
= setpointLpf
- 2 * setpointHpf
;
665 if (gyroRate
>= gminac
&& gyroRate
<= gmaxac
) {
666 const float acErrorRate1
= gmaxac
- gyroRate
;
667 const float acErrorRate2
= gminac
- gyroRate
;
668 if (acErrorRate1
* axisError
[axis
] < 0) {
669 acErrorRate
= acErrorRate1
;
671 acErrorRate
= acErrorRate2
;
673 if (fabsf(acErrorRate
* pidRuntime
.dT
) > fabsf(axisError
[axis
]) ) {
674 acErrorRate
= -axisError
[axis
] * pidRuntime
.pidFrequency
;
677 acErrorRate
= (gyroRate
> gmaxac
? gmaxac
: gminac
) - gyroRate
;
680 if (isAirmodeActivated()) {
681 axisError
[axis
] = constrainf(axisError
[axis
] + acErrorRate
* pidRuntime
.dT
,
682 -pidRuntime
.acErrorLimit
, pidRuntime
.acErrorLimit
);
683 const float acCorrection
= constrainf(axisError
[axis
] * pidRuntime
.acGain
, -pidRuntime
.acLimit
, pidRuntime
.acLimit
);
684 *currentPidSetpoint
+= acCorrection
;
685 *itermErrorRate
+= acCorrection
;
686 DEBUG_SET(DEBUG_AC_CORRECTION
, axis
, lrintf(acCorrection
* 10));
687 if (axis
== FD_ROLL
) {
688 DEBUG_SET(DEBUG_ITERM_RELAX
, 3, lrintf(acCorrection
* 10));
691 DEBUG_SET(DEBUG_AC_ERROR
, axis
, lrintf(axisError
[axis
] * 10));
696 STATIC_UNIT_TESTED
void applyItermRelax(const int axis
, const float iterm
,
697 const float gyroRate
, float *itermErrorRate
, float *currentPidSetpoint
)
699 const float setpointLpf
= pt1FilterApply(&pidRuntime
.windupLpf
[axis
], *currentPidSetpoint
);
700 const float setpointHpf
= fabsf(*currentPidSetpoint
- setpointLpf
);
702 if (pidRuntime
.itermRelax
) {
703 if (axis
< FD_YAW
|| pidRuntime
.itermRelax
== ITERM_RELAX_RPY
|| pidRuntime
.itermRelax
== ITERM_RELAX_RPY_INC
) {
704 const float itermRelaxFactor
= MAX(0, 1 - setpointHpf
/ ITERM_RELAX_SETPOINT_THRESHOLD
);
705 const bool isDecreasingI
=
706 ((iterm
> 0) && (*itermErrorRate
< 0)) || ((iterm
< 0) && (*itermErrorRate
> 0));
707 if ((pidRuntime
.itermRelax
>= ITERM_RELAX_RP_INC
) && isDecreasingI
) {
708 // Do Nothing, use the precalculed itermErrorRate
709 } else if (pidRuntime
.itermRelaxType
== ITERM_RELAX_SETPOINT
) {
710 *itermErrorRate
*= itermRelaxFactor
;
711 } else if (pidRuntime
.itermRelaxType
== ITERM_RELAX_GYRO
) {
712 *itermErrorRate
= fapplyDeadband(setpointLpf
- gyroRate
, setpointHpf
);
714 *itermErrorRate
= 0.0f
;
717 if (axis
== FD_ROLL
) {
718 DEBUG_SET(DEBUG_ITERM_RELAX
, 0, lrintf(setpointHpf
));
719 DEBUG_SET(DEBUG_ITERM_RELAX
, 1, lrintf(itermRelaxFactor
* 100.0f
));
720 DEBUG_SET(DEBUG_ITERM_RELAX
, 2, lrintf(*itermErrorRate
));
724 #if defined(USE_ABSOLUTE_CONTROL)
725 applyAbsoluteControl(axis
, gyroRate
, currentPidSetpoint
, itermErrorRate
);
731 #ifdef USE_AIRMODE_LPF
732 void pidUpdateAirmodeLpf(float currentOffset
)
734 if (pidRuntime
.airmodeThrottleOffsetLimit
== 0.0f
) {
738 float offsetHpf
= currentOffset
* 2.5f
;
739 offsetHpf
= offsetHpf
- pt1FilterApply(&pidRuntime
.airmodeThrottleLpf2
, offsetHpf
);
741 // During high frequency oscillation 2 * currentOffset averages to the offset required to avoid mirroring of the waveform
742 pt1FilterApply(&pidRuntime
.airmodeThrottleLpf1
, offsetHpf
);
743 // Bring offset up immediately so the filter only applies to the decline
744 if (currentOffset
* pidRuntime
.airmodeThrottleLpf1
.state
>= 0 && fabsf(currentOffset
) > pidRuntime
.airmodeThrottleLpf1
.state
) {
745 pidRuntime
.airmodeThrottleLpf1
.state
= currentOffset
;
747 pidRuntime
.airmodeThrottleLpf1
.state
= constrainf(pidRuntime
.airmodeThrottleLpf1
.state
, -pidRuntime
.airmodeThrottleOffsetLimit
, pidRuntime
.airmodeThrottleOffsetLimit
);
750 float pidGetAirmodeThrottleOffset()
752 return pidRuntime
.airmodeThrottleLpf1
.state
;
756 #ifdef USE_LAUNCH_CONTROL
757 #define LAUNCH_CONTROL_MAX_RATE 100.0f
758 #define LAUNCH_CONTROL_MIN_RATE 5.0f
759 #define LAUNCH_CONTROL_ANGLE_WINDOW 10.0f // The remaining angle degrees where rate dampening starts
761 // Use the FAST_CODE_NOINLINE directive to avoid this code from being inlined into ITCM RAM to avoid overflow.
762 // The impact is possibly slightly slower performance on F7/H7 but they have more than enough
763 // processing power that it should be a non-issue.
764 static FAST_CODE_NOINLINE
float applyLaunchControl(int axis
, const rollAndPitchTrims_t
*angleTrim
)
768 // Scale the rates based on stick deflection only. Fixed rates with a max of 100deg/sec
769 // reached at 50% stick deflection. This keeps the launch control positioning consistent
770 // regardless of the user's rates.
771 if ((axis
== FD_PITCH
) || (pidRuntime
.launchControlMode
!= LAUNCH_CONTROL_MODE_PITCHONLY
)) {
772 const float stickDeflection
= constrainf(getRcDeflection(axis
), -0.5f
, 0.5f
);
773 ret
= LAUNCH_CONTROL_MAX_RATE
* stickDeflection
* 2;
777 // If ACC is enabled and a limit angle is set, then try to limit forward tilt
778 // to that angle and slow down the rate as the limit is approached to reduce overshoot
779 if ((axis
== FD_PITCH
) && (pidRuntime
.launchControlAngleLimit
> 0) && (ret
> 0)) {
780 const float currentAngle
= (attitude
.raw
[axis
] - angleTrim
->raw
[axis
]) / 10.0f
;
781 if (currentAngle
>= pidRuntime
.launchControlAngleLimit
) {
784 //for the last 10 degrees scale the rate from the current input to 5 dps
785 const float angleDelta
= pidRuntime
.launchControlAngleLimit
- currentAngle
;
786 if (angleDelta
<= LAUNCH_CONTROL_ANGLE_WINDOW
) {
787 ret
= scaleRangef(angleDelta
, 0, LAUNCH_CONTROL_ANGLE_WINDOW
, LAUNCH_CONTROL_MIN_RATE
, ret
);
799 // Betaflight pid controller, which will be maintained in the future with additional features specialised for current (mini) multirotor usage.
800 // Based on 2DOF reference design (matlab)
801 void FAST_CODE
pidController(const pidProfile_t
*pidProfile
, timeUs_t currentTimeUs
)
803 static float previousGyroRateDterm
[XYZ_AXIS_COUNT
];
804 static float previousRawGyroRateDterm
[XYZ_AXIS_COUNT
];
807 static timeUs_t levelModeStartTimeUs
= 0;
808 static bool gpsRescuePreviousState
= false;
811 const float tpaFactor
= getThrottlePIDAttenuation();
814 const rollAndPitchTrims_t
*angleTrim
= &accelerometerConfig()->accelerometerTrims
;
817 UNUSED(currentTimeUs
);
821 const float tpaFactorKp
= (currentControlRateProfile
->tpaMode
== TPA_MODE_PD
) ? tpaFactor
: 1.0f
;
823 const float tpaFactorKp
= tpaFactor
;
826 #ifdef USE_YAW_SPIN_RECOVERY
827 const bool yawSpinActive
= gyroYawSpinDetected();
830 const bool launchControlActive
= isLaunchControlActive();
833 const bool gpsRescueIsActive
= FLIGHT_MODE(GPS_RESCUE_MODE
);
834 levelMode_e levelMode
;
835 if (FLIGHT_MODE(ANGLE_MODE
) || FLIGHT_MODE(HORIZON_MODE
) || gpsRescueIsActive
) {
836 if (pidRuntime
.levelRaceMode
&& !gpsRescueIsActive
) {
837 levelMode
= LEVEL_MODE_R
;
839 levelMode
= LEVEL_MODE_RP
;
842 levelMode
= LEVEL_MODE_OFF
;
845 // Keep track of when we entered a self-level mode so that we can
846 // add a guard time before crash recovery can activate.
847 // Also reset the guard time whenever GPS Rescue is activated.
849 if ((levelModeStartTimeUs
== 0) || (gpsRescueIsActive
&& !gpsRescuePreviousState
)) {
850 levelModeStartTimeUs
= currentTimeUs
;
853 levelModeStartTimeUs
= 0;
855 gpsRescuePreviousState
= gpsRescueIsActive
;
858 // Dynamic i component,
859 if ((pidRuntime
.antiGravityMode
== ANTI_GRAVITY_SMOOTH
) && pidRuntime
.antiGravityEnabled
) {
860 // traditional itermAccelerator factor for iTerm
861 pidRuntime
.itermAccelerator
= pidRuntime
.antiGravityThrottleHpf
* 0.01f
* pidRuntime
.itermAcceleratorGain
;
862 DEBUG_SET(DEBUG_ANTI_GRAVITY
, 1, lrintf(pidRuntime
.itermAccelerator
* 1000));
863 // users AG Gain changes P boost
864 pidRuntime
.antiGravityPBoost
*= pidRuntime
.itermAcceleratorGain
;
865 // add some percentage of that slower, longer acting P boost factor to prolong AG effect on iTerm
866 pidRuntime
.itermAccelerator
+= pidRuntime
.antiGravityPBoost
* 0.05f
;
867 // set the final P boost amount
868 pidRuntime
.antiGravityPBoost
*= 0.02f
;
870 pidRuntime
.antiGravityPBoost
= 0.0f
;
872 DEBUG_SET(DEBUG_ANTI_GRAVITY
, 0, lrintf(pidRuntime
.itermAccelerator
* 1000));
874 float agGain
= pidRuntime
.dT
* pidRuntime
.itermAccelerator
* AG_KI
;
876 // gradually scale back integration when above windup point
877 float dynCi
= pidRuntime
.dT
;
878 if (pidRuntime
.itermWindupPointInv
> 1.0f
) {
879 dynCi
*= constrainf((1.0f
- getMotorMixRange()) * pidRuntime
.itermWindupPointInv
, 0.0f
, 1.0f
);
882 // Precalculate gyro deta for D-term here, this allows loop unrolling
883 float gyroRateDterm
[XYZ_AXIS_COUNT
];
884 for (int axis
= FD_ROLL
; axis
<= FD_YAW
; ++axis
) {
885 gyroRateDterm
[axis
] = gyro
.gyroADCf
[axis
];
886 // -----calculate raw, unfiltered D component
888 // Divide rate change by dT to get differential (ie dr/dt).
889 // dT is fixed and calculated from the target PID loop time
890 // This is done to avoid DTerm spikes that occur with dynamically
891 // calculated deltaT whenever another task causes the PID
892 // loop execution to be delayed.
894 - (gyroRateDterm
[axis
] - previousRawGyroRateDterm
[axis
]) * pidRuntime
.pidFrequency
/ D_LPF_RAW_SCALE
;
895 previousRawGyroRateDterm
[axis
] = gyroRateDterm
[axis
];
897 // Log the unfiltered D
898 if (axis
== FD_ROLL
) {
899 DEBUG_SET(DEBUG_D_LPF
, 0, lrintf(delta
));
900 } else if (axis
== FD_PITCH
) {
901 DEBUG_SET(DEBUG_D_LPF
, 1, lrintf(delta
));
904 gyroRateDterm
[axis
] = pidRuntime
.dtermNotchApplyFn((filter_t
*) &pidRuntime
.dtermNotch
[axis
], gyroRateDterm
[axis
]);
905 gyroRateDterm
[axis
] = pidRuntime
.dtermLowpassApplyFn((filter_t
*) &pidRuntime
.dtermLowpass
[axis
], gyroRateDterm
[axis
]);
906 gyroRateDterm
[axis
] = pidRuntime
.dtermLowpass2ApplyFn((filter_t
*) &pidRuntime
.dtermLowpass2
[axis
], gyroRateDterm
[axis
]);
909 rotateItermAndAxisError();
911 #ifdef USE_RPM_FILTER
915 #ifdef USE_FEEDFORWARD
916 bool newRcFrame
= false;
917 if (getShouldUpdateFeedforward()) {
922 // ----------PID controller----------
923 for (int axis
= FD_ROLL
; axis
<= FD_YAW
; ++axis
) {
925 float currentPidSetpoint
= getSetpointRate(axis
);
926 if (pidRuntime
.maxVelocity
[axis
]) {
927 currentPidSetpoint
= accelerationLimit(axis
, currentPidSetpoint
);
929 // Yaw control is GYRO based, direct sticks control is applied to rate PID
930 // When Race Mode is active PITCH control is also GYRO based in level or horizon mode
937 if (axis
== FD_PITCH
) {
943 if (axis
== FD_YAW
) {
946 currentPidSetpoint
= pidLevel(axis
, pidProfile
, angleTrim
, currentPidSetpoint
);
950 #ifdef USE_ACRO_TRAINER
951 if ((axis
!= FD_YAW
) && pidRuntime
.acroTrainerActive
&& !pidRuntime
.inCrashRecoveryMode
&& !launchControlActive
) {
952 currentPidSetpoint
= applyAcroTrainer(axis
, angleTrim
, currentPidSetpoint
);
954 #endif // USE_ACRO_TRAINER
956 #ifdef USE_LAUNCH_CONTROL
957 if (launchControlActive
) {
959 currentPidSetpoint
= applyLaunchControl(axis
, angleTrim
);
961 currentPidSetpoint
= applyLaunchControl(axis
, NULL
);
966 // Handle yaw spin recovery - zero the setpoint on yaw to aid in recovery
967 // It's not necessary to zero the set points for R/P because the PIDs will be zeroed below
968 #ifdef USE_YAW_SPIN_RECOVERY
969 if ((axis
== FD_YAW
) && yawSpinActive
) {
970 currentPidSetpoint
= 0.0f
;
972 #endif // USE_YAW_SPIN_RECOVERY
974 // -----calculate error rate
975 const float gyroRate
= gyro
.gyroADCf
[axis
]; // Process variable from gyro output in deg/sec
976 float errorRate
= currentPidSetpoint
- gyroRate
; // r - y
979 pidProfile
->crash_recovery
, angleTrim
, axis
, currentTimeUs
, gyroRate
,
980 ¤tPidSetpoint
, &errorRate
);
983 const float previousIterm
= pidData
[axis
].I
;
984 float itermErrorRate
= errorRate
;
985 #ifdef USE_ABSOLUTE_CONTROL
986 float uncorrectedSetpoint
= currentPidSetpoint
;
989 #if defined(USE_ITERM_RELAX)
990 if (!launchControlActive
&& !pidRuntime
.inCrashRecoveryMode
) {
991 applyItermRelax(axis
, previousIterm
, gyroRate
, &itermErrorRate
, ¤tPidSetpoint
);
992 errorRate
= currentPidSetpoint
- gyroRate
;
995 #ifdef USE_ABSOLUTE_CONTROL
996 float setpointCorrection
= currentPidSetpoint
- uncorrectedSetpoint
;
999 // --------low-level gyro-based PID based on 2DOF PID controller. ----------
1000 // 2-DOF PID controller with optional filter on derivative term.
1001 // b = 1 and only c (feedforward weight) can be tuned (amount derivative on measurement or error).
1003 // -----calculate P component
1004 pidData
[axis
].P
= pidRuntime
.pidCoefficient
[axis
].Kp
* errorRate
* tpaFactorKp
;
1005 if (axis
== FD_YAW
) {
1006 pidData
[axis
].P
= pidRuntime
.ptermYawLowpassApplyFn((filter_t
*) &pidRuntime
.ptermYawLowpass
, pidData
[axis
].P
);
1009 // -----calculate I component
1012 #ifdef USE_LAUNCH_CONTROL
1013 // if launch control is active override the iterm gains and apply iterm windup protection to all axes
1014 if (launchControlActive
) {
1015 Ki
= pidRuntime
.launchControlKi
;
1020 Ki
= pidRuntime
.pidCoefficient
[axis
].Ki
;
1021 axisDynCi
= (axis
== FD_YAW
) ? dynCi
: pidRuntime
.dT
; // only apply windup protection to yaw
1024 pidData
[axis
].I
= constrainf(previousIterm
+ (Ki
* axisDynCi
+ agGain
) * itermErrorRate
, -pidRuntime
.itermLimit
, pidRuntime
.itermLimit
);
1026 // -----calculate pidSetpointDelta
1027 float pidSetpointDelta
= 0;
1028 #ifdef USE_FEEDFORWARD
1029 pidSetpointDelta
= feedforwardApply(axis
, newRcFrame
, pidRuntime
.feedforwardAveraging
);
1031 pidRuntime
.previousPidSetpoint
[axis
] = currentPidSetpoint
;
1033 // -----calculate D component
1034 // disable D if launch control is active
1035 if ((pidRuntime
.pidCoefficient
[axis
].Kd
> 0) && !launchControlActive
) {
1037 // Divide rate change by dT to get differential (ie dr/dt).
1038 // dT is fixed and calculated from the target PID loop time
1039 // This is done to avoid DTerm spikes that occur with dynamically
1040 // calculated deltaT whenever another task causes the PID
1041 // loop execution to be delayed.
1043 - (gyroRateDterm
[axis
] - previousGyroRateDterm
[axis
]) * pidRuntime
.pidFrequency
;
1044 float preTpaData
= pidRuntime
.pidCoefficient
[axis
].Kd
* delta
;
1046 #if defined(USE_ACC)
1047 if (cmpTimeUs(currentTimeUs
, levelModeStartTimeUs
) > CRASH_RECOVERY_DETECTION_DELAY_US
) {
1048 detectAndSetCrashRecovery(pidProfile
->crash_recovery
, axis
, currentTimeUs
, delta
, errorRate
);
1052 #if defined(USE_D_MIN)
1053 float dMinFactor
= 1.0f
;
1054 if (pidRuntime
.dMinPercent
[axis
] > 0) {
1055 float dMinGyroFactor
= biquadFilterApply(&pidRuntime
.dMinRange
[axis
], delta
);
1056 dMinGyroFactor
= fabsf(dMinGyroFactor
) * pidRuntime
.dMinGyroGain
;
1057 const float dMinSetpointFactor
= (fabsf(pidSetpointDelta
)) * pidRuntime
.dMinSetpointGain
;
1058 dMinFactor
= MAX(dMinGyroFactor
, dMinSetpointFactor
);
1059 dMinFactor
= pidRuntime
.dMinPercent
[axis
] + (1.0f
- pidRuntime
.dMinPercent
[axis
]) * dMinFactor
;
1060 dMinFactor
= pt1FilterApply(&pidRuntime
.dMinLowpass
[axis
], dMinFactor
);
1061 dMinFactor
= MIN(dMinFactor
, 1.0f
);
1062 if (axis
== FD_ROLL
) {
1063 DEBUG_SET(DEBUG_D_MIN
, 0, lrintf(dMinGyroFactor
* 100));
1064 DEBUG_SET(DEBUG_D_MIN
, 1, lrintf(dMinSetpointFactor
* 100));
1065 DEBUG_SET(DEBUG_D_MIN
, 2, lrintf(pidRuntime
.pidCoefficient
[axis
].Kd
* dMinFactor
* 10 / DTERM_SCALE
));
1066 } else if (axis
== FD_PITCH
) {
1067 DEBUG_SET(DEBUG_D_MIN
, 3, lrintf(pidRuntime
.pidCoefficient
[axis
].Kd
* dMinFactor
* 10 / DTERM_SCALE
));
1071 // Apply the dMinFactor
1072 preTpaData
*= dMinFactor
;
1074 pidData
[axis
].D
= preTpaData
* tpaFactor
;
1076 // Log the value of D pre application of TPA
1077 preTpaData
*= D_LPF_FILT_SCALE
;
1079 if (axis
== FD_ROLL
) {
1080 DEBUG_SET(DEBUG_D_LPF
, 2, lrintf(preTpaData
));
1081 } else if (axis
== FD_PITCH
) {
1082 DEBUG_SET(DEBUG_D_LPF
, 3, lrintf(preTpaData
));
1085 pidData
[axis
].D
= 0;
1087 if (axis
== FD_ROLL
) {
1088 DEBUG_SET(DEBUG_D_LPF
, 2, 0);
1089 } else if (axis
== FD_PITCH
) {
1090 DEBUG_SET(DEBUG_D_LPF
, 3, 0);
1094 previousGyroRateDterm
[axis
] = gyroRateDterm
[axis
];
1096 // -----calculate feedforward component
1097 #ifdef USE_ABSOLUTE_CONTROL
1098 // include abs control correction in feedforward
1099 pidSetpointDelta
+= setpointCorrection
- pidRuntime
.oldSetpointCorrection
[axis
];
1100 pidRuntime
.oldSetpointCorrection
[axis
] = setpointCorrection
;
1103 // Only enable feedforward for rate mode and if launch control is inactive
1104 const float feedforwardGain
= (flightModeFlags
|| launchControlActive
) ? 0.0f
: pidRuntime
.pidCoefficient
[axis
].Kf
;
1105 if (feedforwardGain
> 0) {
1106 // no transition if feedforwardTransition == 0
1107 float transition
= pidRuntime
.feedforwardTransition
> 0 ? MIN(1.f
, getRcDeflectionAbs(axis
) * pidRuntime
.feedforwardTransition
) : 1;
1108 float feedForward
= feedforwardGain
* transition
* pidSetpointDelta
* pidRuntime
.pidFrequency
;
1110 #ifdef USE_FEEDFORWARD
1111 pidData
[axis
].F
= shouldApplyFeedforwardLimits(axis
) ?
1112 applyFeedforwardLimit(axis
, feedForward
, pidRuntime
.pidCoefficient
[axis
].Kp
, currentPidSetpoint
) : feedForward
;
1114 pidData
[axis
].F
= feedForward
;
1116 #ifdef USE_RC_SMOOTHING_FILTER
1117 pidData
[axis
].F
= applyRcSmoothingFeedforwardFilter(axis
, pidData
[axis
].F
);
1118 #endif // USE_RC_SMOOTHING_FILTER
1120 pidData
[axis
].F
= 0;
1123 #ifdef USE_YAW_SPIN_RECOVERY
1124 if (yawSpinActive
) {
1125 pidData
[axis
].I
= 0; // in yaw spin always disable I
1126 if (axis
<= FD_PITCH
) {
1127 // zero PIDs on pitch and roll leaving yaw P to correct spin
1128 pidData
[axis
].P
= 0;
1129 pidData
[axis
].D
= 0;
1130 pidData
[axis
].F
= 0;
1133 #endif // USE_YAW_SPIN_RECOVERY
1135 #ifdef USE_LAUNCH_CONTROL
1136 // Disable P/I appropriately based on the launch control mode
1137 if (launchControlActive
) {
1138 // if not using FULL mode then disable I accumulation on yaw as
1139 // yaw has a tendency to windup. Otherwise limit yaw iterm accumulation.
1140 const int launchControlYawItermLimit
= (pidRuntime
.launchControlMode
== LAUNCH_CONTROL_MODE_FULL
) ? LAUNCH_CONTROL_YAW_ITERM_LIMIT
: 0;
1141 pidData
[FD_YAW
].I
= constrainf(pidData
[FD_YAW
].I
, -launchControlYawItermLimit
, launchControlYawItermLimit
);
1143 // for pitch-only mode we disable everything except pitch P/I
1144 if (pidRuntime
.launchControlMode
== LAUNCH_CONTROL_MODE_PITCHONLY
) {
1145 pidData
[FD_ROLL
].P
= 0;
1146 pidData
[FD_ROLL
].I
= 0;
1147 pidData
[FD_YAW
].P
= 0;
1148 // don't let I go negative (pitch backwards) as front motors are limited in the mixer
1149 pidData
[FD_PITCH
].I
= MAX(0.0f
, pidData
[FD_PITCH
].I
);
1153 // calculating the PID sum
1155 // P boost at the end of throttle chop
1156 // attenuate effect if turning more than 50 deg/s, half at 100 deg/s
1157 float agBoostAttenuator
= fabsf(currentPidSetpoint
) / 50.0f
;
1158 agBoostAttenuator
= MAX(agBoostAttenuator
, 1.0f
);
1159 const float agBoost
= 1.0f
+ (pidRuntime
.antiGravityPBoost
/ agBoostAttenuator
);
1160 if (axis
!= FD_YAW
) {
1161 pidData
[axis
].P
*= agBoost
;
1162 DEBUG_SET(DEBUG_ANTI_GRAVITY
, axis
+ 2, lrintf(agBoost
* 1000));
1165 const float pidSum
= pidData
[axis
].P
+ pidData
[axis
].I
+ pidData
[axis
].D
+ pidData
[axis
].F
;
1166 #ifdef USE_INTEGRATED_YAW_CONTROL
1167 if (axis
== FD_YAW
&& pidRuntime
.useIntegratedYaw
) {
1168 pidData
[axis
].Sum
+= pidSum
* pidRuntime
.dT
* 100.0f
;
1169 pidData
[axis
].Sum
-= pidData
[axis
].Sum
* pidRuntime
.integratedYawRelax
/ 100000.0f
* pidRuntime
.dT
/ 0.000125f
;
1173 pidData
[axis
].Sum
= pidSum
;
1177 // Disable PID control if at zero throttle or if gyro overflow detected
1178 // This may look very innefficient, but it is done on purpose to always show real CPU usage as in flight
1179 if (!pidRuntime
.pidStabilisationEnabled
|| gyroOverflowDetected()) {
1180 for (int axis
= FD_ROLL
; axis
<= FD_YAW
; ++axis
) {
1181 pidData
[axis
].P
= 0;
1182 pidData
[axis
].I
= 0;
1183 pidData
[axis
].D
= 0;
1184 pidData
[axis
].F
= 0;
1186 pidData
[axis
].Sum
= 0;
1188 } else if (pidRuntime
.zeroThrottleItermReset
) {
1193 bool crashRecoveryModeActive(void)
1195 return pidRuntime
.inCrashRecoveryMode
;
1198 #ifdef USE_ACRO_TRAINER
1199 void pidSetAcroTrainerState(bool newState
)
1201 if (pidRuntime
.acroTrainerActive
!= newState
) {
1203 pidAcroTrainerInit();
1205 pidRuntime
.acroTrainerActive
= newState
;
1208 #endif // USE_ACRO_TRAINER
1210 void pidSetAntiGravityState(bool newState
)
1212 if (newState
!= pidRuntime
.antiGravityEnabled
) {
1213 // reset the accelerator on state changes
1214 pidRuntime
.itermAccelerator
= 0.0f
;
1216 pidRuntime
.antiGravityEnabled
= newState
;
1219 bool pidAntiGravityEnabled(void)
1221 return pidRuntime
.antiGravityEnabled
;
1225 void dynLpfDTermUpdate(float throttle
)
1227 unsigned int cutoffFreq
;
1228 if (pidRuntime
.dynLpfFilter
!= DYN_LPF_NONE
) {
1229 if (pidRuntime
.dynLpfCurveExpo
> 0) {
1230 cutoffFreq
= dynLpfCutoffFreq(throttle
, pidRuntime
.dynLpfMin
, pidRuntime
.dynLpfMax
, pidRuntime
.dynLpfCurveExpo
);
1232 cutoffFreq
= fmax(dynThrottle(throttle
) * pidRuntime
.dynLpfMax
, pidRuntime
.dynLpfMin
);
1234 switch (pidRuntime
.dynLpfFilter
) {
1236 for (int axis
= 0; axis
< XYZ_AXIS_COUNT
; axis
++) {
1237 pt1FilterUpdateCutoff(&pidRuntime
.dtermLowpass
[axis
].pt1Filter
, pt1FilterGain(cutoffFreq
, pidRuntime
.dT
));
1240 case DYN_LPF_BIQUAD
:
1241 for (int axis
= 0; axis
< XYZ_AXIS_COUNT
; axis
++) {
1242 biquadFilterUpdateLPF(&pidRuntime
.dtermLowpass
[axis
].biquadFilter
, cutoffFreq
, targetPidLooptime
);
1246 for (int axis
= 0; axis
< XYZ_AXIS_COUNT
; axis
++) {
1247 pt2FilterUpdateCutoff(&pidRuntime
.dtermLowpass
[axis
].pt2Filter
, pt2FilterGain(cutoffFreq
, pidRuntime
.dT
));
1251 for (int axis
= 0; axis
< XYZ_AXIS_COUNT
; axis
++) {
1252 pt3FilterUpdateCutoff(&pidRuntime
.dtermLowpass
[axis
].pt3Filter
, pt3FilterGain(cutoffFreq
, pidRuntime
.dT
));
1260 float dynLpfCutoffFreq(float throttle
, uint16_t dynLpfMin
, uint16_t dynLpfMax
, uint8_t expo
) {
1261 const float expof
= expo
/ 10.0f
;
1263 curve
= throttle
* (1 - throttle
) * expof
+ throttle
;
1264 return (dynLpfMax
- dynLpfMin
) * curve
+ dynLpfMin
;
1267 void pidSetItermReset(bool enabled
)
1269 pidRuntime
.zeroThrottleItermReset
= enabled
;
1272 float pidGetPreviousSetpoint(int axis
)
1274 return pidRuntime
.previousPidSetpoint
[axis
];
1279 return pidRuntime
.dT
;
1282 float pidGetPidFrequency()
1284 return pidRuntime
.pidFrequency
;