2 ******************************************************************************
3 * @addtogroup OpenPilotModules OpenPilot Modules
5 * @addtogroup ActuatorModule Actuator Module
6 * @brief Compute servo/motor settings based on @ref ActuatorDesired "desired actuator positions" and aircraft type.
7 * This is where all the mixing of channels is computed.
11 * @author The LibrePilot Project, http://www.librepilot.org Copyright (C) 2015.
12 * The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
13 * @brief Actuator module. Drives the actuators (servos, motors etc).
15 * @see The GNU Public License (GPL) Version 3
17 *****************************************************************************/
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 3 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful, but
25 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
26 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
29 * You should have received a copy of the GNU General Public License along
30 * with this program; if not, write to the Free Software Foundation, Inc.,
31 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
35 #include <openpilot.h>
37 #include "accessorydesired.h"
39 #include "actuatorsettings.h"
40 #include "systemsettings.h"
41 #include "actuatordesired.h"
42 #include "actuatorcommand.h"
43 #include "flightstatus.h"
44 #include <flightmodesettings.h>
45 #include "mixersettings.h"
46 #include "mixerstatus.h"
47 #include "cameradesired.h"
48 #include "hwsettings.h"
49 #include "manualcontrolcommand.h"
51 #include <systemsettings.h>
52 #include <sanitycheck.h>
53 #ifndef PIOS_EXCLUDE_ADVANCED_FEATURES
54 #include <vtolpathfollowersettings.h>
56 #undef PIOS_INCLUDE_INSTRUMENTATION
57 #ifdef PIOS_INCLUDE_INSTRUMENTATION
58 #include <pios_instrumentation.h>
59 static int8_t counter
;
60 // Counter 0xAC700001 total Actuator body execution time(excluding queue waits etc).
64 #define MAX_QUEUE_SIZE 2
66 #if defined(PIOS_ACTUATOR_STACK_SIZE)
67 #define STACK_SIZE_BYTES PIOS_ACTUATOR_STACK_SIZE
69 #define STACK_SIZE_BYTES 1312
72 #define TASK_PRIORITY (tskIDLE_PRIORITY + 4) // device driver
73 #define FAILSAFE_TIMEOUT_MS 100
74 #define MAX_MIX_ACTUATORS ACTUATORCOMMAND_CHANNEL_NUMELEM
76 #define CAMERA_BOOT_DELAY_MS 7000
78 #define ACTUATOR_ONESHOT_CLOCK 12000000
79 #define ACTUATOR_ONESHOT125_PULSE_FACTOR 1.5f
80 #define ACTUATOR_ONESHOT42_PULSE_FACTOR 0.5f
81 #define ACTUATOR_MULTISHOT_PULSE_FACTOR 0.24f
82 #define ACTUATOR_PWM_CLOCK 1000000
87 static xQueueHandle queue
;
88 static xTaskHandle taskHandle
;
89 static FrameType_t frameType
= FRAME_TYPE_MULTIROTOR
;
90 static SystemSettingsThrustControlOptions thrustType
= SYSTEMSETTINGS_THRUSTCONTROL_THROTTLE
;
91 static bool camStabEnabled
;
92 static bool camControlEnabled
;
94 static uint8_t pinsMode
[MAX_MIX_ACTUATORS
];
95 // used to inform the actuator thread that actuator update rate is changed
96 static ActuatorSettingsData actuatorSettings
;
97 static bool spinWhileArmed
;
99 // used to inform the actuator thread that mixer settings are changed
100 static MixerSettingsData mixerSettings
;
101 static int mixer_settings_count
= 2;
104 static void actuatorTask(void *parameters
);
105 static int16_t scaleChannel(float value
, int16_t max
, int16_t min
, int16_t neutral
);
106 static int16_t scaleMotor(float value
, int16_t max
, int16_t min
, int16_t neutral
, float maxMotor
, float minMotor
, bool armed
, bool alwaysStabilizeWhenArmed
, float throttleDesired
);
107 static void setFailsafe();
108 static float MixerCurveFullRangeProportional(const float input
, const float *curve
, uint8_t elements
, bool multirotor
);
109 static float MixerCurveFullRangeAbsolute(const float input
, const float *curve
, uint8_t elements
, bool multirotor
);
110 static bool set_channel(uint8_t mixer_channel
, uint16_t value
);
111 static void actuator_update_rate_if_changed(bool force_update
);
112 static void MixerSettingsUpdatedCb(UAVObjEvent
*ev
);
113 static void ActuatorSettingsUpdatedCb(UAVObjEvent
*ev
);
114 static void SettingsUpdatedCb(UAVObjEvent
*ev
);
115 float ProcessMixer(const int index
, const float curve1
, const float curve2
,
116 ActuatorDesiredData
*desired
,
117 bool multirotor
, bool fixedwing
);
119 // this structure is equivalent to the UAVObjects for one mixer.
123 } __attribute__((packed
)) Mixer_t
;
126 * @brief Module initialization
129 int32_t ActuatorStart()
132 xTaskCreate(actuatorTask
, "Actuator", STACK_SIZE_BYTES
/ 4, NULL
, TASK_PRIORITY
, &taskHandle
);
133 PIOS_TASK_MONITOR_RegisterTask(TASKINFO_RUNNING_ACTUATOR
, taskHandle
);
134 #ifdef PIOS_INCLUDE_WDG
135 PIOS_WDG_RegisterFlag(PIOS_WDG_ACTUATOR
);
137 SettingsUpdatedCb(NULL
);
138 MixerSettingsUpdatedCb(NULL
);
139 ActuatorSettingsUpdatedCb(NULL
);
144 * @brief Module initialization
147 int32_t ActuatorInitialize()
149 // Register for notification of changes to ActuatorSettings
150 ActuatorSettingsInitialize();
151 ActuatorSettingsConnectCallback(ActuatorSettingsUpdatedCb
);
153 // Register for notification of changes to MixerSettings
154 MixerSettingsInitialize();
155 MixerSettingsConnectCallback(MixerSettingsUpdatedCb
);
157 // Listen for ActuatorDesired updates (Primary input to this module)
158 ActuatorDesiredInitialize();
159 queue
= xQueueCreate(MAX_QUEUE_SIZE
, sizeof(UAVObjEvent
));
160 ActuatorDesiredConnectQueue(queue
);
162 // Register AccessoryDesired (Secondary input to this module)
163 AccessoryDesiredInitialize();
165 // Check if CameraStab module is enabled
166 HwSettingsOptionalModulesData optionalModules
;
167 HwSettingsInitialize();
168 HwSettingsOptionalModulesGet(&optionalModules
);
169 camStabEnabled
= (optionalModules
.CameraStab
== HWSETTINGS_OPTIONALMODULES_ENABLED
);
170 camControlEnabled
= (optionalModules
.CameraControl
== HWSETTINGS_OPTIONALMODULES_ENABLED
);
171 // Primary output of this module
172 ActuatorCommandInitialize();
174 #ifdef DIAG_MIXERSTATUS
175 // UAVO only used for inspecting the internal status of the mixer during debug
176 MixerStatusInitialize();
179 #ifndef PIOS_EXCLUDE_ADVANCED_FEATURES
180 VtolPathFollowerSettingsInitialize();
181 VtolPathFollowerSettingsConnectCallback(&SettingsUpdatedCb
);
183 SystemSettingsInitialize();
184 SystemSettingsConnectCallback(&SettingsUpdatedCb
);
188 MODULE_INITCALL(ActuatorInitialize
, ActuatorStart
);
191 * @brief Main Actuator module task
193 * Universal matrix based mixer for VTOL, helis and fixed wing.
194 * Converts desired roll,pitch,yaw and throttle to servo/ESC outputs.
196 * Because of how the Throttle ranges from 0 to 1, the motors should too!
198 * Note this code depends on the UAVObjects for the mixers being all being the same
199 * and in sequence. If you change the object definition, make sure you check the code!
201 * @return -1 if error, 0 if success
203 static void actuatorTask(__attribute__((unused
)) void *parameters
)
206 portTickType lastSysTime
;
207 portTickType thisSysTime
;
208 uint32_t dTMilliseconds
;
210 ActuatorCommandData command
;
211 ActuatorDesiredData desired
;
212 MixerStatusData mixerStatus
;
213 FlightModeSettingsData settings
;
214 FlightStatusData flightStatus
;
215 float throttleDesired
;
216 float collectiveDesired
;
218 #ifdef PIOS_INCLUDE_INSTRUMENTATION
219 counter
= PIOS_Instrumentation_CreateCounter(0xAC700001);
221 /* Read initial values of ActuatorSettings */
223 ActuatorSettingsGet(&actuatorSettings
);
225 /* Read initial values of MixerSettings */
226 MixerSettingsGet(&mixerSettings
);
228 /* Force an initial configuration of the actuator update rates */
229 actuator_update_rate_if_changed(true);
231 // Go to the neutral (failsafe) values until an ActuatorDesired update is received
235 lastSysTime
= xTaskGetTickCount();
237 #ifdef PIOS_INCLUDE_WDG
238 PIOS_WDG_UpdateFlag(PIOS_WDG_ACTUATOR
);
241 // Wait until the ActuatorDesired object is updated
242 uint8_t rc
= xQueueReceive(queue
, &ev
, FAILSAFE_TIMEOUT_MS
/ portTICK_RATE_MS
);
243 #ifdef PIOS_INCLUDE_INSTRUMENTATION
244 PIOS_Instrumentation_TimeStart(counter
);
248 /* Update of ActuatorDesired timed out. Go to failsafe */
253 // Check how long since last update
254 thisSysTime
= xTaskGetTickCount();
255 dTMilliseconds
= (thisSysTime
== lastSysTime
) ? 1 : (thisSysTime
- lastSysTime
) * portTICK_RATE_MS
;
256 lastSysTime
= thisSysTime
;
258 FlightStatusGet(&flightStatus
);
259 FlightModeSettingsGet(&settings
);
260 ActuatorDesiredGet(&desired
);
261 ActuatorCommandGet(&command
);
263 // read in throttle and collective -demultiplex thrust
264 switch (thrustType
) {
265 case SYSTEMSETTINGS_THRUSTCONTROL_THROTTLE
:
266 throttleDesired
= desired
.Thrust
;
267 ManualControlCommandCollectiveGet(&collectiveDesired
);
269 case SYSTEMSETTINGS_THRUSTCONTROL_COLLECTIVE
:
270 ManualControlCommandThrottleGet(&throttleDesired
);
271 collectiveDesired
= desired
.Thrust
;
274 ManualControlCommandThrottleGet(&throttleDesired
);
275 ManualControlCommandCollectiveGet(&collectiveDesired
);
278 bool armed
= flightStatus
.Armed
== FLIGHTSTATUS_ARMED_ARMED
;
279 bool activeThrottle
= (throttleDesired
< -0.001f
|| throttleDesired
> 0.001f
); // for ground and reversible motors
280 bool positiveThrottle
= (throttleDesired
> 0.00f
);
281 bool multirotor
= (GetCurrentFrameType() == FRAME_TYPE_MULTIROTOR
); // check if frame is a multirotor.
282 bool fixedwing
= (GetCurrentFrameType() == FRAME_TYPE_FIXED_WING
); // check if frame is a fixedwing.
283 bool alwaysArmed
= settings
.Arming
== FLIGHTMODESETTINGS_ARMING_ALWAYSARMED
;
284 bool alwaysStabilizeWhenArmed
= flightStatus
.AlwaysStabilizeWhenArmed
== FLIGHTSTATUS_ALWAYSSTABILIZEWHENARMED_TRUE
;
287 alwaysStabilizeWhenArmed
= false; // Do not allow always stabilize when alwaysArmed is active. This is dangerous.
291 throttleDesired
= 0.00f
; // this also happens in scaleMotors as a per axis check
294 if ((frameType
== FRAME_TYPE_GROUND
&& !activeThrottle
) || (frameType
!= FRAME_TYPE_GROUND
&& throttleDesired
<= 0.00f
) || !armed
) {
295 // throttleDesired should never be 0 or go below 0.
296 // force set all other controls to zero if throttle is cut (previously set in Stabilization)
297 // todo: can probably remove this
298 if (!(multirotor
&& alwaysStabilizeWhenArmed
&& armed
)) { // we don't do this if this is a multirotor AND AlwaysStabilizeWhenArmed is true and the model is armed
299 if (actuatorSettings
.LowThrottleZeroAxis
.Roll
== ACTUATORSETTINGS_LOWTHROTTLEZEROAXIS_TRUE
) {
300 desired
.Roll
= 0.00f
;
302 if (actuatorSettings
.LowThrottleZeroAxis
.Pitch
== ACTUATORSETTINGS_LOWTHROTTLEZEROAXIS_TRUE
) {
303 desired
.Pitch
= 0.00f
;
305 if (actuatorSettings
.LowThrottleZeroAxis
.Yaw
== ACTUATORSETTINGS_LOWTHROTTLEZEROAXIS_TRUE
) {
311 #ifdef DIAG_MIXERSTATUS
312 MixerStatusGet(&mixerStatus
);
315 if ((mixer_settings_count
< 2) && !ActuatorCommandReadOnly()) { // Nothing can fly with less than two mixers.
320 AlarmsClear(SYSTEMALARMS_ALARM_ACTUATOR
);
322 float curve1
= 0.0f
; // curve 1 is the throttle curve applied to all motors.
325 // Interpolate curve 1 from throttleDesired as input.
326 // assume reversible motor/mixer initially. We can later reverse this. The difference is simply that -ve throttleDesired values
328 curve1
= MixerCurveFullRangeProportional(throttleDesired
, mixerSettings
.ThrottleCurve1
, MIXERSETTINGS_THROTTLECURVE1_NUMELEM
, multirotor
);
330 // The source for the secondary curve is selectable
331 AccessoryDesiredData accessory
;
332 uint8_t curve2Source
= mixerSettings
.Curve2Source
;
333 switch (curve2Source
) {
334 case MIXERSETTINGS_CURVE2SOURCE_THROTTLE
:
335 // assume reversible motor/mixer initially
336 curve2
= MixerCurveFullRangeProportional(throttleDesired
, mixerSettings
.ThrottleCurve2
, MIXERSETTINGS_THROTTLECURVE2_NUMELEM
, multirotor
);
338 case MIXERSETTINGS_CURVE2SOURCE_ROLL
:
339 // Throttle curve contribution the same for +ve vs -ve roll
341 curve2
= MixerCurveFullRangeProportional(desired
.Roll
, mixerSettings
.ThrottleCurve2
, MIXERSETTINGS_THROTTLECURVE2_NUMELEM
, multirotor
);
343 curve2
= MixerCurveFullRangeAbsolute(desired
.Roll
, mixerSettings
.ThrottleCurve2
, MIXERSETTINGS_THROTTLECURVE2_NUMELEM
, multirotor
);
346 case MIXERSETTINGS_CURVE2SOURCE_PITCH
:
347 // Throttle curve contribution the same for +ve vs -ve pitch
349 curve2
= MixerCurveFullRangeProportional(desired
.Pitch
, mixerSettings
.ThrottleCurve2
,
350 MIXERSETTINGS_THROTTLECURVE2_NUMELEM
, multirotor
);
352 curve2
= MixerCurveFullRangeAbsolute(desired
.Pitch
, mixerSettings
.ThrottleCurve2
,
353 MIXERSETTINGS_THROTTLECURVE2_NUMELEM
, multirotor
);
356 case MIXERSETTINGS_CURVE2SOURCE_YAW
:
357 // Throttle curve contribution the same for +ve vs -ve yaw
359 curve2
= MixerCurveFullRangeProportional(desired
.Yaw
, mixerSettings
.ThrottleCurve2
, MIXERSETTINGS_THROTTLECURVE2_NUMELEM
, multirotor
);
361 curve2
= MixerCurveFullRangeAbsolute(desired
.Yaw
, mixerSettings
.ThrottleCurve2
, MIXERSETTINGS_THROTTLECURVE2_NUMELEM
, multirotor
);
364 case MIXERSETTINGS_CURVE2SOURCE_COLLECTIVE
:
365 // assume reversible motor/mixer initially
366 curve2
= MixerCurveFullRangeProportional(collectiveDesired
, mixerSettings
.ThrottleCurve2
,
367 MIXERSETTINGS_THROTTLECURVE2_NUMELEM
, multirotor
);
369 case MIXERSETTINGS_CURVE2SOURCE_ACCESSORY0
:
370 case MIXERSETTINGS_CURVE2SOURCE_ACCESSORY1
:
371 case MIXERSETTINGS_CURVE2SOURCE_ACCESSORY2
:
372 case MIXERSETTINGS_CURVE2SOURCE_ACCESSORY3
:
373 case MIXERSETTINGS_CURVE2SOURCE_ACCESSORY4
:
374 case MIXERSETTINGS_CURVE2SOURCE_ACCESSORY5
:
375 if (AccessoryDesiredInstGet(mixerSettings
.Curve2Source
- MIXERSETTINGS_CURVE2SOURCE_ACCESSORY0
, &accessory
) == 0) {
376 // Throttle curve contribution the same for +ve vs -ve accessory....maybe not want we want.
377 curve2
= MixerCurveFullRangeAbsolute(accessory
.AccessoryVal
, mixerSettings
.ThrottleCurve2
, MIXERSETTINGS_THROTTLECURVE2_NUMELEM
, multirotor
);
387 float *status
= (float *)&mixerStatus
; // access status objects as an array of floats
388 Mixer_t
*mixers
= (Mixer_t
*)&mixerSettings
.Mixer1Type
;
389 float maxMotor
= -1.0f
; // highest motor value. Addition method needs this to be -1.0f, division method needs this to be 1.0f
390 float minMotor
= 1.0f
; // lowest motor value Addition method needs this to be 1.0f, division method needs this to be -1.0f
392 for (int ct
= 0; ct
< MAX_MIX_ACTUATORS
; ct
++) {
393 // During boot all camera actuators should be completely disabled (PWM pulse = 0).
394 // command.Channel[i] is reused below as a channel PWM activity flag:
395 // 0 - PWM disabled, >0 - PWM set to real mixer value using scaleChannel() later.
396 // Setting it to 1 by default means "Rescale this channel and enable PWM on its output".
397 command
.Channel
[ct
] = 1;
399 uint8_t mixer_type
= mixers
[ct
].type
;
401 if (mixer_type
== MIXERSETTINGS_MIXER1TYPE_DISABLED
) {
402 // Set to minimum if disabled. This is not the same as saying PWM pulse = 0 us
407 if ((mixer_type
== MIXERSETTINGS_MIXER1TYPE_MOTOR
)) {
408 float nonreversible_curve1
= curve1
;
409 float nonreversible_curve2
= curve2
;
410 if (nonreversible_curve1
< 0.0f
) {
411 nonreversible_curve1
= 0.0f
;
413 if (nonreversible_curve2
< 0.0f
) {
414 if (!multirotor
) { // allow negative throttle if multirotor. function scaleMotors handles the sanity checks.
415 nonreversible_curve2
= 0.0f
;
418 status
[ct
] = ProcessMixer(ct
, nonreversible_curve1
, nonreversible_curve2
, &desired
, multirotor
, fixedwing
);
419 // If not armed or motors aren't meant to spin all the time
421 (!spinWhileArmed
&& !positiveThrottle
)) {
422 status
[ct
] = -1; // force min throttle
424 // If armed meant to keep spinning,
425 else if ((spinWhileArmed
&& !positiveThrottle
) ||
429 // allow throttle values lower than 0 if multirotor.
430 // Values will be scaled to 0 if they need to be in the scaleMotor function
433 } else if (mixer_type
== MIXERSETTINGS_MIXER1TYPE_REVERSABLEMOTOR
) {
434 status
[ct
] = ProcessMixer(ct
, curve1
, curve2
, &desired
, multirotor
, fixedwing
);
435 // Reversable Motors are like Motors but go to neutral instead of minimum
436 // If not armed or motor is inactive - no "spinwhilearmed" for this engine type
437 if (!armed
|| !activeThrottle
) {
438 status
[ct
] = 0; // force neutral throttle
440 } else if (mixer_type
== MIXERSETTINGS_MIXER1TYPE_SERVO
) {
441 status
[ct
] = ProcessMixer(ct
, curve1
, curve2
, &desired
, multirotor
, fixedwing
);
445 // If an accessory channel is selected for direct bypass mode
446 // In this configuration the accessory channel is scaled and mapped
447 // directly to output. Note: THERE IS NO SAFETY CHECK HERE FOR ARMING
448 // these also will not be updated in failsafe mode. I'm not sure what
449 // the correct behavior is since it seems domain specific. I don't love
451 if ((mixer_type
>= MIXERSETTINGS_MIXER1TYPE_ACCESSORY0
) &&
452 (mixer_type
<= MIXERSETTINGS_MIXER1TYPE_ACCESSORY5
)) {
453 if (AccessoryDesiredInstGet(mixer_type
- MIXERSETTINGS_MIXER1TYPE_ACCESSORY0
, &accessory
) == 0) {
454 status
[ct
] = accessory
.AccessoryVal
;
460 if ((mixer_type
>= MIXERSETTINGS_MIXER1TYPE_CAMERAROLLORSERVO1
) &&
461 (mixer_type
<= MIXERSETTINGS_MIXER1TYPE_CAMERAYAW
)) {
462 if (camStabEnabled
) {
463 CameraDesiredData cameraDesired
;
464 CameraDesiredGet(&cameraDesired
);
465 switch (mixer_type
) {
466 case MIXERSETTINGS_MIXER1TYPE_CAMERAROLLORSERVO1
:
467 status
[ct
] = cameraDesired
.RollOrServo1
;
469 case MIXERSETTINGS_MIXER1TYPE_CAMERAPITCHORSERVO2
:
470 status
[ct
] = cameraDesired
.PitchOrServo2
;
472 case MIXERSETTINGS_MIXER1TYPE_CAMERAYAW
:
473 status
[ct
] = cameraDesired
.Yaw
;
482 // Disable camera actuators for CAMERA_BOOT_DELAY_MS after boot
483 if (thisSysTime
< (CAMERA_BOOT_DELAY_MS
/ portTICK_RATE_MS
)) {
484 command
.Channel
[ct
] = 0;
488 if (mixer_type
== MIXERSETTINGS_MIXER1TYPE_CAMERATRIGGER
) {
489 if (camControlEnabled
) {
490 CameraDesiredTriggerGet(&status
[ct
]);
497 // If mixer type is motor we need to find which motor has the highest value and which motor has the lowest value.
498 // For use in function scaleMotor
499 if (mixers
[ct
].type
== MIXERSETTINGS_MIXER1TYPE_MOTOR
) {
500 if (maxMotor
< status
[ct
]) {
501 maxMotor
= status
[ct
];
503 if (minMotor
> status
[ct
]) {
504 minMotor
= status
[ct
];
509 // Set real actuator output values scaling them from mixers. All channels
510 // will be set except explicitly disabled (which will have PWM pulse = 0).
511 for (int i
= 0; i
< MAX_MIX_ACTUATORS
; i
++) {
512 if (command
.Channel
[i
]) {
513 if (mixers
[i
].type
== MIXERSETTINGS_MIXER1TYPE_MOTOR
) { // If mixer is for a motor we need to find the highest value of all motors
514 command
.Channel
[i
] = scaleMotor(status
[i
],
515 actuatorSettings
.ChannelMax
[i
],
516 actuatorSettings
.ChannelMin
[i
],
517 actuatorSettings
.ChannelNeutral
[i
],
521 alwaysStabilizeWhenArmed
,
523 } else { // else we scale the channel
524 command
.Channel
[i
] = scaleChannel(status
[i
],
525 actuatorSettings
.ChannelMax
[i
],
526 actuatorSettings
.ChannelMin
[i
],
527 actuatorSettings
.ChannelNeutral
[i
]);
533 command
.UpdateTime
= dTMilliseconds
;
534 if (command
.UpdateTime
> command
.MaxUpdateTime
) {
535 command
.MaxUpdateTime
= command
.UpdateTime
;
537 // Update output object
538 ActuatorCommandSet(&command
);
539 // Update in case read only (eg. during servo configuration)
540 ActuatorCommandGet(&command
);
542 #ifdef DIAG_MIXERSTATUS
543 MixerStatusSet(&mixerStatus
);
547 // Update servo outputs
550 for (int n
= 0; n
< ACTUATORCOMMAND_CHANNEL_NUMELEM
; ++n
) {
551 success
&= set_channel(n
, command
.Channel
[n
]);
557 command
.NumFailedUpdates
++;
558 ActuatorCommandSet(&command
);
559 AlarmsSet(SYSTEMALARMS_ALARM_ACTUATOR
, SYSTEMALARMS_ALARM_CRITICAL
);
561 #ifdef PIOS_INCLUDE_INSTRUMENTATION
562 PIOS_Instrumentation_TimeEnd(counter
);
569 * Process mixing for one actuator
571 float ProcessMixer(const int index
, const float curve1
, const float curve2
,
572 ActuatorDesiredData
*desired
, bool multirotor
, bool fixedwing
)
574 const Mixer_t
*mixers
= (Mixer_t
*)&mixerSettings
.Mixer1Type
; // pointer to array of mixers in UAVObjects
575 const Mixer_t
*mixer
= &mixers
[index
];
576 float differential
= 1.0f
;
578 // Apply differential only for fixedwing and Roll servos
579 if (fixedwing
&& (mixerSettings
.FirstRollServo
> 0) &&
580 (mixer
->type
== MIXERSETTINGS_MIXER1TYPE_SERVO
) &&
581 (mixer
->matrix
[MIXERSETTINGS_MIXER1VECTOR_ROLL
] != 0)) {
582 // Positive differential
583 if (mixerSettings
.RollDifferential
> 0) {
584 // Check for first Roll servo (should be left aileron or elevon) and Roll desired (positive/negative)
585 if (((index
== mixerSettings
.FirstRollServo
- 1) && (desired
->Roll
> 0.0f
))
586 || ((index
!= mixerSettings
.FirstRollServo
- 1) && (desired
->Roll
< 0.0f
))) {
587 differential
-= (mixerSettings
.RollDifferential
* 0.01f
);
589 } else if (mixerSettings
.RollDifferential
< 0) {
590 if (((index
== mixerSettings
.FirstRollServo
- 1) && (desired
->Roll
< 0.0f
))
591 || ((index
!= mixerSettings
.FirstRollServo
- 1) && (desired
->Roll
> 0.0f
))) {
592 differential
-= (-mixerSettings
.RollDifferential
* 0.01f
);
597 float result
= ((((float)mixer
->matrix
[MIXERSETTINGS_MIXER1VECTOR_THROTTLECURVE1
]) * curve1
) +
598 (((float)mixer
->matrix
[MIXERSETTINGS_MIXER1VECTOR_THROTTLECURVE2
]) * curve2
) +
599 (((float)mixer
->matrix
[MIXERSETTINGS_MIXER1VECTOR_ROLL
]) * desired
->Roll
* differential
) +
600 (((float)mixer
->matrix
[MIXERSETTINGS_MIXER1VECTOR_PITCH
]) * desired
->Pitch
) +
601 (((float)mixer
->matrix
[MIXERSETTINGS_MIXER1VECTOR_YAW
]) * desired
->Yaw
)) / 128.0f
;
603 if (mixer
->type
== MIXERSETTINGS_MIXER1TYPE_MOTOR
) {
604 if (!multirotor
) { // we allow negative throttle with a multirotor
605 if (result
< 0.0f
) { // zero throttle
616 * Interpolate a throttle curve
617 * Full range input (-1 to 1) for yaw, roll, pitch
618 * Output range (-1 to 1) reversible motor/throttle curve
620 * Input of -1 -> -lookup(1)
621 * Input of 0 -> lookup(0)
622 * Input of 1 -> lookup(1)
624 static float MixerCurveFullRangeProportional(const float input
, const float *curve
, uint8_t elements
, bool multirotor
)
626 float unsigned_value
= MixerCurveFullRangeAbsolute(input
, curve
, elements
, multirotor
);
629 return -unsigned_value
;
631 return unsigned_value
;
636 * Interpolate a throttle curve
637 * Full range input (-1 to 1) for yaw, roll, pitch
638 * Output range (0 to 1) non-reversible motor/throttle curve
640 * Input of -1 -> lookup(1)
641 * Input of 0 -> lookup(0)
642 * Input of 1 -> lookup(1)
644 static float MixerCurveFullRangeAbsolute(const float input
, const float *curve
, uint8_t elements
, bool multirotor
)
646 float abs_input
= fabsf(input
);
647 float scale
= abs_input
* (float)(elements
- 1);
650 scale
-= (float)idx1
; // remainder
655 if (idx2
>= elements
) {
656 idx2
= elements
- 1; // clamp to highest entry in table
657 if (idx1
>= elements
) {
659 // if multirotor frame we can return throttle values higher than 100%.
660 // Since the we don't have elements in the curve higher than 100% we return
661 // the last element multiplied by the throttle float
662 if (input
< 2.0f
) { // this limits positive throttle to 200% of max value in table (Maybe this is too much allowance)
663 return curve
[idx2
] * input
;
665 return curve
[idx2
] * 2.0f
; // return 200% of max value in table
672 float unsigned_value
= curve
[idx1
] * (1.0f
- scale
) + curve
[idx2
] * scale
;
673 return unsigned_value
;
678 * Convert channel from -1/+1 to servo pulse duration in microseconds
680 static int16_t scaleChannel(float value
, int16_t max
, int16_t min
, int16_t neutral
)
686 valueScaled
= (int16_t)(value
* ((float)(max
- neutral
))) + neutral
;
688 valueScaled
= (int16_t)(value
* ((float)(neutral
- min
))) + neutral
;
692 if (valueScaled
> max
) {
695 if (valueScaled
< min
) {
699 if (valueScaled
< max
) {
702 if (valueScaled
> min
) {
711 * Move and compress all motor outputs so that none goes below neutral,
712 * and all motors are below or equal to max.
714 static inline int16_t scaleMotorMoveAndCompress(float valueMotor
, int16_t max
, int16_t neutral
, float maxMotor
, float minMotor
)
716 // The valueMotor parameter is the desired motor value somewhere in the
717 // [minMotor, maxMotor] range, which is [< -1.00, > 1.00].
719 // Before converting valueMotor to the [neutral, max] range, we scale
720 // valueMotor to a value in the [0.0f, 1.0f] range.
722 // This is done by, first, conceptually moving all three values valueMotor,
723 // minMotor, and maxMotor, equally so that the [minMotor, maxMotor] range,
724 // are contained or overlaps with the [0.0f, 1.0f] range.
726 // Then if the [minMotor, maxMotor] range is larger than 1.0f, the values
727 // are compressed enough to shrink the [minMotor + move, maxMotor + move]
728 // range to fit within the [0.0f, 1.0f] range.
730 // First move the values so that the source range [minMotor, maxMotor]
731 // covers the target range [0.0f, 1.0f] as much as possible.
732 float moveValue
= 0.0f
;
734 if (minMotor
<= 0.0f
) {
735 // Negative minMotor always adjust to 0.
736 moveValue
= -minMotor
;
737 } else if (maxMotor
> 1.0f
) {
738 // A too large maxMotor value adjust the range down towards, but not past, the minMotor value.
739 float beyondMax
= maxMotor
- 1.0f
;
740 moveValue
= -(beyondMax
< minMotor
? beyondMax
: minMotor
);
743 // Then calculate the compress value, if the source range is greater than 1.0f.
744 float compressValue
= 1.0f
;
746 float rangeMotor
= maxMotor
- minMotor
;
747 if (rangeMotor
> 1.0f
) {
748 compressValue
= rangeMotor
;
751 // Combine the movement and compression, to get the value within [0.0f, 1.0f]
752 float movedAndCompressedValue
= (valueMotor
+ moveValue
) / compressValue
;
754 // And last, convert the value into the [neutral, max] range.
755 int16_t valueScaled
= movedAndCompressedValue
* ((float)(max
- neutral
)) + neutral
;
757 if (valueScaled
> max
) {
758 valueScaled
= max
; // clamp to max value only after scaling is done.
761 PIOS_Assert(valueScaled
>= neutral
);
767 * Constrain motor values to keep any one motor value from going too far out of range of another motor
769 static int16_t scaleMotor(float value
, int16_t max
, int16_t min
, int16_t neutral
, float maxMotor
, float minMotor
, bool armed
, bool alwaysStabilizeWhenArmed
, float throttleDesired
)
774 valueScaled
= scaleMotorMoveAndCompress(value
, max
, neutral
, maxMotor
, minMotor
);
776 // not sure what to do about reversed polarity right now. Why would anyone do this?
777 valueScaled
= scaleChannel(value
, max
, min
, neutral
);
780 // I've added the bool alwaysStabilizeWhenArmed to this function. Right now we command the motors at min or a range between neutral and max.
781 // NEVER should a motor be command at between min and neutral. I don't like the idea of stabilization ever commanding a motor to min, but we give people the option
782 // This prevents motors startup sync issues causing possible ESC failures.
786 // if not armed return min EVERYTIME!
788 } else if (!alwaysStabilizeWhenArmed
&& (throttleDesired
<= 0.0f
) && spinWhileArmed
) {
789 // all motors idle is alwaysStabilizeWhenArmed is false, throttle is less than or equal to neutral and spin while armed
790 // stabilize when armed?
791 valueScaled
= neutral
;
792 } else if (!spinWhileArmed
&& (throttleDesired
<= 0.0f
)) {
801 * Set actuator output to the neutral values (failsafe)
803 static void setFailsafe()
805 /* grab only the parts that we are going to use */
806 int16_t Channel
[ACTUATORCOMMAND_CHANNEL_NUMELEM
];
808 ActuatorCommandChannelGet(Channel
);
810 const Mixer_t
*mixers
= (Mixer_t
*)&mixerSettings
.Mixer1Type
; // pointer to array of mixers in UAVObjects
812 // Reset ActuatorCommand to safe values
813 for (int n
= 0; n
< ACTUATORCOMMAND_CHANNEL_NUMELEM
; ++n
) {
814 if (mixers
[n
].type
== MIXERSETTINGS_MIXER1TYPE_MOTOR
) {
815 Channel
[n
] = actuatorSettings
.ChannelMin
[n
];
816 } else if (mixers
[n
].type
== MIXERSETTINGS_MIXER1TYPE_SERVO
|| mixers
[n
].type
== MIXERSETTINGS_MIXER1TYPE_REVERSABLEMOTOR
) {
817 // reversible motors need calibration wizard that allows channel neutral to be the 0 velocity point
818 Channel
[n
] = actuatorSettings
.ChannelNeutral
[n
];
825 AlarmsSet(SYSTEMALARMS_ALARM_ACTUATOR
, SYSTEMALARMS_ALARM_CRITICAL
);
827 // Update servo outputs
828 for (int n
= 0; n
< ACTUATORCOMMAND_CHANNEL_NUMELEM
; ++n
) {
829 set_channel(n
, Channel
[n
]);
831 // Send the updated command
834 // Update output object's parts that we changed
835 ActuatorCommandChannelSet(Channel
);
839 * determine buzzer or blink sequence
842 typedef enum { BUZZ_BUZZER
= 0, BUZZ_ARMING
= 1, BUZZ_INFO
= 2, BUZZ_MAX
= 3 } buzzertype
;
844 static inline bool buzzerState(buzzertype type
)
846 // This is for buzzers that take a PWM input
848 static uint32_t tune
[BUZZ_MAX
] = { 0 };
849 static uint32_t tunestate
[BUZZ_MAX
] = { 0 };
852 uint32_t newTune
= 0;
854 if (type
== BUZZ_BUZZER
) {
855 // Decide what tune to play
856 if (AlarmsGet(SYSTEMALARMS_ALARM_BATTERY
) > SYSTEMALARMS_ALARM_WARNING
) {
857 newTune
= 0b11110110110000; // pause, short, short, short, long
858 } else if (AlarmsGet(SYSTEMALARMS_ALARM_GPS
) >= SYSTEMALARMS_ALARM_WARNING
) {
859 newTune
= 0x80000000; // pause, short
863 } else { // BUZZ_ARMING || BUZZ_INFO
865 FlightStatusArmedGet(&arming
);
867 newTune
= 0x80000000; // 0b1000...
869 // Merge the error pattern for InfoLed
870 if (type
== BUZZ_INFO
) {
871 if (AlarmsGet(SYSTEMALARMS_ALARM_BATTERY
) > SYSTEMALARMS_ALARM_WARNING
) {
872 newTune
|= 0b00000000001111111011111110000000;
873 } else if (AlarmsGet(SYSTEMALARMS_ALARM_GPS
) >= SYSTEMALARMS_ALARM_WARNING
) {
874 newTune
|= 0b00000000000000110110110000000000;
877 // fast double blink pattern if armed
878 if (arming
== FLIGHTSTATUS_ARMED_ARMED
) {
879 newTune
|= 0xA0000000; // 0b101000...
883 // Do we need to change tune?
884 if (newTune
!= tune
[type
]) {
885 tune
[type
] = newTune
;
886 // resynchronize all tunes on change, so they stay in sync
887 for (int i
= 0; i
< BUZZ_MAX
; i
++) {
888 tunestate
[i
] = tune
[i
];
894 static portTickType lastSysTime
= 0;
895 portTickType thisSysTime
= xTaskGetTickCount();
898 // For now, only look at the battery alarm, because functions like AlarmsHasCritical() can block for some time; to be discussed
900 if (thisSysTime
> lastSysTime
) {
901 dT
= thisSysTime
- lastSysTime
;
903 lastSysTime
= 0; // avoid the case where SysTimeMax-lastSysTime <80
906 buzzOn
= (tunestate
[type
] & 1);
909 // Go to next bit in alarm_seq_state
910 for (int i
= 0; i
< BUZZ_MAX
; i
++) {
912 if (tunestate
[i
] == 0) { // All done, re-start the tune
913 tunestate
[i
] = tune
[i
];
916 lastSysTime
= thisSysTime
;
923 #if defined(ARCH_POSIX) || defined(ARCH_WIN32)
924 static bool set_channel(uint8_t mixer_channel
, uint16_t value
)
929 static bool set_channel(uint8_t mixer_channel
, uint16_t value
)
931 switch (actuatorSettings
.ChannelType
[mixer_channel
]) {
932 case ACTUATORSETTINGS_CHANNELTYPE_PWMALARMBUZZER
:
933 PIOS_Servo_Set(actuatorSettings
.ChannelAddr
[mixer_channel
],
934 buzzerState(BUZZ_BUZZER
) ? actuatorSettings
.ChannelMax
[mixer_channel
] : actuatorSettings
.ChannelMin
[mixer_channel
]);
937 case ACTUATORSETTINGS_CHANNELTYPE_ARMINGLED
:
938 PIOS_Servo_Set(actuatorSettings
.ChannelAddr
[mixer_channel
],
939 buzzerState(BUZZ_ARMING
) ? actuatorSettings
.ChannelMax
[mixer_channel
] : actuatorSettings
.ChannelMin
[mixer_channel
]);
942 case ACTUATORSETTINGS_CHANNELTYPE_INFOLED
:
943 PIOS_Servo_Set(actuatorSettings
.ChannelAddr
[mixer_channel
],
944 buzzerState(BUZZ_INFO
) ? actuatorSettings
.ChannelMax
[mixer_channel
] : actuatorSettings
.ChannelMin
[mixer_channel
]);
947 case ACTUATORSETTINGS_CHANNELTYPE_PWM
:
949 uint8_t mode
= pinsMode
[actuatorSettings
.ChannelAddr
[mixer_channel
]];
951 case ACTUATORSETTINGS_BANKMODE_ONESHOT125
:
952 // Remap 1000-2000 range to 125-250µs
953 PIOS_Servo_Set(actuatorSettings
.ChannelAddr
[mixer_channel
], value
* ACTUATOR_ONESHOT125_PULSE_FACTOR
);
955 case ACTUATORSETTINGS_BANKMODE_ONESHOT42
:
956 // Remap 1000-2000 range to 41,666-83,333µs
957 PIOS_Servo_Set(actuatorSettings
.ChannelAddr
[mixer_channel
], value
* ACTUATOR_ONESHOT42_PULSE_FACTOR
);
959 case ACTUATORSETTINGS_BANKMODE_MULTISHOT
:
960 // Remap 1000-2000 range to 5-25µs
961 PIOS_Servo_Set(actuatorSettings
.ChannelAddr
[mixer_channel
], (value
* ACTUATOR_MULTISHOT_PULSE_FACTOR
) - 180);
964 PIOS_Servo_Set(actuatorSettings
.ChannelAddr
[mixer_channel
], value
);
970 #if defined(PIOS_INCLUDE_I2C_ESC)
971 case ACTUATORSETTINGS_CHANNELTYPE_MK
:
972 return PIOS_SetMKSpeed(actuatorSettings
->ChannelAddr
[mixer_channel
], value
);
974 case ACTUATORSETTINGS_CHANNELTYPE_ASTEC4
:
975 return PIOS_SetAstec4Speed(actuatorSettings
->ChannelAddr
[mixer_channel
], value
);
984 #endif /* if defined(ARCH_POSIX) || defined(ARCH_WIN32) */
987 * @brief Update the servo update rate
989 static void actuator_update_rate_if_changed(bool force_update
)
991 static uint16_t prevBankUpdateFreq
[ACTUATORSETTINGS_BANKUPDATEFREQ_NUMELEM
];
992 static uint8_t prevBankMode
[ACTUATORSETTINGS_BANKMODE_NUMELEM
];
993 bool updateMode
= force_update
|| (memcmp(prevBankMode
, actuatorSettings
.BankMode
, sizeof(prevBankMode
)) != 0);
994 bool updateFreq
= force_update
|| (memcmp(prevBankUpdateFreq
, actuatorSettings
.BankUpdateFreq
, sizeof(prevBankUpdateFreq
)) != 0);
996 // check if any setting is changed
997 if (updateMode
|| updateFreq
) {
998 /* Something has changed, apply the settings to HW */
1000 uint16_t freq
[ACTUATORSETTINGS_BANKUPDATEFREQ_NUMELEM
];
1001 uint32_t clock
[ACTUATORSETTINGS_BANKUPDATEFREQ_NUMELEM
] = { 0 };
1002 for (uint8_t i
= 0; i
< ACTUATORSETTINGS_BANKMODE_NUMELEM
; i
++) {
1003 if (force_update
|| (actuatorSettings
.BankMode
[i
] != prevBankMode
[i
])) {
1004 PIOS_Servo_SetBankMode(i
,
1005 actuatorSettings
.BankMode
[i
] ==
1006 ACTUATORSETTINGS_BANKMODE_PWM
?
1007 PIOS_SERVO_BANK_MODE_PWM
:
1008 PIOS_SERVO_BANK_MODE_SINGLE_PULSE
1011 switch (actuatorSettings
.BankMode
[i
]) {
1012 case ACTUATORSETTINGS_BANKMODE_ONESHOT125
:
1013 case ACTUATORSETTINGS_BANKMODE_ONESHOT42
:
1014 case ACTUATORSETTINGS_BANKMODE_MULTISHOT
:
1015 freq
[i
] = 100; // Value must be small enough so CCr isn't update until the PIOS_Servo_Update is triggered
1016 clock
[i
] = ACTUATOR_ONESHOT_CLOCK
; // Setup an 12MHz timer clock
1018 case ACTUATORSETTINGS_BANKMODE_PWMSYNC
:
1020 clock
[i
] = ACTUATOR_PWM_CLOCK
;
1023 freq
[i
] = actuatorSettings
.BankUpdateFreq
[i
];
1024 clock
[i
] = ACTUATOR_PWM_CLOCK
;
1029 memcpy(prevBankMode
,
1030 actuatorSettings
.BankMode
,
1031 sizeof(prevBankMode
));
1033 PIOS_Servo_SetHz(freq
, clock
, ACTUATORSETTINGS_BANKUPDATEFREQ_NUMELEM
);
1035 memcpy(prevBankUpdateFreq
,
1036 actuatorSettings
.BankUpdateFreq
,
1037 sizeof(prevBankUpdateFreq
));
1038 // retrieve mode from related bank
1039 for (uint8_t i
= 0; i
< MAX_MIX_ACTUATORS
; i
++) {
1040 uint8_t bank
= PIOS_Servo_GetPinBank(i
);
1041 pinsMode
[i
] = actuatorSettings
.BankMode
[bank
];
1046 static void ActuatorSettingsUpdatedCb(__attribute__((unused
)) UAVObjEvent
*ev
)
1048 ActuatorSettingsGet(&actuatorSettings
);
1049 spinWhileArmed
= actuatorSettings
.MotorsSpinWhileArmed
== ACTUATORSETTINGS_MOTORSSPINWHILEARMED_TRUE
;
1050 if (frameType
== FRAME_TYPE_GROUND
) {
1051 spinWhileArmed
= false;
1053 actuator_update_rate_if_changed(false);
1056 static void MixerSettingsUpdatedCb(__attribute__((unused
)) UAVObjEvent
*ev
)
1058 MixerSettingsGet(&mixerSettings
);
1059 mixer_settings_count
= 0;
1060 Mixer_t
*mixers
= (Mixer_t
*)&mixerSettings
.Mixer1Type
;
1061 for (int ct
= 0; ct
< MAX_MIX_ACTUATORS
; ct
++) {
1062 if (mixers
[ct
].type
!= MIXERSETTINGS_MIXER1TYPE_DISABLED
) {
1063 mixer_settings_count
++;
1067 static void SettingsUpdatedCb(__attribute__((unused
)) UAVObjEvent
*ev
)
1069 frameType
= GetCurrentFrameType();
1070 #ifndef PIOS_EXCLUDE_ADVANCED_FEATURES
1071 uint8_t TreatCustomCraftAs
;
1072 VtolPathFollowerSettingsTreatCustomCraftAsGet(&TreatCustomCraftAs
);
1074 if (frameType
== FRAME_TYPE_CUSTOM
) {
1075 switch (TreatCustomCraftAs
) {
1076 case VTOLPATHFOLLOWERSETTINGS_TREATCUSTOMCRAFTAS_FIXEDWING
:
1077 frameType
= FRAME_TYPE_FIXED_WING
;
1079 case VTOLPATHFOLLOWERSETTINGS_TREATCUSTOMCRAFTAS_VTOL
:
1080 frameType
= FRAME_TYPE_MULTIROTOR
;
1082 case VTOLPATHFOLLOWERSETTINGS_TREATCUSTOMCRAFTAS_GROUND
:
1083 frameType
= FRAME_TYPE_GROUND
;
1089 SystemSettingsThrustControlGet(&thrustType
);