2 * This file is part of Cleanflight.
4 * Cleanflight is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * Cleanflight is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with Cleanflight. If not, see <http://www.gnu.org/licenses/>.
24 #include "build/build_config.h"
25 #include "build/debug.h"
27 #include "common/axis.h"
28 #include "common/maths.h"
29 #include "common/filter.h"
31 #include "drivers/time.h"
33 #include "sensors/sensors.h"
34 #include "sensors/acceleration.h"
35 #include "sensors/boardalignment.h"
36 #include "sensors/gyro.h"
37 #include "sensors/pitotmeter.h"
39 #include "flight/pid.h"
40 #include "flight/imu.h"
41 #include "flight/mixer.h"
43 #include "fc/config.h"
44 #include "fc/controlrate_profile.h"
45 #include "fc/rc_controls.h"
46 #include "fc/rc_modes.h"
47 #include "fc/runtime_config.h"
49 #include "navigation/navigation.h"
50 #include "navigation/navigation_private.h"
52 #include "programming/logic_condition.h"
56 #include "sensors/battery.h"
58 // Base frequencies for smoothing pitch and roll
59 #define NAV_FW_BASE_PITCH_CUTOFF_FREQUENCY_HZ 2.0f
60 #define NAV_FW_BASE_ROLL_CUTOFF_FREQUENCY_HZ 10.0f
62 // If we are going slower than NAV_FW_MIN_VEL_SPEED_BOOST - boost throttle to fight against the wind
63 #define NAV_FW_THROTTLE_SPEED_BOOST_GAIN 1.5f
64 #define NAV_FW_MIN_VEL_SPEED_BOOST 700.0f // 7 m/s
66 // If this is enabled navigation won't be applied if velocity is below 3 m/s
67 //#define NAV_FW_LIMIT_MIN_FLY_VELOCITY
69 static bool isPitchAdjustmentValid
= false;
70 static bool isRollAdjustmentValid
= false;
71 static bool isYawAdjustmentValid
= false;
72 static float throttleSpeedAdjustment
= 0;
73 static bool isAutoThrottleManuallyIncreased
= false;
74 static int32_t navHeadingError
;
75 static float navCrossTrackError
;
76 static int8_t loiterDirYaw
= 1;
77 bool needToCalculateCircularLoiter
;
79 // Calculates the cutoff frequency for smoothing out roll/pitch commands
80 // control_smoothness valid range from 0 to 9
81 // resulting cutoff_freq ranging from baseFreq downwards to ~0.11Hz
82 static float getSmoothnessCutoffFreq(float baseFreq
)
84 uint16_t smoothness
= 10 - navConfig()->fw
.control_smoothness
;
85 return 0.001f
* baseFreq
* (float)(smoothness
*smoothness
*smoothness
) + 0.1f
;
88 // Calculates the cutoff frequency for smoothing out pitchToThrottleCorrection
89 // pitch_to_throttle_smooth valid range from 0 to 9
90 // resulting cutoff_freq ranging from baseFreq downwards to ~0.01Hz
91 static float getPitchToThrottleSmoothnessCutoffFreq(float baseFreq
)
93 uint16_t smoothness
= 10 - navConfig()->fw
.pitch_to_throttle_smooth
;
94 return 0.001f
* baseFreq
* (float)(smoothness
*smoothness
*smoothness
) + 0.01f
;
97 /*-----------------------------------------------------------
99 *-----------------------------------------------------------*/
100 void setupFixedWingAltitudeController(void)
105 void resetFixedWingAltitudeController(void)
107 navPidReset(&posControl
.pids
.fw_alt
);
108 posControl
.rcAdjustment
[PITCH
] = 0;
109 isPitchAdjustmentValid
= false;
110 throttleSpeedAdjustment
= 0;
113 bool adjustFixedWingAltitudeFromRCInput(void)
115 int16_t rcAdjustment
= applyDeadbandRescaled(rcCommand
[PITCH
], rcControlsConfig()->alt_hold_deadband
, -500, 500);
118 // set velocity proportional to stick movement
119 float rcClimbRate
= -rcAdjustment
* navConfig()->general
.max_manual_climb_rate
/ (500.0f
- rcControlsConfig()->alt_hold_deadband
);
120 updateClimbRateToAltitudeController(rcClimbRate
, ROC_TO_ALT_NORMAL
);
124 // Adjusting finished - reset desired position to stay exactly where pilot released the stick
125 if (posControl
.flags
.isAdjustingAltitude
) {
126 updateClimbRateToAltitudeController(0, ROC_TO_ALT_RESET
);
132 // Position to velocity controller for Z axis
133 static void updateAltitudeVelocityAndPitchController_FW(timeDelta_t deltaMicros
)
135 static pt1Filter_t velzFilterState
;
137 // On a fixed wing we might not have a reliable climb rate source (if no BARO available), so we can't apply PID controller to
138 // velocity error. We use PID controller on altitude error and calculate desired pitch angle
141 const float demSPE
= (posControl
.desiredState
.pos
.z
* 0.01f
) * GRAVITY_MSS
;
142 const float demSKE
= 0.0f
;
144 const float estSPE
= (navGetCurrentActualPositionAndVelocity()->pos
.z
* 0.01f
) * GRAVITY_MSS
;
145 const float estSKE
= 0.0f
;
147 // speedWeight controls balance between potential and kinetic energy used for pitch controller
148 // speedWeight = 1.0 : pitch will only control airspeed and won't control altitude
149 // speedWeight = 0.5 : pitch will be used to control both airspeed and altitude
150 // speedWeight = 0.0 : pitch will only control altitude
151 const float speedWeight
= 0.0f
; // no speed sensing for now
153 const float demSEB
= demSPE
* (1.0f
- speedWeight
) - demSKE
* speedWeight
;
154 const float estSEB
= estSPE
* (1.0f
- speedWeight
) - estSKE
* speedWeight
;
156 // SEB to pitch angle gain to account for airspeed (with respect to specified reference (tuning) speed
157 const float pitchGainInv
= 1.0f
/ 1.0f
;
159 // Here we use negative values for dive for better clarity
160 const float maxClimbDeciDeg
= DEGREES_TO_DECIDEGREES(navConfig()->fw
.max_climb_angle
);
161 const float minDiveDeciDeg
= -DEGREES_TO_DECIDEGREES(navConfig()->fw
.max_dive_angle
);
163 // PID controller to translate energy balance error [J] into pitch angle [decideg]
164 float targetPitchAngle
= navPidApply3(&posControl
.pids
.fw_alt
, demSEB
, estSEB
, US2S(deltaMicros
), minDiveDeciDeg
, maxClimbDeciDeg
, 0, pitchGainInv
, 1.0f
);
166 // Apply low-pass filter to prevent rapid correction
167 targetPitchAngle
= pt1FilterApply4(&velzFilterState
, targetPitchAngle
, getSmoothnessCutoffFreq(NAV_FW_BASE_PITCH_CUTOFF_FREQUENCY_HZ
), US2S(deltaMicros
));
169 // Reconstrain pitch angle ( >0 - climb, <0 - dive)
170 targetPitchAngle
= constrainf(targetPitchAngle
, minDiveDeciDeg
, maxClimbDeciDeg
);
171 posControl
.rcAdjustment
[PITCH
] = targetPitchAngle
;
174 void applyFixedWingAltitudeAndThrottleController(timeUs_t currentTimeUs
)
176 static timeUs_t previousTimePositionUpdate
= 0; // Occurs @ altitude sensor update rate (max MAX_ALTITUDE_UPDATE_RATE_HZ)
178 if ((posControl
.flags
.estAltStatus
>= EST_USABLE
)) {
179 if (posControl
.flags
.verticalPositionDataNew
) {
180 const timeDeltaLarge_t deltaMicrosPositionUpdate
= currentTimeUs
- previousTimePositionUpdate
;
181 previousTimePositionUpdate
= currentTimeUs
;
183 // Check if last correction was not too long ago
184 if (deltaMicrosPositionUpdate
< MAX_POSITION_UPDATE_INTERVAL_US
) {
185 updateAltitudeVelocityAndPitchController_FW(deltaMicrosPositionUpdate
);
188 // Position update has not occurred in time (first iteration or glitch), reset altitude controller
189 resetFixedWingAltitudeController();
192 // Indicate that information is no longer usable
193 posControl
.flags
.verticalPositionDataConsumed
= true;
196 isPitchAdjustmentValid
= true;
199 // No valid altitude sensor data, don't adjust pitch automatically, rcCommand[PITCH] is passed through to PID controller
200 isPitchAdjustmentValid
= false;
204 /*-----------------------------------------------------------
205 * Adjusts desired heading from pilot's input
206 *-----------------------------------------------------------*/
207 bool adjustFixedWingHeadingFromRCInput(void)
209 if (ABS(rcCommand
[YAW
]) > rcControlsConfig()->pos_hold_deadband
) {
216 /*-----------------------------------------------------------
217 * XY-position controller for multicopter aircraft
218 *-----------------------------------------------------------*/
219 static fpVector3_t virtualDesiredPosition
;
220 static pt1Filter_t fwPosControllerCorrectionFilterState
;
223 * TODO Currently this function resets both FixedWing and Rover & Boat position controller
225 void resetFixedWingPositionController(void)
227 virtualDesiredPosition
.x
= 0;
228 virtualDesiredPosition
.y
= 0;
229 virtualDesiredPosition
.z
= 0;
231 navPidReset(&posControl
.pids
.fw_nav
);
232 navPidReset(&posControl
.pids
.fw_heading
);
233 posControl
.rcAdjustment
[ROLL
] = 0;
234 posControl
.rcAdjustment
[YAW
] = 0;
235 isRollAdjustmentValid
= false;
236 isYawAdjustmentValid
= false;
238 pt1FilterReset(&fwPosControllerCorrectionFilterState
, 0.0f
);
241 static int8_t loiterDirection(void) {
242 int8_t dir
= 1; //NAV_LOITER_RIGHT
244 if (navConfig()->fw
.loiter_direction
== NAV_LOITER_LEFT
) {
248 if (navConfig()->fw
.loiter_direction
== NAV_LOITER_YAW
) {
250 if (rcCommand
[YAW
] < -250) {
251 loiterDirYaw
= 1; //RIGHT //yaw is contrariwise
254 if (rcCommand
[YAW
] > 250) {
255 loiterDirYaw
= -1; //LEFT //see annexCode in fc_core.c
261 if (IS_RC_MODE_ACTIVE(BOXLOITERDIRCHN
)) {
268 static void calculateVirtualPositionTarget_FW(float trackingPeriod
)
270 float posErrorX
= posControl
.desiredState
.pos
.x
- navGetCurrentActualPositionAndVelocity()->pos
.x
;
271 float posErrorY
= posControl
.desiredState
.pos
.y
- navGetCurrentActualPositionAndVelocity()->pos
.y
;
273 float distanceToActualTarget
= calc_length_pythagorean_2D(posErrorX
, posErrorY
);
275 // Limit minimum forward velocity to 1 m/s
276 float trackingDistance
= trackingPeriod
* MAX(posControl
.actualState
.velXY
, 100.0f
);
278 uint32_t navLoiterRadius
= getLoiterRadius(navConfig()->fw
.loiter_radius
);
279 fpVector3_t loiterCenterPos
= posControl
.desiredState
.pos
;
280 int8_t loiterTurnDirection
= loiterDirection();
282 // Detemine if a circular loiter is required.
283 // For waypoints only use circular loiter when angular visibility is > 30 degs, otherwise head straight toward target
284 #define TAN_15DEG 0.26795f
285 needToCalculateCircularLoiter
= isNavHoldPositionActive() &&
286 (distanceToActualTarget
<= (navLoiterRadius
/ TAN_15DEG
)) &&
287 (distanceToActualTarget
> 50.0f
);
289 /* WP turn smoothing with 2 options, 1: pass through WP, 2: cut inside turn missing WP
290 * Works for turns > 30 degs and < 160 degs.
291 * Option 1 switches to loiter path around waypoint using navLoiterRadius.
292 * Loiter centered on point inside turn at required distance from waypoint and
293 * on a bearing midway between current and next waypoint course bearings.
294 * Option 2 simply uses a normal turn once the turn initiation point is reached */
295 int32_t waypointTurnAngle
= posControl
.activeWaypoint
.nextTurnAngle
== -1 ? -1 : ABS(posControl
.activeWaypoint
.nextTurnAngle
);
296 posControl
.flags
.wpTurnSmoothingActive
= false;
297 if (waypointTurnAngle
> 3000 && waypointTurnAngle
< 16000 && isWaypointNavTrackingActive() && !needToCalculateCircularLoiter
) {
298 // turnStartFactor adjusts start of loiter based on turn angle
299 float turnStartFactor
;
300 if (navConfig()->fw
.wp_turn_smoothing
== WP_TURN_SMOOTHING_ON
) { // passes through WP
301 turnStartFactor
= waypointTurnAngle
/ 6000.0f
;
302 } else { // // cut inside turn missing WP
303 turnStartFactor
= constrainf(tan_approx(CENTIDEGREES_TO_RADIANS(waypointTurnAngle
/ 2.0f
)), 1.0f
, 2.0f
);
305 // velXY provides additional turn initiation distance based on an assumed 1 second delayed turn response time
306 if (posControl
.wpDistance
< (posControl
.actualState
.velXY
+ navLoiterRadius
* turnStartFactor
)) {
307 if (navConfig()->fw
.wp_turn_smoothing
== WP_TURN_SMOOTHING_ON
) {
308 int32_t loiterCenterBearing
= wrap_36000(((wrap_18000(posControl
.activeWaypoint
.nextTurnAngle
- 18000)) / 2) + posControl
.activeWaypoint
.yaw
+ 18000);
309 loiterCenterPos
.x
= posControl
.activeWaypoint
.pos
.x
+ navLoiterRadius
* cos_approx(CENTIDEGREES_TO_RADIANS(loiterCenterBearing
));
310 loiterCenterPos
.y
= posControl
.activeWaypoint
.pos
.y
+ navLoiterRadius
* sin_approx(CENTIDEGREES_TO_RADIANS(loiterCenterBearing
));
312 posErrorX
= loiterCenterPos
.x
- navGetCurrentActualPositionAndVelocity()->pos
.x
;
313 posErrorY
= loiterCenterPos
.y
- navGetCurrentActualPositionAndVelocity()->pos
.y
;
315 // turn direction to next waypoint
316 loiterTurnDirection
= posControl
.activeWaypoint
.nextTurnAngle
> 0 ? 1 : -1; // 1 = right
318 needToCalculateCircularLoiter
= true;
320 posControl
.flags
.wpTurnSmoothingActive
= true;
324 // We are closing in on a waypoint, calculate circular loiter if required
325 if (needToCalculateCircularLoiter
) {
326 float loiterAngle
= atan2_approx(-posErrorY
, -posErrorX
) + DEGREES_TO_RADIANS(loiterTurnDirection
* 45.0f
);
327 float loiterTargetX
= loiterCenterPos
.x
+ navLoiterRadius
* cos_approx(loiterAngle
);
328 float loiterTargetY
= loiterCenterPos
.y
+ navLoiterRadius
* sin_approx(loiterAngle
);
330 // We have temporary loiter target. Recalculate distance and position error
331 posErrorX
= loiterTargetX
- navGetCurrentActualPositionAndVelocity()->pos
.x
;
332 posErrorY
= loiterTargetY
- navGetCurrentActualPositionAndVelocity()->pos
.y
;
333 distanceToActualTarget
= calc_length_pythagorean_2D(posErrorX
, posErrorY
);
336 // Calculate virtual waypoint
337 virtualDesiredPosition
.x
= navGetCurrentActualPositionAndVelocity()->pos
.x
+ posErrorX
* (trackingDistance
/ distanceToActualTarget
);
338 virtualDesiredPosition
.y
= navGetCurrentActualPositionAndVelocity()->pos
.y
+ posErrorY
* (trackingDistance
/ distanceToActualTarget
);
340 // Shift position according to pilot's ROLL input (up to max_manual_speed velocity)
341 if (posControl
.flags
.isAdjustingPosition
) {
342 int16_t rcRollAdjustment
= applyDeadbandRescaled(rcCommand
[ROLL
], rcControlsConfig()->pos_hold_deadband
, -500, 500);
344 if (rcRollAdjustment
) {
345 float rcShiftY
= rcRollAdjustment
* navConfig()->general
.max_manual_speed
/ 500.0f
* trackingPeriod
;
347 // Rotate this target shift from body frame to to earth frame and apply to position target
348 virtualDesiredPosition
.x
+= -rcShiftY
* posControl
.actualState
.sinYaw
;
349 virtualDesiredPosition
.y
+= rcShiftY
* posControl
.actualState
.cosYaw
;
354 bool adjustFixedWingPositionFromRCInput(void)
356 int16_t rcRollAdjustment
= applyDeadbandRescaled(rcCommand
[ROLL
], rcControlsConfig()->pos_hold_deadband
, -500, 500);
357 return (rcRollAdjustment
);
360 float processHeadingYawController(timeDelta_t deltaMicros
, int32_t navHeadingError
, bool errorIsDecreasing
) {
361 static float limit
= 0.0f
;
364 limit
= pidProfile()->navFwPosHdgPidsumLimit
* 100.0f
;
367 const pidControllerFlags_e yawPidFlags
= errorIsDecreasing
? PID_SHRINK_INTEGRATOR
: 0;
369 const float yawAdjustment
= navPidApply2(
370 &posControl
.pids
.fw_heading
,
372 applyDeadband(navHeadingError
, navConfig()->fw
.yawControlDeadband
* 100),
379 DEBUG_SET(DEBUG_NAV_YAW
, 0, posControl
.pids
.fw_heading
.proportional
);
380 DEBUG_SET(DEBUG_NAV_YAW
, 1, posControl
.pids
.fw_heading
.integral
);
381 DEBUG_SET(DEBUG_NAV_YAW
, 2, posControl
.pids
.fw_heading
.derivative
);
382 DEBUG_SET(DEBUG_NAV_YAW
, 3, navHeadingError
);
383 DEBUG_SET(DEBUG_NAV_YAW
, 4, posControl
.pids
.fw_heading
.output_constrained
);
385 return yawAdjustment
;
388 static void updatePositionHeadingController_FW(timeUs_t currentTimeUs
, timeDelta_t deltaMicros
)
390 static timeUs_t previousTimeMonitoringUpdate
;
391 static int32_t previousHeadingError
;
392 static bool errorIsDecreasing
;
393 static bool forceTurnDirection
= false;
395 // We have virtual position target, calculate heading error
396 int32_t virtualTargetBearing
= calculateBearingToDestination(&virtualDesiredPosition
);
398 /* If waypoint tracking enabled quickly force craft toward waypoint course line and closely track along it */
399 if (navConfig()->fw
.wp_tracking_accuracy
&& isWaypointNavTrackingActive() && !needToCalculateCircularLoiter
) {
400 // courseVirtualCorrection initially used to determine current position relative to course line for later use
401 int32_t courseVirtualCorrection
= wrap_18000(posControl
.activeWaypoint
.yaw
- virtualTargetBearing
);
402 navCrossTrackError
= ABS(posControl
.wpDistance
* sin_approx(CENTIDEGREES_TO_RADIANS(courseVirtualCorrection
)));
404 // tracking only active when certain distance and heading conditions are met
405 if ((ABS(wrap_18000(virtualTargetBearing
- posControl
.actualState
.yaw
)) < 9000 || posControl
.wpDistance
< 1000.0f
) && navCrossTrackError
> 200) {
406 int32_t courseHeadingError
= wrap_18000(posControl
.activeWaypoint
.yaw
- posControl
.actualState
.yaw
);
408 // captureFactor adjusts distance/heading sensitivity balance when closing in on course line.
409 // Closing distance threashold based on speed and an assumed 1 second response time.
410 float captureFactor
= navCrossTrackError
< posControl
.actualState
.velXY
? constrainf(2.0f
- ABS(courseHeadingError
) / 500.0f
, 0.0f
, 2.0f
) : 1.0f
;
412 // bias between reducing distance to course line and aligning with course heading adjusted by waypoint_tracking_accuracy
413 // initial courseCorrectionFactor based on distance to course line
414 float courseCorrectionFactor
= constrainf(captureFactor
* navCrossTrackError
/ (1000.0f
* navConfig()->fw
.wp_tracking_accuracy
), 0.0f
, 1.0f
);
415 courseCorrectionFactor
= courseVirtualCorrection
< 0 ? -courseCorrectionFactor
: courseCorrectionFactor
;
417 // course heading alignment factor
418 float courseHeadingFactor
= constrainf(courseHeadingError
/ 18000.0f
, 0.0f
, 1.0f
);
419 courseHeadingFactor
= courseHeadingError
< 0 ? -courseHeadingFactor
: courseHeadingFactor
;
421 // final courseCorrectionFactor combining distance and heading factors
422 courseCorrectionFactor
= constrainf(courseCorrectionFactor
- courseHeadingFactor
, -1.0f
, 1.0f
);
424 // final courseVirtualCorrection value
425 courseVirtualCorrection
= DEGREES_TO_CENTIDEGREES(navConfig()->fw
.wp_tracking_max_angle
) * courseCorrectionFactor
;
426 virtualTargetBearing
= wrap_36000(posControl
.activeWaypoint
.yaw
- courseVirtualCorrection
);
431 * Calculate NAV heading error
432 * Units are centidegrees
434 navHeadingError
= wrap_18000(virtualTargetBearing
- posControl
.actualState
.yaw
);
436 // Forced turn direction
437 // If heading error is close to 180 deg we initiate forced turn and only disable it when heading error goes below 90 deg
438 if (ABS(navHeadingError
) > 17000) {
439 forceTurnDirection
= true;
441 else if (ABS(navHeadingError
) < 9000 && forceTurnDirection
) {
442 forceTurnDirection
= false;
445 // If forced turn direction flag is enabled we fix the sign of the direction
446 if (forceTurnDirection
) {
447 navHeadingError
= loiterDirection() * ABS(navHeadingError
);
450 // Slow error monitoring (2Hz rate)
451 if ((currentTimeUs
- previousTimeMonitoringUpdate
) >= HZ2US(NAV_FW_CONTROL_MONITORING_RATE
)) {
452 // Check if error is decreasing over time
453 errorIsDecreasing
= (ABS(previousHeadingError
) > ABS(navHeadingError
));
455 // Save values for next iteration
456 previousHeadingError
= navHeadingError
;
457 previousTimeMonitoringUpdate
= currentTimeUs
;
460 // Only allow PID integrator to shrink if error is decreasing over time
461 const pidControllerFlags_e pidFlags
= PID_DTERM_FROM_ERROR
| (errorIsDecreasing
? PID_SHRINK_INTEGRATOR
: 0);
463 // Input error in (deg*100), output roll angle (deg*100)
464 float rollAdjustment
= navPidApply2(&posControl
.pids
.fw_nav
, posControl
.actualState
.yaw
+ navHeadingError
, posControl
.actualState
.yaw
, US2S(deltaMicros
),
465 -DEGREES_TO_CENTIDEGREES(navConfig()->fw
.max_bank_angle
),
466 DEGREES_TO_CENTIDEGREES(navConfig()->fw
.max_bank_angle
),
469 // Apply low-pass filter to prevent rapid correction
470 rollAdjustment
= pt1FilterApply4(&fwPosControllerCorrectionFilterState
, rollAdjustment
, getSmoothnessCutoffFreq(NAV_FW_BASE_ROLL_CUTOFF_FREQUENCY_HZ
), US2S(deltaMicros
));
472 // Convert rollAdjustment to decidegrees (rcAdjustment holds decidegrees)
473 posControl
.rcAdjustment
[ROLL
] = CENTIDEGREES_TO_DECIDEGREES(rollAdjustment
);
477 * It is working in relative mode and we aim to keep error at zero
479 if (STATE(FW_HEADING_USE_YAW
)) {
480 posControl
.rcAdjustment
[YAW
] = processHeadingYawController(deltaMicros
, navHeadingError
, errorIsDecreasing
);
482 posControl
.rcAdjustment
[YAW
] = 0;
486 void applyFixedWingPositionController(timeUs_t currentTimeUs
)
488 static timeUs_t previousTimePositionUpdate
= 0; // Occurs @ GPS update rate
490 // Apply controller only if position source is valid. In absence of valid pos sensor (GPS loss), we'd stick in forced ANGLE mode
491 if ((posControl
.flags
.estPosStatus
>= EST_USABLE
)) {
492 // If we have new position - update velocity and acceleration controllers
493 if (posControl
.flags
.horizontalPositionDataNew
) {
494 const timeDeltaLarge_t deltaMicrosPositionUpdate
= currentTimeUs
- previousTimePositionUpdate
;
495 previousTimePositionUpdate
= currentTimeUs
;
497 if (deltaMicrosPositionUpdate
< MAX_POSITION_UPDATE_INTERVAL_US
) {
498 // Calculate virtual position target at a distance of forwardVelocity * HZ2S(POSITION_TARGET_UPDATE_RATE_HZ)
499 // Account for pilot's roll input (move position target left/right at max of max_manual_speed)
500 // POSITION_TARGET_UPDATE_RATE_HZ should be chosen keeping in mind that position target shouldn't be reached until next pos update occurs
501 // FIXME: verify the above
502 calculateVirtualPositionTarget_FW(HZ2S(MIN_POSITION_UPDATE_RATE_HZ
) * 2);
504 updatePositionHeadingController_FW(currentTimeUs
, deltaMicrosPositionUpdate
);
507 // Position update has not occurred in time (first iteration or glitch), reset altitude controller
508 resetFixedWingPositionController();
511 // Indicate that information is no longer usable
512 posControl
.flags
.horizontalPositionDataConsumed
= true;
515 isRollAdjustmentValid
= true;
516 isYawAdjustmentValid
= true;
519 // No valid pos sensor data, don't adjust pitch automatically, rcCommand[ROLL] is passed through to PID controller
520 isRollAdjustmentValid
= false;
521 isYawAdjustmentValid
= false;
525 int16_t applyFixedWingMinSpeedController(timeUs_t currentTimeUs
)
527 static timeUs_t previousTimePositionUpdate
= 0; // Occurs @ GPS update rate
529 // Apply controller only if position source is valid
530 if ((posControl
.flags
.estPosStatus
>= EST_USABLE
)) {
531 // If we have new position - update velocity and acceleration controllers
532 if (posControl
.flags
.horizontalPositionDataNew
) {
533 const timeDeltaLarge_t deltaMicrosPositionUpdate
= currentTimeUs
- previousTimePositionUpdate
;
534 previousTimePositionUpdate
= currentTimeUs
;
536 if (deltaMicrosPositionUpdate
< MAX_POSITION_UPDATE_INTERVAL_US
) {
537 float velThrottleBoost
= (NAV_FW_MIN_VEL_SPEED_BOOST
- posControl
.actualState
.velXY
) * NAV_FW_THROTTLE_SPEED_BOOST_GAIN
* US2S(deltaMicrosPositionUpdate
);
539 // If we are in the deadband of 50cm/s - don't update speed boost
540 if (fabsf(posControl
.actualState
.velXY
- NAV_FW_MIN_VEL_SPEED_BOOST
) > 50) {
541 throttleSpeedAdjustment
+= velThrottleBoost
;
544 throttleSpeedAdjustment
= constrainf(throttleSpeedAdjustment
, 0.0f
, 500.0f
);
547 // Position update has not occurred in time (first iteration or glitch), reset altitude controller
548 throttleSpeedAdjustment
= 0;
551 // Indicate that information is no longer usable
552 posControl
.flags
.horizontalPositionDataConsumed
= true;
556 // No valid pos sensor data, we can't calculate speed
557 throttleSpeedAdjustment
= 0;
560 return throttleSpeedAdjustment
;
563 int16_t fixedWingPitchToThrottleCorrection(int16_t pitch
, timeUs_t currentTimeUs
)
565 static timeUs_t previousTimePitchToThrCorr
= 0;
566 const timeDeltaLarge_t deltaMicrosPitchToThrCorr
= currentTimeUs
- previousTimePitchToThrCorr
;
567 previousTimePitchToThrCorr
= currentTimeUs
;
569 static pt1Filter_t pitchToThrFilterState
;
571 // Apply low-pass filter to pitch angle to smooth throttle correction
572 int16_t filteredPitch
= (int16_t)pt1FilterApply4(&pitchToThrFilterState
, pitch
, getPitchToThrottleSmoothnessCutoffFreq(NAV_FW_BASE_PITCH_CUTOFF_FREQUENCY_HZ
), US2S(deltaMicrosPitchToThrCorr
));
574 if (ABS(pitch
- filteredPitch
) > navConfig()->fw
.pitch_to_throttle_thresh
) {
575 // Unfiltered throttle correction outside of pitch deadband
576 return DECIDEGREES_TO_DEGREES(pitch
) * currentBatteryProfile
->nav
.fw
.pitch_to_throttle
;
579 // Filtered throttle correction inside of pitch deadband
580 return DECIDEGREES_TO_DEGREES(filteredPitch
) * currentBatteryProfile
->nav
.fw
.pitch_to_throttle
;
584 void applyFixedWingPitchRollThrottleController(navigationFSMStateFlags_t navStateFlags
, timeUs_t currentTimeUs
)
586 int16_t minThrottleCorrection
= currentBatteryProfile
->nav
.fw
.min_throttle
- currentBatteryProfile
->nav
.fw
.cruise_throttle
;
587 int16_t maxThrottleCorrection
= currentBatteryProfile
->nav
.fw
.max_throttle
- currentBatteryProfile
->nav
.fw
.cruise_throttle
;
589 if (isRollAdjustmentValid
&& (navStateFlags
& NAV_CTL_POS
)) {
590 // ROLL >0 right, <0 left
591 int16_t rollCorrection
= constrain(posControl
.rcAdjustment
[ROLL
], -DEGREES_TO_DECIDEGREES(navConfig()->fw
.max_bank_angle
), DEGREES_TO_DECIDEGREES(navConfig()->fw
.max_bank_angle
));
592 rcCommand
[ROLL
] = pidAngleToRcCommand(rollCorrection
, pidProfile()->max_angle_inclination
[FD_ROLL
]);
595 if (isYawAdjustmentValid
&& (navStateFlags
& NAV_CTL_POS
)) {
596 rcCommand
[YAW
] = posControl
.rcAdjustment
[YAW
];
599 if (isPitchAdjustmentValid
&& (navStateFlags
& NAV_CTL_ALT
)) {
600 // PITCH >0 dive, <0 climb
601 int16_t pitchCorrection
= constrain(posControl
.rcAdjustment
[PITCH
], -DEGREES_TO_DECIDEGREES(navConfig()->fw
.max_dive_angle
), DEGREES_TO_DECIDEGREES(navConfig()->fw
.max_climb_angle
));
602 rcCommand
[PITCH
] = -pidAngleToRcCommand(pitchCorrection
, pidProfile()->max_angle_inclination
[FD_PITCH
]);
603 int16_t throttleCorrection
= fixedWingPitchToThrottleCorrection(pitchCorrection
, currentTimeUs
);
605 #ifdef NAV_FIXED_WING_LANDING
606 if (navStateFlags
& NAV_CTL_LAND
) {
607 // During LAND we do not allow to raise THROTTLE when nose is up to reduce speed
608 throttleCorrection
= constrain(throttleCorrection
, minThrottleCorrection
, 0);
611 throttleCorrection
= constrain(throttleCorrection
, minThrottleCorrection
, maxThrottleCorrection
);
612 #ifdef NAV_FIXED_WING_LANDING
616 // Speed controller - only apply in POS mode when NOT NAV_CTL_LAND
617 if ((navStateFlags
& NAV_CTL_POS
) && !(navStateFlags
& NAV_CTL_LAND
)) {
618 throttleCorrection
+= applyFixedWingMinSpeedController(currentTimeUs
);
619 throttleCorrection
= constrain(throttleCorrection
, minThrottleCorrection
, maxThrottleCorrection
);
622 uint16_t correctedThrottleValue
= constrain(currentBatteryProfile
->nav
.fw
.cruise_throttle
+ throttleCorrection
, currentBatteryProfile
->nav
.fw
.min_throttle
, currentBatteryProfile
->nav
.fw
.max_throttle
);
624 // Manual throttle increase
625 if (navConfig()->fw
.allow_manual_thr_increase
&& !FLIGHT_MODE(FAILSAFE_MODE
)) {
626 if (rcCommand
[THROTTLE
] < PWM_RANGE_MIN
+ (PWM_RANGE_MAX
- PWM_RANGE_MIN
) * 0.95){
627 correctedThrottleValue
+= MAX(0, rcCommand
[THROTTLE
] - currentBatteryProfile
->nav
.fw
.cruise_throttle
);
629 correctedThrottleValue
= motorConfig()->maxthrottle
;
631 isAutoThrottleManuallyIncreased
= (rcCommand
[THROTTLE
] > currentBatteryProfile
->nav
.fw
.cruise_throttle
);
633 isAutoThrottleManuallyIncreased
= false;
636 rcCommand
[THROTTLE
] = constrain(correctedThrottleValue
, getThrottleIdleValue(), motorConfig()->maxthrottle
);
639 #ifdef NAV_FIXED_WING_LANDING
641 * Then altitude is below landing slowdown min. altitude, enable final approach procedure
642 * TODO refactor conditions in this metod if logic is proven to be correct
644 if (navStateFlags
& NAV_CTL_LAND
|| STATE(LANDING_DETECTED
)) {
645 int32_t finalAltitude
= navConfig()->general
.land_slowdown_minalt
+ posControl
.rthState
.homeTmpWaypoint
.z
;
647 if ((posControl
.flags
.estAltStatus
>= EST_USABLE
&& navGetCurrentActualPositionAndVelocity()->pos
.z
<= finalAltitude
) ||
648 (posControl
.flags
.estAglStatus
== EST_TRUSTED
&& posControl
.actualState
.agl
.pos
.z
<= navConfig()->general
.land_slowdown_minalt
)) {
650 // Set motor to min. throttle and stop it when MOTOR_STOP feature is enabled
651 rcCommand
[THROTTLE
] = getThrottleIdleValue();
652 ENABLE_STATE(NAV_MOTOR_STOP_OR_IDLE
);
654 // Stabilize ROLL axis on 0 degrees banking regardless of loiter radius and position
657 // Stabilize PITCH angle into shallow dive as specified by the nav_fw_land_dive_angle setting (default value is 2 - defined in navigation.c).
658 rcCommand
[PITCH
] = pidAngleToRcCommand(DEGREES_TO_DECIDEGREES(navConfig()->fw
.land_dive_angle
), pidProfile()->max_angle_inclination
[FD_PITCH
]);
664 bool isFixedWingAutoThrottleManuallyIncreased()
666 return isAutoThrottleManuallyIncreased
;
669 bool isFixedWingFlying(void)
671 float airspeed
= 0.0f
;
673 airspeed
= getAirspeedEstimate();
675 bool throttleCondition
= getMotorCount() == 0 || rcCommand
[THROTTLE
] > currentBatteryProfile
->nav
.fw
.cruise_throttle
;
676 bool velCondition
= posControl
.actualState
.velXY
> 250.0f
|| airspeed
> 250.0f
;
677 bool launchCondition
= isNavLaunchEnabled() && fixedWingLaunchStatus() == FW_LAUNCH_FLYING
;
679 return (isImuHeadingValid() && throttleCondition
&& velCondition
) || launchCondition
;
682 /*-----------------------------------------------------------
683 * FixedWing land detector
684 *-----------------------------------------------------------*/
685 bool isFixedWingLandingDetected(void)
687 DEBUG_SET(DEBUG_LANDING
, 4, 0);
688 static bool fixAxisCheck
= false;
689 const bool throttleIsLow
= calculateThrottleStatus(THROTTLE_STATUS_TYPE_RC
) == THROTTLE_LOW
;
691 // Basic condition to start looking for landing
692 bool startCondition
= (navGetCurrentStateFlags() & (NAV_CTL_LAND
| NAV_CTL_EMERG
))
693 || FLIGHT_MODE(FAILSAFE_MODE
)
694 || (!navigationIsControllingThrottle() && throttleIsLow
);
696 if (!startCondition
|| posControl
.flags
.resetLandingDetector
) {
697 return fixAxisCheck
= posControl
.flags
.resetLandingDetector
= false;
699 DEBUG_SET(DEBUG_LANDING
, 4, 1);
701 static timeMs_t fwLandingTimerStartAt
;
702 static int16_t fwLandSetRollDatum
;
703 static int16_t fwLandSetPitchDatum
;
704 const float sensitivity
= navConfig()->general
.land_detect_sensitivity
/ 5.0f
;
706 timeMs_t currentTimeMs
= millis();
708 // Check horizontal and vertical velocities are low (cm/s)
709 bool velCondition
= fabsf(navGetCurrentActualPositionAndVelocity()->vel
.z
) < (50.0f
* sensitivity
) &&
710 posControl
.actualState
.velXY
< (100.0f
* sensitivity
);
711 // Check angular rates are low (degs/s)
712 bool gyroCondition
= averageAbsGyroRates() < (2.0f
* sensitivity
);
713 DEBUG_SET(DEBUG_LANDING
, 2, velCondition
);
714 DEBUG_SET(DEBUG_LANDING
, 3, gyroCondition
);
716 if (velCondition
&& gyroCondition
){
717 DEBUG_SET(DEBUG_LANDING
, 4, 2);
718 DEBUG_SET(DEBUG_LANDING
, 5, fixAxisCheck
);
719 if (!fixAxisCheck
) { // capture roll and pitch angles to be used as datums to check for absolute change
720 fwLandSetRollDatum
= attitude
.values
.roll
; //0.1 deg increments
721 fwLandSetPitchDatum
= attitude
.values
.pitch
;
723 fwLandingTimerStartAt
= currentTimeMs
;
725 const uint8_t angleLimit
= 5 * sensitivity
;
726 bool isRollAxisStatic
= ABS(fwLandSetRollDatum
- attitude
.values
.roll
) < angleLimit
;
727 bool isPitchAxisStatic
= ABS(fwLandSetPitchDatum
- attitude
.values
.pitch
) < angleLimit
;
728 DEBUG_SET(DEBUG_LANDING
, 6, isRollAxisStatic
);
729 DEBUG_SET(DEBUG_LANDING
, 7, isPitchAxisStatic
);
730 if (isRollAxisStatic
&& isPitchAxisStatic
) {
731 // Probably landed, low horizontal and vertical velocities and no axis rotation in Roll and Pitch
732 timeMs_t safetyTimeDelay
= 2000 + navConfig()->general
.auto_disarm_delay
;
733 return currentTimeMs
- fwLandingTimerStartAt
> safetyTimeDelay
; // check conditions stable for 2s + optional extra delay
735 fixAxisCheck
= false;
742 /*-----------------------------------------------------------
743 * FixedWing emergency landing
744 *-----------------------------------------------------------*/
745 void applyFixedWingEmergencyLandingController(timeUs_t currentTimeUs
)
747 rcCommand
[ROLL
] = pidAngleToRcCommand(failsafeConfig()->failsafe_fw_roll_angle
, pidProfile()->max_angle_inclination
[FD_ROLL
]);
748 rcCommand
[YAW
] = -pidRateToRcCommand(failsafeConfig()->failsafe_fw_yaw_rate
, currentControlRateProfile
->stabilized
.rates
[FD_YAW
]);
749 rcCommand
[THROTTLE
] = currentBatteryProfile
->failsafe_throttle
;
751 if (posControl
.flags
.estAltStatus
>= EST_USABLE
) {
752 updateClimbRateToAltitudeController(-1.0f
* navConfig()->general
.emerg_descent_rate
, ROC_TO_ALT_NORMAL
);
753 applyFixedWingAltitudeAndThrottleController(currentTimeUs
);
755 int16_t pitchCorrection
= constrain(posControl
.rcAdjustment
[PITCH
], -DEGREES_TO_DECIDEGREES(navConfig()->fw
.max_dive_angle
), DEGREES_TO_DECIDEGREES(navConfig()->fw
.max_climb_angle
));
756 rcCommand
[PITCH
] = -pidAngleToRcCommand(pitchCorrection
, pidProfile()->max_angle_inclination
[FD_PITCH
]);
758 rcCommand
[PITCH
] = pidAngleToRcCommand(failsafeConfig()->failsafe_fw_pitch_angle
, pidProfile()->max_angle_inclination
[FD_PITCH
]);
762 /*-----------------------------------------------------------
763 * Calculate loiter target based on current position and velocity
764 *-----------------------------------------------------------*/
765 void calculateFixedWingInitialHoldPosition(fpVector3_t
* pos
)
767 // TODO: stub, this should account for velocity and target loiter radius
768 *pos
= navGetCurrentActualPositionAndVelocity()->pos
;
771 void resetFixedWingHeadingController(void)
773 updateHeadingHoldTarget(CENTIDEGREES_TO_DEGREES(posControl
.actualState
.yaw
));
776 void applyFixedWingNavigationController(navigationFSMStateFlags_t navStateFlags
, timeUs_t currentTimeUs
)
778 if (navStateFlags
& NAV_CTL_LAUNCH
) {
779 applyFixedWingLaunchController(currentTimeUs
);
781 else if (navStateFlags
& NAV_CTL_EMERG
) {
782 applyFixedWingEmergencyLandingController(currentTimeUs
);
785 #ifdef NAV_FW_LIMIT_MIN_FLY_VELOCITY
786 // Don't apply anything if ground speed is too low (<3m/s)
787 if (posControl
.actualState
.velXY
> 300) {
791 if (navStateFlags
& NAV_CTL_ALT
) {
792 if (getMotorStatus() == MOTOR_STOPPED_USER
|| FLIGHT_MODE(SOARING_MODE
)) {
793 // Motor has been stopped by user or soaring mode enabled to override altitude control
794 resetFixedWingAltitudeController();
795 setDesiredPosition(&navGetCurrentActualPositionAndVelocity()->pos
, posControl
.actualState
.yaw
, NAV_POS_UPDATE_Z
);
797 applyFixedWingAltitudeAndThrottleController(currentTimeUs
);
801 if (navStateFlags
& NAV_CTL_POS
) {
802 applyFixedWingPositionController(currentTimeUs
);
806 posControl
.rcAdjustment
[PITCH
] = 0;
807 posControl
.rcAdjustment
[ROLL
] = 0;
810 if (FLIGHT_MODE(NAV_COURSE_HOLD_MODE
) && posControl
.flags
.isAdjustingPosition
) {
811 rcCommand
[ROLL
] = applyDeadbandRescaled(rcCommand
[ROLL
], rcControlsConfig()->pos_hold_deadband
, -500, 500);
814 //if (navStateFlags & NAV_CTL_YAW)
815 if ((navStateFlags
& NAV_CTL_ALT
) || (navStateFlags
& NAV_CTL_POS
)) {
816 applyFixedWingPitchRollThrottleController(navStateFlags
, currentTimeUs
);
819 if (FLIGHT_MODE(SOARING_MODE
) && navConfig()->general
.flags
.soaring_motor_stop
) {
820 ENABLE_STATE(NAV_MOTOR_STOP_OR_IDLE
);
825 int32_t navigationGetHeadingError(void)
827 return navHeadingError
;
830 float navigationGetCrossTrackError(void)
832 return navCrossTrackError
;