use Throttle Setpoint, not rcDATA(throttle), for TPA
[betaflight.git] / src / main / flight / pid.c
blob6722dab7dfeee74a8bb789142981f7a09bcc59de
1 /*
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)
8 * any later version.
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/>.
21 #include <stdbool.h>
22 #include <stdint.h>
23 #include <string.h>
24 #include <math.h>
26 #include "platform.h"
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"
42 #include "fc/core.h"
43 #include "fc/rc.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"
53 #include "io/gps.h"
55 #include "pg/pg.h"
56 #include "pg/pg_ids.h"
58 #include "sensors/acceleration.h"
59 #include "sensors/battery.h"
60 #include "sensors/gyro.h"
62 #include "pid.h"
64 typedef enum {
65 LEVEL_MODE_OFF = 0,
66 LEVEL_MODE_R,
67 LEVEL_MODE_RP,
68 } levelMode_e;
70 const char pidNames[] =
71 "ROLL;"
72 "PITCH;"
73 "YAW;"
74 "LEVEL;"
75 "MAG;";
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];
83 #endif
85 #if defined(USE_THROTTLE_BOOST)
86 FAST_DATA_ZERO_INIT float throttleBoost;
87 pt1Filter_t throttleLpf;
88 #endif
90 PG_REGISTER_WITH_RESET_TEMPLATE(pidConfig_t, pidConfig, PG_PID_CONFIG, 3);
92 #if defined(STM32F1)
93 #define PID_PROCESS_DENOM_DEFAULT 8
94 #elif defined(STM32F3)
95 #define PID_PROCESS_DENOM_DEFAULT 4
96 #elif defined(STM32F411xE) || defined(STM32G4) //G4 sometimes cpu overflow when PID rate set to higher than 4k
97 #define PID_PROCESS_DENOM_DEFAULT 2
98 #else
99 #define PID_PROCESS_DENOM_DEFAULT 1
100 #endif
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
109 #else
110 PG_RESET_TEMPLATE(pidConfig_t, pidConfig,
111 .pid_process_denom = PID_PROCESS_DENOM_DEFAULT
113 #endif
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, 3);
126 void resetPidProfile(pidProfile_t *pidProfile)
128 RESET_CONFIG(pidProfile_t, pidProfile,
129 .pid = {
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,
138 .yaw_lowpass_hz = 100,
139 .dterm_notch_hz = 0,
140 .dterm_notch_cutoff = 0,
141 .itermWindupPointPercent = 85,
142 .pidAtMinThrottle = PID_STABILISATION_ON,
143 .levelAngleLimit = 55,
144 .feedforward_transition = 0,
145 .yawRateAccelLimit = 0,
146 .rateAccelLimit = 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,
160 .itermLimit = 400,
161 .throttle_boost = 5,
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_lpf1_static_hz = DTERM_LPF1_DYN_MIN_HZ_DEFAULT,
177 // NOTE: dynamic lpf is enabled by default so this setting is actually
178 // overridden and the static lowpass 1 is disabled. We can't set this
179 // value to 0 otherwise Configurator versions 10.4 and earlier will also
180 // reset the lowpass filter type to PT1 overriding the desired BIQUAD setting.
181 .dterm_lpf2_static_hz = DTERM_LPF2_HZ_DEFAULT, // second Dterm LPF ON by default
182 .dterm_lpf1_type = FILTER_PT1,
183 .dterm_lpf2_type = FILTER_PT1,
184 .dterm_lpf1_dyn_min_hz = DTERM_LPF1_DYN_MIN_HZ_DEFAULT,
185 .dterm_lpf1_dyn_max_hz = DTERM_LPF1_DYN_MAX_HZ_DEFAULT,
186 .launchControlMode = LAUNCH_CONTROL_MODE_NORMAL,
187 .launchControlThrottlePercent = 20,
188 .launchControlAngleLimit = 0,
189 .launchControlGain = 40,
190 .launchControlAllowTriggerReset = true,
191 .use_integrated_yaw = false,
192 .integrated_yaw_relax = 200,
193 .thrustLinearization = 0,
194 .d_min = D_MIN_DEFAULT,
195 .d_min_gain = 37,
196 .d_min_advance = 20,
197 .motor_output_limit = 100,
198 .auto_profile_cell_count = AUTO_PROFILE_CELL_COUNT_STAY,
199 .transient_throttle_limit = 0,
200 .profileName = { 0 },
201 .dyn_idle_min_rpm = 0,
202 .dyn_idle_p_gain = 50,
203 .dyn_idle_i_gain = 50,
204 .dyn_idle_d_gain = 50,
205 .dyn_idle_max_increase = 150,
206 .feedforward_averaging = FEEDFORWARD_AVERAGING_OFF,
207 .feedforward_max_rate_limit = 90,
208 .feedforward_smooth_factor = 25,
209 .feedforward_jitter_factor = 7,
210 .feedforward_boost = 15,
211 .dterm_lpf1_dyn_expo = 5,
212 .level_race_mode = false,
213 .vbat_sag_compensation = 0,
214 .simplified_pids_mode = PID_SIMPLIFIED_TUNING_RPY,
215 .simplified_master_multiplier = SIMPLIFIED_TUNING_DEFAULT,
216 .simplified_roll_pitch_ratio = SIMPLIFIED_TUNING_DEFAULT,
217 .simplified_i_gain = SIMPLIFIED_TUNING_DEFAULT,
218 .simplified_d_gain = SIMPLIFIED_TUNING_D_DEFAULT,
219 .simplified_pi_gain = SIMPLIFIED_TUNING_DEFAULT,
220 .simplified_dmin_ratio = SIMPLIFIED_TUNING_D_DEFAULT,
221 .simplified_feedforward_gain = SIMPLIFIED_TUNING_DEFAULT,
222 .simplified_pitch_pi_gain = SIMPLIFIED_TUNING_DEFAULT,
223 .simplified_dterm_filter = true,
224 .simplified_dterm_filter_multiplier = SIMPLIFIED_TUNING_DEFAULT,
227 #ifndef USE_D_MIN
228 pidProfile->pid[PID_ROLL].D = 30;
229 pidProfile->pid[PID_PITCH].D = 32;
230 #endif
233 void pgResetFn_pidProfiles(pidProfile_t *pidProfiles)
235 for (int i = 0; i < PID_PROFILE_COUNT; i++) {
236 resetPidProfile(&pidProfiles[i]);
240 // Scale factors to make best use of range with D_LPF debugging, aiming for max +/-16K as debug values are 16 bit
241 #define D_LPF_RAW_SCALE 25
242 #define D_LPF_FILT_SCALE 22
245 void pidSetItermAccelerator(float newItermAccelerator)
247 pidRuntime.itermAccelerator = newItermAccelerator;
250 bool pidOsdAntiGravityActive(void)
252 return (pidRuntime.itermAccelerator > pidRuntime.antiGravityOsdCutoff);
255 void pidStabilisationState(pidStabilisationState_e pidControllerState)
257 pidRuntime.pidStabilisationEnabled = (pidControllerState == PID_STABILISATION_ON) ? true : false;
260 const angle_index_t rcAliasToAngleIndexMap[] = { AI_ROLL, AI_PITCH };
262 #ifdef USE_FEEDFORWARD
263 float pidGetFeedforwardTransitionFactor()
265 return pidRuntime.feedforwardTransitionFactor;
268 float pidGetFeedforwardSmoothFactor()
270 return pidRuntime.feedforwardSmoothFactor;
273 float pidGetFeedforwardJitterFactor()
275 return pidRuntime.feedforwardJitterFactor;
278 float pidGetFeedforwardBoostFactor()
280 return pidRuntime.feedforwardBoostFactor;
282 #endif
284 void pidResetIterm(void)
286 for (int axis = 0; axis < 3; axis++) {
287 pidData[axis].I = 0.0f;
288 #if defined(USE_ABSOLUTE_CONTROL)
289 axisError[axis] = 0.0f;
290 #endif
294 void pidUpdateTpaFactor(float throttle)
296 const float tpaBreakpoint = (currentControlRateProfile->tpa_breakpoint - 1000) / 1000.0f;
297 float tpaRate = currentControlRateProfile->tpa_rate / 100.0f;
298 if (throttle > tpaBreakpoint) {
299 if (throttle < 1.0f) {
300 tpaRate *= (throttle - tpaBreakpoint) / (1.0f - tpaBreakpoint);
302 } else {
303 tpaRate = 0.0f;
305 pidRuntime.tpaFactor = 1.0f - tpaRate;
308 void pidUpdateAntiGravityThrottleFilter(float throttle)
310 if (pidRuntime.antiGravityMode == ANTI_GRAVITY_SMOOTH) {
311 // calculate a boost factor for P in the same way as for I when throttle changes quickly
312 const float antiGravityThrottleLpf = pt1FilterApply(&pidRuntime.antiGravityThrottleLpf, throttle);
313 // focus P boost on low throttle range only
314 if (throttle < 0.5f) {
315 pidRuntime.antiGravityPBoost = 0.5f - throttle;
316 } else {
317 pidRuntime.antiGravityPBoost = 0.0f;
319 // use lowpass to identify start of a throttle up, use this to reduce boost at start by half
320 if (antiGravityThrottleLpf < throttle) {
321 pidRuntime.antiGravityPBoost *= 0.5f;
323 // high-passed throttle focuses boost on faster throttle changes
324 pidRuntime.antiGravityThrottleHpf = fabsf(throttle - antiGravityThrottleLpf);
325 pidRuntime.antiGravityPBoost = pidRuntime.antiGravityPBoost * pidRuntime.antiGravityThrottleHpf;
326 // smooth the P boost at 3hz to remove the jagged edges and prolong the effect after throttle stops
327 pidRuntime.antiGravityPBoost = pt1FilterApply(&pidRuntime.antiGravitySmoothLpf, pidRuntime.antiGravityPBoost);
331 #ifdef USE_ACRO_TRAINER
332 void pidAcroTrainerInit(void)
334 pidRuntime.acroTrainerAxisState[FD_ROLL] = 0;
335 pidRuntime.acroTrainerAxisState[FD_PITCH] = 0;
337 #endif // USE_ACRO_TRAINER
339 #ifdef USE_THRUST_LINEARIZATION
340 float pidCompensateThrustLinearization(float throttle)
342 if (pidRuntime.thrustLinearization != 0.0f) {
343 // for whoops where a lot of TL is needed, allow more throttle boost
344 const float throttleReversed = (1.0f - throttle);
345 throttle /= 1.0f + pidRuntime.throttleCompensateAmount * powf(throttleReversed, 2);
347 return throttle;
350 float pidApplyThrustLinearization(float motorOutput)
352 if (pidRuntime.thrustLinearization != 0.0f) {
353 if (motorOutput > 0.0f) {
354 const float motorOutputReversed = (1.0f - motorOutput);
355 motorOutput *= 1.0f + powf(motorOutputReversed, 2) * pidRuntime.thrustLinearization;
358 return motorOutput;
360 #endif
362 #if defined(USE_ACC)
363 // calculate the stick deflection while applying level mode expo
364 static float getLevelModeRcDeflection(uint8_t axis)
366 const float stickDeflection = getRcDeflection(axis);
367 if (axis < FD_YAW) {
368 const float expof = currentControlRateProfile->levelExpo[axis] / 100.0f;
369 return power3(stickDeflection) * expof + stickDeflection * (1 - expof);
370 } else {
371 return stickDeflection;
375 // calculates strength of horizon leveling; 0 = none, 1.0 = most leveling
376 STATIC_UNIT_TESTED float calcHorizonLevelStrength(void)
378 // start with 1.0 at center stick, 0.0 at max stick deflection:
379 float horizonLevelStrength = 1.0f - MAX(fabsf(getLevelModeRcDeflection(FD_ROLL)), fabsf(getLevelModeRcDeflection(FD_PITCH)));
381 // 0 at level, 90 at vertical, 180 at inverted (degrees):
382 const float currentInclination = MAX(ABS(attitude.values.roll), ABS(attitude.values.pitch)) / 10.0f;
384 // horizonTiltExpertMode: 0 = leveling always active when sticks centered,
385 // 1 = leveling can be totally off when inverted
386 if (pidRuntime.horizonTiltExpertMode) {
387 if (pidRuntime.horizonTransition > 0 && pidRuntime.horizonCutoffDegrees > 0) {
388 // if d_level > 0 and horizonTiltEffect < 175
389 // horizonCutoffDegrees: 0 to 125 => 270 to 90 (represents where leveling goes to zero)
390 // inclinationLevelRatio (0.0 to 1.0) is smaller (less leveling)
391 // for larger inclinations; 0.0 at horizonCutoffDegrees value:
392 const float inclinationLevelRatio = constrainf((pidRuntime.horizonCutoffDegrees-currentInclination) / pidRuntime.horizonCutoffDegrees, 0, 1);
393 // apply configured horizon sensitivity:
394 // when stick is near center (horizonLevelStrength ~= 1.0)
395 // H_sensitivity value has little effect,
396 // when stick is deflected (horizonLevelStrength near 0.0)
397 // H_sensitivity value has more effect:
398 horizonLevelStrength = (horizonLevelStrength - 1) * 100 / pidRuntime.horizonTransition + 1;
399 // apply inclination ratio, which may lower leveling
400 // to zero regardless of stick position:
401 horizonLevelStrength *= inclinationLevelRatio;
402 } else { // d_level=0 or horizon_tilt_effect>=175 means no leveling
403 horizonLevelStrength = 0;
405 } else { // horizon_tilt_expert_mode = 0 (leveling always active when sticks centered)
406 float sensitFact;
407 if (pidRuntime.horizonFactorRatio < 1.0f) { // if horizonTiltEffect > 0
408 // horizonFactorRatio: 1.0 to 0.0 (larger means more leveling)
409 // inclinationLevelRatio (0.0 to 1.0) is smaller (less leveling)
410 // for larger inclinations, goes to 1.0 at inclination==level:
411 const float inclinationLevelRatio = (180 - currentInclination) / 180 * (1.0f - pidRuntime.horizonFactorRatio) + pidRuntime.horizonFactorRatio;
412 // apply ratio to configured horizon sensitivity:
413 sensitFact = pidRuntime.horizonTransition * inclinationLevelRatio;
414 } else { // horizonTiltEffect=0 for "old" functionality
415 sensitFact = pidRuntime.horizonTransition;
418 if (sensitFact <= 0) { // zero means no leveling
419 horizonLevelStrength = 0;
420 } else {
421 // when stick is near center (horizonLevelStrength ~= 1.0)
422 // sensitFact value has little effect,
423 // when stick is deflected (horizonLevelStrength near 0.0)
424 // sensitFact value has more effect:
425 horizonLevelStrength = ((horizonLevelStrength - 1) * (100 / sensitFact)) + 1;
428 return constrainf(horizonLevelStrength, 0, 1);
431 // Use the FAST_CODE_NOINLINE directive to avoid this code from being inlined into ITCM RAM to avoid overflow.
432 // The impact is possibly slightly slower performance on F7/H7 but they have more than enough
433 // processing power that it should be a non-issue.
434 STATIC_UNIT_TESTED FAST_CODE_NOINLINE float pidLevel(int axis, const pidProfile_t *pidProfile, const rollAndPitchTrims_t *angleTrim, float currentPidSetpoint) {
435 // calculate error angle and limit the angle to the max inclination
436 // rcDeflection is in range [-1.0, 1.0]
437 float angle = pidProfile->levelAngleLimit * getLevelModeRcDeflection(axis);
438 #ifdef USE_GPS_RESCUE
439 angle += gpsRescueAngle[axis] / 100; // ANGLE IS IN CENTIDEGREES
440 #endif
441 angle = constrainf(angle, -pidProfile->levelAngleLimit, pidProfile->levelAngleLimit);
442 const float errorAngle = angle - ((attitude.raw[axis] - angleTrim->raw[axis]) / 10.0f);
443 if (FLIGHT_MODE(ANGLE_MODE) || FLIGHT_MODE(GPS_RESCUE_MODE)) {
444 // ANGLE mode - control is angle based
445 currentPidSetpoint = errorAngle * pidRuntime.levelGain;
446 } else {
447 // HORIZON mode - mix of ANGLE and ACRO modes
448 // mix in errorAngle to currentPidSetpoint to add a little auto-level feel
449 const float horizonLevelStrength = calcHorizonLevelStrength();
450 currentPidSetpoint = currentPidSetpoint + (errorAngle * pidRuntime.horizonGain * horizonLevelStrength);
452 return currentPidSetpoint;
455 static void handleCrashRecovery(
456 const pidCrashRecovery_e crash_recovery, const rollAndPitchTrims_t *angleTrim,
457 const int axis, const timeUs_t currentTimeUs, const float gyroRate, float *currentPidSetpoint, float *errorRate)
459 if (pidRuntime.inCrashRecoveryMode && cmpTimeUs(currentTimeUs, pidRuntime.crashDetectedAtUs) > pidRuntime.crashTimeDelayUs) {
460 if (crash_recovery == PID_CRASH_RECOVERY_BEEP) {
461 BEEP_ON;
463 if (axis == FD_YAW) {
464 *errorRate = constrainf(*errorRate, -pidRuntime.crashLimitYaw, pidRuntime.crashLimitYaw);
465 } else {
466 // on roll and pitch axes calculate currentPidSetpoint and errorRate to level the aircraft to recover from crash
467 if (sensors(SENSOR_ACC)) {
468 // errorAngle is deviation from horizontal
469 const float errorAngle = -(attitude.raw[axis] - angleTrim->raw[axis]) / 10.0f;
470 *currentPidSetpoint = errorAngle * pidRuntime.levelGain;
471 *errorRate = *currentPidSetpoint - gyroRate;
474 // reset iterm, since accumulated error before crash is now meaningless
475 // and iterm windup during crash recovery can be extreme, especially on yaw axis
476 pidData[axis].I = 0.0f;
477 if (cmpTimeUs(currentTimeUs, pidRuntime.crashDetectedAtUs) > pidRuntime.crashTimeLimitUs
478 || (getMotorMixRange() < 1.0f
479 && fabsf(gyro.gyroADCf[FD_ROLL]) < pidRuntime.crashRecoveryRate
480 && fabsf(gyro.gyroADCf[FD_PITCH]) < pidRuntime.crashRecoveryRate
481 && fabsf(gyro.gyroADCf[FD_YAW]) < pidRuntime.crashRecoveryRate)) {
482 if (sensors(SENSOR_ACC)) {
483 // check aircraft nearly level
484 if (ABS(attitude.raw[FD_ROLL] - angleTrim->raw[FD_ROLL]) < pidRuntime.crashRecoveryAngleDeciDegrees
485 && ABS(attitude.raw[FD_PITCH] - angleTrim->raw[FD_PITCH]) < pidRuntime.crashRecoveryAngleDeciDegrees) {
486 pidRuntime.inCrashRecoveryMode = false;
487 BEEP_OFF;
489 } else {
490 pidRuntime.inCrashRecoveryMode = false;
491 BEEP_OFF;
497 static void detectAndSetCrashRecovery(
498 const pidCrashRecovery_e crash_recovery, const int axis,
499 const timeUs_t currentTimeUs, const float delta, const float errorRate)
501 // if crash recovery is on and accelerometer enabled and there is no gyro overflow, then check for a crash
502 // no point in trying to recover if the crash is so severe that the gyro overflows
503 if ((crash_recovery || FLIGHT_MODE(GPS_RESCUE_MODE)) && !gyroOverflowDetected()) {
504 if (ARMING_FLAG(ARMED)) {
505 if (getMotorMixRange() >= 1.0f && !pidRuntime.inCrashRecoveryMode
506 && fabsf(delta) > pidRuntime.crashDtermThreshold
507 && fabsf(errorRate) > pidRuntime.crashGyroThreshold
508 && fabsf(getSetpointRate(axis)) < pidRuntime.crashSetpointThreshold) {
509 if (crash_recovery == PID_CRASH_RECOVERY_DISARM) {
510 setArmingDisabled(ARMING_DISABLED_CRASH_DETECTED);
511 disarm(DISARM_REASON_CRASH_PROTECTION);
512 } else {
513 pidRuntime.inCrashRecoveryMode = true;
514 pidRuntime.crashDetectedAtUs = currentTimeUs;
517 if (pidRuntime.inCrashRecoveryMode && cmpTimeUs(currentTimeUs, pidRuntime.crashDetectedAtUs) < pidRuntime.crashTimeDelayUs && (fabsf(errorRate) < pidRuntime.crashGyroThreshold
518 || fabsf(getSetpointRate(axis)) > pidRuntime.crashSetpointThreshold)) {
519 pidRuntime.inCrashRecoveryMode = false;
520 BEEP_OFF;
522 } else if (pidRuntime.inCrashRecoveryMode) {
523 pidRuntime.inCrashRecoveryMode = false;
524 BEEP_OFF;
528 #endif // USE_ACC
530 #ifdef USE_ACRO_TRAINER
532 int acroTrainerSign(float x)
534 return x > 0 ? 1 : -1;
537 // Acro Trainer - Manipulate the setPoint to limit axis angle while in acro mode
538 // There are three states:
539 // 1. Current angle has exceeded limit
540 // Apply correction to return to limit (similar to pidLevel)
541 // 2. Future overflow has been projected based on current angle and gyro rate
542 // Manage the setPoint to control the gyro rate as the actual angle approaches the limit (try to prevent overshoot)
543 // 3. If no potential overflow is detected, then return the original setPoint
545 // Use the FAST_CODE_NOINLINE directive to avoid this code from being inlined into ITCM RAM. We accept the
546 // performance decrease when Acro Trainer mode is active under the assumption that user is unlikely to be
547 // expecting ultimate flight performance at very high loop rates when in this mode.
548 static FAST_CODE_NOINLINE float applyAcroTrainer(int axis, const rollAndPitchTrims_t *angleTrim, float setPoint)
550 float ret = setPoint;
552 if (!FLIGHT_MODE(ANGLE_MODE) && !FLIGHT_MODE(HORIZON_MODE) && !FLIGHT_MODE(GPS_RESCUE_MODE)) {
553 bool resetIterm = false;
554 float projectedAngle = 0;
555 const int setpointSign = acroTrainerSign(setPoint);
556 const float currentAngle = (attitude.raw[axis] - angleTrim->raw[axis]) / 10.0f;
557 const int angleSign = acroTrainerSign(currentAngle);
559 if ((pidRuntime.acroTrainerAxisState[axis] != 0) && (pidRuntime.acroTrainerAxisState[axis] != setpointSign)) { // stick has reversed - stop limiting
560 pidRuntime.acroTrainerAxisState[axis] = 0;
563 // Limit and correct the angle when it exceeds the limit
564 if ((fabsf(currentAngle) > pidRuntime.acroTrainerAngleLimit) && (pidRuntime.acroTrainerAxisState[axis] == 0)) {
565 if (angleSign == setpointSign) {
566 pidRuntime.acroTrainerAxisState[axis] = angleSign;
567 resetIterm = true;
571 if (pidRuntime.acroTrainerAxisState[axis] != 0) {
572 ret = constrainf(((pidRuntime.acroTrainerAngleLimit * angleSign) - currentAngle) * pidRuntime.acroTrainerGain, -ACRO_TRAINER_SETPOINT_LIMIT, ACRO_TRAINER_SETPOINT_LIMIT);
573 } else {
575 // Not currently over the limit so project the angle based on current angle and
576 // gyro angular rate using a sliding window based on gyro rate (faster rotation means larger window.
577 // If the projected angle exceeds the limit then apply limiting to minimize overshoot.
578 // Calculate the lookahead window by scaling proportionally with gyro rate from 0-500dps
579 float checkInterval = constrainf(fabsf(gyro.gyroADCf[axis]) / ACRO_TRAINER_LOOKAHEAD_RATE_LIMIT, 0.0f, 1.0f) * pidRuntime.acroTrainerLookaheadTime;
580 projectedAngle = (gyro.gyroADCf[axis] * checkInterval) + currentAngle;
581 const int projectedAngleSign = acroTrainerSign(projectedAngle);
582 if ((fabsf(projectedAngle) > pidRuntime.acroTrainerAngleLimit) && (projectedAngleSign == setpointSign)) {
583 ret = ((pidRuntime.acroTrainerAngleLimit * projectedAngleSign) - projectedAngle) * pidRuntime.acroTrainerGain;
584 resetIterm = true;
588 if (resetIterm) {
589 pidData[axis].I = 0;
592 if (axis == pidRuntime.acroTrainerDebugAxis) {
593 DEBUG_SET(DEBUG_ACRO_TRAINER, 0, lrintf(currentAngle * 10.0f));
594 DEBUG_SET(DEBUG_ACRO_TRAINER, 1, pidRuntime.acroTrainerAxisState[axis]);
595 DEBUG_SET(DEBUG_ACRO_TRAINER, 2, lrintf(ret));
596 DEBUG_SET(DEBUG_ACRO_TRAINER, 3, lrintf(projectedAngle * 10.0f));
600 return ret;
602 #endif // USE_ACRO_TRAINER
604 static float accelerationLimit(int axis, float currentPidSetpoint)
606 static float previousSetpoint[XYZ_AXIS_COUNT];
607 const float currentVelocity = currentPidSetpoint - previousSetpoint[axis];
609 if (fabsf(currentVelocity) > pidRuntime.maxVelocity[axis]) {
610 currentPidSetpoint = (currentVelocity > 0) ? previousSetpoint[axis] + pidRuntime.maxVelocity[axis] : previousSetpoint[axis] - pidRuntime.maxVelocity[axis];
613 previousSetpoint[axis] = currentPidSetpoint;
614 return currentPidSetpoint;
617 static void rotateVector(float v[XYZ_AXIS_COUNT], float rotation[XYZ_AXIS_COUNT])
619 // rotate v around rotation vector rotation
620 // rotation in radians, all elements must be small
621 for (int i = 0; i < XYZ_AXIS_COUNT; i++) {
622 int i_1 = (i + 1) % 3;
623 int i_2 = (i + 2) % 3;
624 float newV = v[i_1] + v[i_2] * rotation[i];
625 v[i_2] -= v[i_1] * rotation[i];
626 v[i_1] = newV;
630 STATIC_UNIT_TESTED void rotateItermAndAxisError()
632 if (pidRuntime.itermRotation
633 #if defined(USE_ABSOLUTE_CONTROL)
634 || pidRuntime.acGain > 0 || debugMode == DEBUG_AC_ERROR
635 #endif
637 const float gyroToAngle = pidRuntime.dT * RAD;
638 float rotationRads[XYZ_AXIS_COUNT];
639 for (int i = FD_ROLL; i <= FD_YAW; i++) {
640 rotationRads[i] = gyro.gyroADCf[i] * gyroToAngle;
642 #if defined(USE_ABSOLUTE_CONTROL)
643 if (pidRuntime.acGain > 0 || debugMode == DEBUG_AC_ERROR) {
644 rotateVector(axisError, rotationRads);
646 #endif
647 if (pidRuntime.itermRotation) {
648 float v[XYZ_AXIS_COUNT];
649 for (int i = 0; i < XYZ_AXIS_COUNT; i++) {
650 v[i] = pidData[i].I;
652 rotateVector(v, rotationRads );
653 for (int i = 0; i < XYZ_AXIS_COUNT; i++) {
654 pidData[i].I = v[i];
660 #ifdef USE_RC_SMOOTHING_FILTER
661 float FAST_CODE applyRcSmoothingFeedforwardFilter(int axis, float pidSetpointDelta)
663 float ret = pidSetpointDelta;
664 if (axis == pidRuntime.rcSmoothingDebugAxis) {
665 DEBUG_SET(DEBUG_RC_SMOOTHING, 1, lrintf(pidSetpointDelta * 100.0f));
667 if (pidRuntime.feedforwardLpfInitialized) {
668 ret = pt3FilterApply(&pidRuntime.feedforwardPt3[axis], pidSetpointDelta);
669 if (axis == pidRuntime.rcSmoothingDebugAxis) {
670 DEBUG_SET(DEBUG_RC_SMOOTHING, 2, lrintf(ret * 100.0f));
673 return ret;
675 #endif // USE_RC_SMOOTHING_FILTER
677 #if defined(USE_ITERM_RELAX)
678 #if defined(USE_ABSOLUTE_CONTROL)
679 STATIC_UNIT_TESTED void applyAbsoluteControl(const int axis, const float gyroRate, float *currentPidSetpoint, float *itermErrorRate)
681 if (pidRuntime.acGain > 0 || debugMode == DEBUG_AC_ERROR) {
682 const float setpointLpf = pt1FilterApply(&pidRuntime.acLpf[axis], *currentPidSetpoint);
683 const float setpointHpf = fabsf(*currentPidSetpoint - setpointLpf);
684 float acErrorRate = 0;
685 const float gmaxac = setpointLpf + 2 * setpointHpf;
686 const float gminac = setpointLpf - 2 * setpointHpf;
687 if (gyroRate >= gminac && gyroRate <= gmaxac) {
688 const float acErrorRate1 = gmaxac - gyroRate;
689 const float acErrorRate2 = gminac - gyroRate;
690 if (acErrorRate1 * axisError[axis] < 0) {
691 acErrorRate = acErrorRate1;
692 } else {
693 acErrorRate = acErrorRate2;
695 if (fabsf(acErrorRate * pidRuntime.dT) > fabsf(axisError[axis]) ) {
696 acErrorRate = -axisError[axis] * pidRuntime.pidFrequency;
698 } else {
699 acErrorRate = (gyroRate > gmaxac ? gmaxac : gminac ) - gyroRate;
702 if (isAirmodeActivated()) {
703 axisError[axis] = constrainf(axisError[axis] + acErrorRate * pidRuntime.dT,
704 -pidRuntime.acErrorLimit, pidRuntime.acErrorLimit);
705 const float acCorrection = constrainf(axisError[axis] * pidRuntime.acGain, -pidRuntime.acLimit, pidRuntime.acLimit);
706 *currentPidSetpoint += acCorrection;
707 *itermErrorRate += acCorrection;
708 DEBUG_SET(DEBUG_AC_CORRECTION, axis, lrintf(acCorrection * 10));
709 if (axis == FD_ROLL) {
710 DEBUG_SET(DEBUG_ITERM_RELAX, 3, lrintf(acCorrection * 10));
713 DEBUG_SET(DEBUG_AC_ERROR, axis, lrintf(axisError[axis] * 10));
716 #endif
718 STATIC_UNIT_TESTED void applyItermRelax(const int axis, const float iterm,
719 const float gyroRate, float *itermErrorRate, float *currentPidSetpoint)
721 const float setpointLpf = pt1FilterApply(&pidRuntime.windupLpf[axis], *currentPidSetpoint);
722 const float setpointHpf = fabsf(*currentPidSetpoint - setpointLpf);
724 if (pidRuntime.itermRelax) {
725 if (axis < FD_YAW || pidRuntime.itermRelax == ITERM_RELAX_RPY || pidRuntime.itermRelax == ITERM_RELAX_RPY_INC) {
726 const float itermRelaxFactor = MAX(0, 1 - setpointHpf / ITERM_RELAX_SETPOINT_THRESHOLD);
727 const bool isDecreasingI =
728 ((iterm > 0) && (*itermErrorRate < 0)) || ((iterm < 0) && (*itermErrorRate > 0));
729 if ((pidRuntime.itermRelax >= ITERM_RELAX_RP_INC) && isDecreasingI) {
730 // Do Nothing, use the precalculed itermErrorRate
731 } else if (pidRuntime.itermRelaxType == ITERM_RELAX_SETPOINT) {
732 *itermErrorRate *= itermRelaxFactor;
733 } else if (pidRuntime.itermRelaxType == ITERM_RELAX_GYRO ) {
734 *itermErrorRate = fapplyDeadband(setpointLpf - gyroRate, setpointHpf);
735 } else {
736 *itermErrorRate = 0.0f;
739 if (axis == FD_ROLL) {
740 DEBUG_SET(DEBUG_ITERM_RELAX, 0, lrintf(setpointHpf));
741 DEBUG_SET(DEBUG_ITERM_RELAX, 1, lrintf(itermRelaxFactor * 100.0f));
742 DEBUG_SET(DEBUG_ITERM_RELAX, 2, lrintf(*itermErrorRate));
746 #if defined(USE_ABSOLUTE_CONTROL)
747 applyAbsoluteControl(axis, gyroRate, currentPidSetpoint, itermErrorRate);
748 #endif
751 #endif
753 #ifdef USE_AIRMODE_LPF
754 void pidUpdateAirmodeLpf(float currentOffset)
756 if (pidRuntime.airmodeThrottleOffsetLimit == 0.0f) {
757 return;
760 float offsetHpf = currentOffset * 2.5f;
761 offsetHpf = offsetHpf - pt1FilterApply(&pidRuntime.airmodeThrottleLpf2, offsetHpf);
763 // During high frequency oscillation 2 * currentOffset averages to the offset required to avoid mirroring of the waveform
764 pt1FilterApply(&pidRuntime.airmodeThrottleLpf1, offsetHpf);
765 // Bring offset up immediately so the filter only applies to the decline
766 if (currentOffset * pidRuntime.airmodeThrottleLpf1.state >= 0 && fabsf(currentOffset) > pidRuntime.airmodeThrottleLpf1.state) {
767 pidRuntime.airmodeThrottleLpf1.state = currentOffset;
769 pidRuntime.airmodeThrottleLpf1.state = constrainf(pidRuntime.airmodeThrottleLpf1.state, -pidRuntime.airmodeThrottleOffsetLimit, pidRuntime.airmodeThrottleOffsetLimit);
772 float pidGetAirmodeThrottleOffset()
774 return pidRuntime.airmodeThrottleLpf1.state;
776 #endif
778 #ifdef USE_LAUNCH_CONTROL
779 #define LAUNCH_CONTROL_MAX_RATE 100.0f
780 #define LAUNCH_CONTROL_MIN_RATE 5.0f
781 #define LAUNCH_CONTROL_ANGLE_WINDOW 10.0f // The remaining angle degrees where rate dampening starts
783 // Use the FAST_CODE_NOINLINE directive to avoid this code from being inlined into ITCM RAM to avoid overflow.
784 // The impact is possibly slightly slower performance on F7/H7 but they have more than enough
785 // processing power that it should be a non-issue.
786 static FAST_CODE_NOINLINE float applyLaunchControl(int axis, const rollAndPitchTrims_t *angleTrim)
788 float ret = 0.0f;
790 // Scale the rates based on stick deflection only. Fixed rates with a max of 100deg/sec
791 // reached at 50% stick deflection. This keeps the launch control positioning consistent
792 // regardless of the user's rates.
793 if ((axis == FD_PITCH) || (pidRuntime.launchControlMode != LAUNCH_CONTROL_MODE_PITCHONLY)) {
794 const float stickDeflection = constrainf(getRcDeflection(axis), -0.5f, 0.5f);
795 ret = LAUNCH_CONTROL_MAX_RATE * stickDeflection * 2;
798 #if defined(USE_ACC)
799 // If ACC is enabled and a limit angle is set, then try to limit forward tilt
800 // to that angle and slow down the rate as the limit is approached to reduce overshoot
801 if ((axis == FD_PITCH) && (pidRuntime.launchControlAngleLimit > 0) && (ret > 0)) {
802 const float currentAngle = (attitude.raw[axis] - angleTrim->raw[axis]) / 10.0f;
803 if (currentAngle >= pidRuntime.launchControlAngleLimit) {
804 ret = 0.0f;
805 } else {
806 //for the last 10 degrees scale the rate from the current input to 5 dps
807 const float angleDelta = pidRuntime.launchControlAngleLimit - currentAngle;
808 if (angleDelta <= LAUNCH_CONTROL_ANGLE_WINDOW) {
809 ret = scaleRangef(angleDelta, 0, LAUNCH_CONTROL_ANGLE_WINDOW, LAUNCH_CONTROL_MIN_RATE, ret);
813 #else
814 UNUSED(angleTrim);
815 #endif
817 return ret;
819 #endif
821 // Betaflight pid controller, which will be maintained in the future with additional features specialised for current (mini) multirotor usage.
822 // Based on 2DOF reference design (matlab)
823 void FAST_CODE pidController(const pidProfile_t *pidProfile, timeUs_t currentTimeUs)
825 static float previousGyroRateDterm[XYZ_AXIS_COUNT];
826 static float previousRawGyroRateDterm[XYZ_AXIS_COUNT];
828 #if defined(USE_ACC)
829 static timeUs_t levelModeStartTimeUs = 0;
830 static bool gpsRescuePreviousState = false;
831 #endif
833 #if defined(USE_ACC)
834 const rollAndPitchTrims_t *angleTrim = &accelerometerConfig()->accelerometerTrims;
835 #else
836 UNUSED(pidProfile);
837 UNUSED(currentTimeUs);
838 #endif
840 #ifdef USE_TPA_MODE
841 const float tpaFactorKp = (currentControlRateProfile->tpaMode == TPA_MODE_PD) ? pidRuntime.tpaFactor : 1.0f;
842 #else
843 const float tpaFactorKp = pidRuntime.tpaFactor;
844 #endif
846 #ifdef USE_YAW_SPIN_RECOVERY
847 const bool yawSpinActive = gyroYawSpinDetected();
848 #endif
850 const bool launchControlActive = isLaunchControlActive();
852 #if defined(USE_ACC)
853 const bool gpsRescueIsActive = FLIGHT_MODE(GPS_RESCUE_MODE);
854 levelMode_e levelMode;
855 if (FLIGHT_MODE(ANGLE_MODE) || FLIGHT_MODE(HORIZON_MODE) || gpsRescueIsActive) {
856 if (pidRuntime.levelRaceMode && !gpsRescueIsActive) {
857 levelMode = LEVEL_MODE_R;
858 } else {
859 levelMode = LEVEL_MODE_RP;
861 } else {
862 levelMode = LEVEL_MODE_OFF;
865 // Keep track of when we entered a self-level mode so that we can
866 // add a guard time before crash recovery can activate.
867 // Also reset the guard time whenever GPS Rescue is activated.
868 if (levelMode) {
869 if ((levelModeStartTimeUs == 0) || (gpsRescueIsActive && !gpsRescuePreviousState)) {
870 levelModeStartTimeUs = currentTimeUs;
872 } else {
873 levelModeStartTimeUs = 0;
875 gpsRescuePreviousState = gpsRescueIsActive;
876 #endif
878 // Dynamic i component,
879 if ((pidRuntime.antiGravityMode == ANTI_GRAVITY_SMOOTH) && pidRuntime.antiGravityEnabled) {
880 // traditional itermAccelerator factor for iTerm
881 pidRuntime.itermAccelerator = pidRuntime.antiGravityThrottleHpf * 0.01f * pidRuntime.itermAcceleratorGain;
882 DEBUG_SET(DEBUG_ANTI_GRAVITY, 1, lrintf(pidRuntime.itermAccelerator * 1000));
883 // users AG Gain changes P boost
884 pidRuntime.antiGravityPBoost *= pidRuntime.itermAcceleratorGain;
885 // add some percentage of that slower, longer acting P boost factor to prolong AG effect on iTerm
886 pidRuntime.itermAccelerator += pidRuntime.antiGravityPBoost * 0.05f;
887 // set the final P boost amount
888 pidRuntime.antiGravityPBoost *= 0.02f;
889 } else {
890 pidRuntime.antiGravityPBoost = 0.0f;
892 DEBUG_SET(DEBUG_ANTI_GRAVITY, 0, lrintf(pidRuntime.itermAccelerator * 1000));
894 float agGain = pidRuntime.dT * pidRuntime.itermAccelerator * AG_KI;
896 // gradually scale back integration when above windup point
897 float dynCi = pidRuntime.dT;
898 if (pidRuntime.itermWindupPointInv > 1.0f) {
899 dynCi *= constrainf((1.0f - getMotorMixRange()) * pidRuntime.itermWindupPointInv, 0.0f, 1.0f);
902 // Precalculate gyro deta for D-term here, this allows loop unrolling
903 float gyroRateDterm[XYZ_AXIS_COUNT];
904 for (int axis = FD_ROLL; axis <= FD_YAW; ++axis) {
905 gyroRateDterm[axis] = gyro.gyroADCf[axis];
906 // -----calculate raw, unfiltered D component
908 // Divide rate change by dT to get differential (ie dr/dt).
909 // dT is fixed and calculated from the target PID loop time
910 // This is done to avoid DTerm spikes that occur with dynamically
911 // calculated deltaT whenever another task causes the PID
912 // loop execution to be delayed.
913 const float delta =
914 - (gyroRateDterm[axis] - previousRawGyroRateDterm[axis]) * pidRuntime.pidFrequency / D_LPF_RAW_SCALE;
915 previousRawGyroRateDterm[axis] = gyroRateDterm[axis];
917 // Log the unfiltered D
918 if (axis == FD_ROLL) {
919 DEBUG_SET(DEBUG_D_LPF, 0, lrintf(delta));
920 } else if (axis == FD_PITCH) {
921 DEBUG_SET(DEBUG_D_LPF, 1, lrintf(delta));
924 gyroRateDterm[axis] = pidRuntime.dtermNotchApplyFn((filter_t *) &pidRuntime.dtermNotch[axis], gyroRateDterm[axis]);
925 gyroRateDterm[axis] = pidRuntime.dtermLowpassApplyFn((filter_t *) &pidRuntime.dtermLowpass[axis], gyroRateDterm[axis]);
926 gyroRateDterm[axis] = pidRuntime.dtermLowpass2ApplyFn((filter_t *) &pidRuntime.dtermLowpass2[axis], gyroRateDterm[axis]);
929 rotateItermAndAxisError();
931 #ifdef USE_RPM_FILTER
932 rpmFilterUpdate();
933 #endif
935 #ifdef USE_FEEDFORWARD
936 bool newRcFrame = false;
937 if (getShouldUpdateFeedforward()) {
938 newRcFrame = true;
940 #endif
942 // ----------PID controller----------
943 for (int axis = FD_ROLL; axis <= FD_YAW; ++axis) {
945 float currentPidSetpoint = getSetpointRate(axis);
946 if (pidRuntime.maxVelocity[axis]) {
947 currentPidSetpoint = accelerationLimit(axis, currentPidSetpoint);
949 // Yaw control is GYRO based, direct sticks control is applied to rate PID
950 // When Race Mode is active PITCH control is also GYRO based in level or horizon mode
951 #if defined(USE_ACC)
952 switch (levelMode) {
953 case LEVEL_MODE_OFF:
955 break;
956 case LEVEL_MODE_R:
957 if (axis == FD_PITCH) {
958 break;
961 FALLTHROUGH;
962 case LEVEL_MODE_RP:
963 if (axis == FD_YAW) {
964 break;
966 currentPidSetpoint = pidLevel(axis, pidProfile, angleTrim, currentPidSetpoint);
968 #endif
970 #ifdef USE_ACRO_TRAINER
971 if ((axis != FD_YAW) && pidRuntime.acroTrainerActive && !pidRuntime.inCrashRecoveryMode && !launchControlActive) {
972 currentPidSetpoint = applyAcroTrainer(axis, angleTrim, currentPidSetpoint);
974 #endif // USE_ACRO_TRAINER
976 #ifdef USE_LAUNCH_CONTROL
977 if (launchControlActive) {
978 #if defined(USE_ACC)
979 currentPidSetpoint = applyLaunchControl(axis, angleTrim);
980 #else
981 currentPidSetpoint = applyLaunchControl(axis, NULL);
982 #endif
984 #endif
986 // Handle yaw spin recovery - zero the setpoint on yaw to aid in recovery
987 // It's not necessary to zero the set points for R/P because the PIDs will be zeroed below
988 #ifdef USE_YAW_SPIN_RECOVERY
989 if ((axis == FD_YAW) && yawSpinActive) {
990 currentPidSetpoint = 0.0f;
992 #endif // USE_YAW_SPIN_RECOVERY
994 // -----calculate error rate
995 const float gyroRate = gyro.gyroADCf[axis]; // Process variable from gyro output in deg/sec
996 float errorRate = currentPidSetpoint - gyroRate; // r - y
997 #if defined(USE_ACC)
998 handleCrashRecovery(
999 pidProfile->crash_recovery, angleTrim, axis, currentTimeUs, gyroRate,
1000 &currentPidSetpoint, &errorRate);
1001 #endif
1003 const float previousIterm = pidData[axis].I;
1004 float itermErrorRate = errorRate;
1005 #ifdef USE_ABSOLUTE_CONTROL
1006 float uncorrectedSetpoint = currentPidSetpoint;
1007 #endif
1009 #if defined(USE_ITERM_RELAX)
1010 if (!launchControlActive && !pidRuntime.inCrashRecoveryMode) {
1011 applyItermRelax(axis, previousIterm, gyroRate, &itermErrorRate, &currentPidSetpoint);
1012 errorRate = currentPidSetpoint - gyroRate;
1014 #endif
1015 #ifdef USE_ABSOLUTE_CONTROL
1016 float setpointCorrection = currentPidSetpoint - uncorrectedSetpoint;
1017 #endif
1019 // --------low-level gyro-based PID based on 2DOF PID controller. ----------
1020 // 2-DOF PID controller with optional filter on derivative term.
1021 // b = 1 and only c (feedforward weight) can be tuned (amount derivative on measurement or error).
1023 // -----calculate P component
1024 pidData[axis].P = pidRuntime.pidCoefficient[axis].Kp * errorRate * tpaFactorKp;
1025 if (axis == FD_YAW) {
1026 pidData[axis].P = pidRuntime.ptermYawLowpassApplyFn((filter_t *) &pidRuntime.ptermYawLowpass, pidData[axis].P);
1029 // -----calculate I component
1030 float Ki;
1031 float axisDynCi;
1032 #ifdef USE_LAUNCH_CONTROL
1033 // if launch control is active override the iterm gains and apply iterm windup protection to all axes
1034 if (launchControlActive) {
1035 Ki = pidRuntime.launchControlKi;
1036 axisDynCi = dynCi;
1037 } else
1038 #endif
1040 Ki = pidRuntime.pidCoefficient[axis].Ki;
1041 axisDynCi = (axis == FD_YAW) ? dynCi : pidRuntime.dT; // only apply windup protection to yaw
1044 pidData[axis].I = constrainf(previousIterm + (Ki * axisDynCi + agGain) * itermErrorRate, -pidRuntime.itermLimit, pidRuntime.itermLimit);
1046 // -----calculate pidSetpointDelta
1047 float pidSetpointDelta = 0;
1048 #ifdef USE_FEEDFORWARD
1049 pidSetpointDelta = feedforwardApply(axis, newRcFrame, pidRuntime.feedforwardAveraging);
1050 #endif
1051 pidRuntime.previousPidSetpoint[axis] = currentPidSetpoint;
1053 // -----calculate D component
1054 // disable D if launch control is active
1055 if ((pidRuntime.pidCoefficient[axis].Kd > 0) && !launchControlActive) {
1057 // Divide rate change by dT to get differential (ie dr/dt).
1058 // dT is fixed and calculated from the target PID loop time
1059 // This is done to avoid DTerm spikes that occur with dynamically
1060 // calculated deltaT whenever another task causes the PID
1061 // loop execution to be delayed.
1062 const float delta =
1063 - (gyroRateDterm[axis] - previousGyroRateDterm[axis]) * pidRuntime.pidFrequency;
1064 float preTpaD = pidRuntime.pidCoefficient[axis].Kd * delta;
1066 #if defined(USE_ACC)
1067 if (cmpTimeUs(currentTimeUs, levelModeStartTimeUs) > CRASH_RECOVERY_DETECTION_DELAY_US) {
1068 detectAndSetCrashRecovery(pidProfile->crash_recovery, axis, currentTimeUs, delta, errorRate);
1070 #endif
1072 #if defined(USE_D_MIN)
1073 float dMinFactor = 1.0f;
1074 if (pidRuntime.dMinPercent[axis] > 0) {
1075 float dMinGyroFactor = pt2FilterApply(&pidRuntime.dMinRange[axis], delta);
1076 dMinGyroFactor = fabsf(dMinGyroFactor) * pidRuntime.dMinGyroGain;
1077 const float dMinSetpointFactor = (fabsf(pidSetpointDelta)) * pidRuntime.dMinSetpointGain;
1078 dMinFactor = MAX(dMinGyroFactor, dMinSetpointFactor);
1079 dMinFactor = pidRuntime.dMinPercent[axis] + (1.0f - pidRuntime.dMinPercent[axis]) * dMinFactor;
1080 dMinFactor = pt2FilterApply(&pidRuntime.dMinLowpass[axis], dMinFactor);
1081 dMinFactor = MIN(dMinFactor, 1.0f);
1082 if (axis == FD_ROLL) {
1083 DEBUG_SET(DEBUG_D_MIN, 0, lrintf(dMinGyroFactor * 100));
1084 DEBUG_SET(DEBUG_D_MIN, 1, lrintf(dMinSetpointFactor * 100));
1085 DEBUG_SET(DEBUG_D_MIN, 2, lrintf(pidRuntime.pidCoefficient[axis].Kd * dMinFactor * 10 / DTERM_SCALE));
1086 } else if (axis == FD_PITCH) {
1087 DEBUG_SET(DEBUG_D_MIN, 3, lrintf(pidRuntime.pidCoefficient[axis].Kd * dMinFactor * 10 / DTERM_SCALE));
1091 // Apply the dMinFactor
1092 preTpaD *= dMinFactor;
1093 #endif
1094 pidData[axis].D = preTpaD * pidRuntime.tpaFactor;
1096 // Log the value of D pre application of TPA
1097 preTpaD *= D_LPF_FILT_SCALE;
1099 if (axis == FD_ROLL) {
1100 DEBUG_SET(DEBUG_D_LPF, 2, lrintf(preTpaD));
1101 } else if (axis == FD_PITCH) {
1102 DEBUG_SET(DEBUG_D_LPF, 3, lrintf(preTpaD));
1104 } else {
1105 pidData[axis].D = 0;
1107 if (axis == FD_ROLL) {
1108 DEBUG_SET(DEBUG_D_LPF, 2, 0);
1109 } else if (axis == FD_PITCH) {
1110 DEBUG_SET(DEBUG_D_LPF, 3, 0);
1114 previousGyroRateDterm[axis] = gyroRateDterm[axis];
1116 // -----calculate feedforward component
1117 #ifdef USE_ABSOLUTE_CONTROL
1118 // include abs control correction in feedforward
1119 pidSetpointDelta += setpointCorrection - pidRuntime.oldSetpointCorrection[axis];
1120 pidRuntime.oldSetpointCorrection[axis] = setpointCorrection;
1121 #endif
1123 // no feedforward in launch control
1124 float feedforwardGain = launchControlActive ? 0.0f : pidRuntime.pidCoefficient[axis].Kf;
1125 if (feedforwardGain > 0) {
1126 // halve feedforward in Level mode since stick sensitivity is weaker by about half
1127 feedforwardGain *= FLIGHT_MODE(ANGLE_MODE) ? 0.5f : 1.0f;
1128 // transition now calculated in feedforward.c when new RC data arrives
1129 float feedForward = feedforwardGain * pidSetpointDelta * pidRuntime.pidFrequency;
1131 #ifdef USE_FEEDFORWARD
1132 pidData[axis].F = shouldApplyFeedforwardLimits(axis) ?
1133 applyFeedforwardLimit(axis, feedForward, pidRuntime.pidCoefficient[axis].Kp, currentPidSetpoint) : feedForward;
1134 #else
1135 pidData[axis].F = feedForward;
1136 #endif
1137 #ifdef USE_RC_SMOOTHING_FILTER
1138 pidData[axis].F = applyRcSmoothingFeedforwardFilter(axis, pidData[axis].F);
1139 #endif // USE_RC_SMOOTHING_FILTER
1140 } else {
1141 pidData[axis].F = 0;
1144 #ifdef USE_YAW_SPIN_RECOVERY
1145 if (yawSpinActive) {
1146 pidData[axis].I = 0; // in yaw spin always disable I
1147 if (axis <= FD_PITCH) {
1148 // zero PIDs on pitch and roll leaving yaw P to correct spin
1149 pidData[axis].P = 0;
1150 pidData[axis].D = 0;
1151 pidData[axis].F = 0;
1154 #endif // USE_YAW_SPIN_RECOVERY
1156 #ifdef USE_LAUNCH_CONTROL
1157 // Disable P/I appropriately based on the launch control mode
1158 if (launchControlActive) {
1159 // if not using FULL mode then disable I accumulation on yaw as
1160 // yaw has a tendency to windup. Otherwise limit yaw iterm accumulation.
1161 const int launchControlYawItermLimit = (pidRuntime.launchControlMode == LAUNCH_CONTROL_MODE_FULL) ? LAUNCH_CONTROL_YAW_ITERM_LIMIT : 0;
1162 pidData[FD_YAW].I = constrainf(pidData[FD_YAW].I, -launchControlYawItermLimit, launchControlYawItermLimit);
1164 // for pitch-only mode we disable everything except pitch P/I
1165 if (pidRuntime.launchControlMode == LAUNCH_CONTROL_MODE_PITCHONLY) {
1166 pidData[FD_ROLL].P = 0;
1167 pidData[FD_ROLL].I = 0;
1168 pidData[FD_YAW].P = 0;
1169 // don't let I go negative (pitch backwards) as front motors are limited in the mixer
1170 pidData[FD_PITCH].I = MAX(0.0f, pidData[FD_PITCH].I);
1173 #endif
1174 // calculating the PID sum
1176 // P boost at the end of throttle chop
1177 // attenuate effect if turning more than 50 deg/s, half at 100 deg/s
1178 float agBoostAttenuator = fabsf(currentPidSetpoint) / 50.0f;
1179 agBoostAttenuator = MAX(agBoostAttenuator, 1.0f);
1180 const float agBoost = 1.0f + (pidRuntime.antiGravityPBoost / agBoostAttenuator);
1181 if (axis != FD_YAW) {
1182 pidData[axis].P *= agBoost;
1183 DEBUG_SET(DEBUG_ANTI_GRAVITY, axis + 2, lrintf(agBoost * 1000));
1186 const float pidSum = pidData[axis].P + pidData[axis].I + pidData[axis].D + pidData[axis].F;
1187 #ifdef USE_INTEGRATED_YAW_CONTROL
1188 if (axis == FD_YAW && pidRuntime.useIntegratedYaw) {
1189 pidData[axis].Sum += pidSum * pidRuntime.dT * 100.0f;
1190 pidData[axis].Sum -= pidData[axis].Sum * pidRuntime.integratedYawRelax / 100000.0f * pidRuntime.dT / 0.000125f;
1191 } else
1192 #endif
1194 pidData[axis].Sum = pidSum;
1198 // Disable PID control if at zero throttle or if gyro overflow detected
1199 // This may look very innefficient, but it is done on purpose to always show real CPU usage as in flight
1200 if (!pidRuntime.pidStabilisationEnabled || gyroOverflowDetected()) {
1201 for (int axis = FD_ROLL; axis <= FD_YAW; ++axis) {
1202 pidData[axis].P = 0;
1203 pidData[axis].I = 0;
1204 pidData[axis].D = 0;
1205 pidData[axis].F = 0;
1207 pidData[axis].Sum = 0;
1209 } else if (pidRuntime.zeroThrottleItermReset) {
1210 pidResetIterm();
1214 bool crashRecoveryModeActive(void)
1216 return pidRuntime.inCrashRecoveryMode;
1219 #ifdef USE_ACRO_TRAINER
1220 void pidSetAcroTrainerState(bool newState)
1222 if (pidRuntime.acroTrainerActive != newState) {
1223 if (newState) {
1224 pidAcroTrainerInit();
1226 pidRuntime.acroTrainerActive = newState;
1229 #endif // USE_ACRO_TRAINER
1231 void pidSetAntiGravityState(bool newState)
1233 if (newState != pidRuntime.antiGravityEnabled) {
1234 // reset the accelerator on state changes
1235 pidRuntime.itermAccelerator = 0.0f;
1237 pidRuntime.antiGravityEnabled = newState;
1240 bool pidAntiGravityEnabled(void)
1242 return pidRuntime.antiGravityEnabled;
1245 #ifdef USE_DYN_LPF
1246 void dynLpfDTermUpdate(float throttle)
1248 if (pidRuntime.dynLpfFilter != DYN_LPF_NONE) {
1249 float cutoffFreq;
1250 if (pidRuntime.dynLpfCurveExpo > 0) {
1251 cutoffFreq = dynLpfCutoffFreq(throttle, pidRuntime.dynLpfMin, pidRuntime.dynLpfMax, pidRuntime.dynLpfCurveExpo);
1252 } else {
1253 cutoffFreq = fmaxf(dynThrottle(throttle) * pidRuntime.dynLpfMax, pidRuntime.dynLpfMin);
1256 switch (pidRuntime.dynLpfFilter) {
1257 case DYN_LPF_PT1:
1258 for (int axis = 0; axis < XYZ_AXIS_COUNT; axis++) {
1259 pt1FilterUpdateCutoff(&pidRuntime.dtermLowpass[axis].pt1Filter, pt1FilterGain(cutoffFreq, pidRuntime.dT));
1261 break;
1262 case DYN_LPF_BIQUAD:
1263 for (int axis = 0; axis < XYZ_AXIS_COUNT; axis++) {
1264 biquadFilterUpdateLPF(&pidRuntime.dtermLowpass[axis].biquadFilter, cutoffFreq, targetPidLooptime);
1266 break;
1267 case DYN_LPF_PT2:
1268 for (int axis = 0; axis < XYZ_AXIS_COUNT; axis++) {
1269 pt2FilterUpdateCutoff(&pidRuntime.dtermLowpass[axis].pt2Filter, pt2FilterGain(cutoffFreq, pidRuntime.dT));
1271 break;
1272 case DYN_LPF_PT3:
1273 for (int axis = 0; axis < XYZ_AXIS_COUNT; axis++) {
1274 pt3FilterUpdateCutoff(&pidRuntime.dtermLowpass[axis].pt3Filter, pt3FilterGain(cutoffFreq, pidRuntime.dT));
1276 break;
1280 #endif
1282 float dynLpfCutoffFreq(float throttle, uint16_t dynLpfMin, uint16_t dynLpfMax, uint8_t expo) {
1283 const float expof = expo / 10.0f;
1284 static float curve;
1285 curve = throttle * (1 - throttle) * expof + throttle;
1286 return (dynLpfMax - dynLpfMin) * curve + dynLpfMin;
1289 void pidSetItermReset(bool enabled)
1291 pidRuntime.zeroThrottleItermReset = enabled;
1294 float pidGetPreviousSetpoint(int axis)
1296 return pidRuntime.previousPidSetpoint[axis];
1299 float pidGetDT()
1301 return pidRuntime.dT;
1304 float pidGetPidFrequency()
1306 return pidRuntime.pidFrequency;