LP-311 Remove basic/advanced stabilization tab auto-switch (autotune/txpid lock issues)
[librepilot.git] / flight / modules / Actuator / actuator.c
bloba2a66838f5752be0dc46bb66e16b3fc8571f3405
1 /**
2 ******************************************************************************
3 * @addtogroup OpenPilotModules OpenPilot Modules
4 * @{
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.
8 * @{
10 * @file actuator.c
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
27 * for more details.
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"
38 #include "actuator.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"
50 #include "taskinfo.h"
51 #include <systemsettings.h>
52 #include <sanitycheck.h>
53 #ifndef PIOS_EXCLUDE_ADVANCED_FEATURES
54 #include <vtolpathfollowersettings.h>
55 #endif
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).
61 #endif
63 // Private constants
64 #define MAX_QUEUE_SIZE 2
66 #if defined(PIOS_ACTUATOR_STACK_SIZE)
67 #define STACK_SIZE_BYTES PIOS_ACTUATOR_STACK_SIZE
68 #else
69 #define STACK_SIZE_BYTES 1312
70 #endif
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
83 // Private types
86 // Private variables
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;
93 static uint8_t pinsMode[MAX_MIX_ACTUATORS];
94 // used to inform the actuator thread that actuator update rate is changed
95 static ActuatorSettingsData actuatorSettings;
96 static bool spinWhileArmed;
98 // used to inform the actuator thread that mixer settings are changed
99 static MixerSettingsData mixerSettings;
100 static int mixer_settings_count = 2;
102 // Private functions
103 static void actuatorTask(void *parameters);
104 static int16_t scaleChannel(float value, int16_t max, int16_t min, int16_t neutral);
105 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);
106 static void setFailsafe();
107 static float MixerCurveFullRangeProportional(const float input, const float *curve, uint8_t elements, bool multirotor);
108 static float MixerCurveFullRangeAbsolute(const float input, const float *curve, uint8_t elements, bool multirotor);
109 static bool set_channel(uint8_t mixer_channel, uint16_t value);
110 static void actuator_update_rate_if_changed(bool force_update);
111 static void MixerSettingsUpdatedCb(UAVObjEvent *ev);
112 static void ActuatorSettingsUpdatedCb(UAVObjEvent *ev);
113 static void SettingsUpdatedCb(UAVObjEvent *ev);
114 float ProcessMixer(const int index, const float curve1, const float curve2,
115 ActuatorDesiredData *desired,
116 bool multirotor, bool fixedwing);
118 // this structure is equivalent to the UAVObjects for one mixer.
119 typedef struct {
120 uint8_t type;
121 int8_t matrix[5];
122 } __attribute__((packed)) Mixer_t;
125 * @brief Module initialization
126 * @return 0
128 int32_t ActuatorStart()
130 // Start main task
131 xTaskCreate(actuatorTask, "Actuator", STACK_SIZE_BYTES / 4, NULL, TASK_PRIORITY, &taskHandle);
132 PIOS_TASK_MONITOR_RegisterTask(TASKINFO_RUNNING_ACTUATOR, taskHandle);
133 #ifdef PIOS_INCLUDE_WDG
134 PIOS_WDG_RegisterFlag(PIOS_WDG_ACTUATOR);
135 #endif
136 SettingsUpdatedCb(NULL);
137 MixerSettingsUpdatedCb(NULL);
138 ActuatorSettingsUpdatedCb(NULL);
139 return 0;
143 * @brief Module initialization
144 * @return 0
146 int32_t ActuatorInitialize()
148 // Register for notification of changes to ActuatorSettings
149 ActuatorSettingsInitialize();
150 ActuatorSettingsConnectCallback(ActuatorSettingsUpdatedCb);
152 // Register for notification of changes to MixerSettings
153 MixerSettingsInitialize();
154 MixerSettingsConnectCallback(MixerSettingsUpdatedCb);
156 // Listen for ActuatorDesired updates (Primary input to this module)
157 ActuatorDesiredInitialize();
158 queue = xQueueCreate(MAX_QUEUE_SIZE, sizeof(UAVObjEvent));
159 ActuatorDesiredConnectQueue(queue);
161 // Register AccessoryDesired (Secondary input to this module)
162 AccessoryDesiredInitialize();
164 // Check if CameraStab module is enabled
165 HwSettingsOptionalModulesData optionalModules;
166 HwSettingsInitialize();
167 HwSettingsOptionalModulesGet(&optionalModules);
168 camStabEnabled = (optionalModules.CameraStab == HWSETTINGS_OPTIONALMODULES_ENABLED);
170 // Primary output of this module
171 ActuatorCommandInitialize();
173 #ifdef DIAG_MIXERSTATUS
174 // UAVO only used for inspecting the internal status of the mixer during debug
175 MixerStatusInitialize();
176 #endif
178 #ifndef PIOS_EXCLUDE_ADVANCED_FEATURES
179 VtolPathFollowerSettingsInitialize();
180 VtolPathFollowerSettingsConnectCallback(&SettingsUpdatedCb);
181 #endif
182 SystemSettingsInitialize();
183 SystemSettingsConnectCallback(&SettingsUpdatedCb);
185 return 0;
187 MODULE_INITCALL(ActuatorInitialize, ActuatorStart);
190 * @brief Main Actuator module task
192 * Universal matrix based mixer for VTOL, helis and fixed wing.
193 * Converts desired roll,pitch,yaw and throttle to servo/ESC outputs.
195 * Because of how the Throttle ranges from 0 to 1, the motors should too!
197 * Note this code depends on the UAVObjects for the mixers being all being the same
198 * and in sequence. If you change the object definition, make sure you check the code!
200 * @return -1 if error, 0 if success
202 static void actuatorTask(__attribute__((unused)) void *parameters)
204 UAVObjEvent ev;
205 portTickType lastSysTime;
206 portTickType thisSysTime;
207 uint32_t dTMilliseconds;
209 ActuatorCommandData command;
210 ActuatorDesiredData desired;
211 MixerStatusData mixerStatus;
212 FlightModeSettingsData settings;
213 FlightStatusData flightStatus;
214 float throttleDesired;
215 float collectiveDesired;
217 #ifdef PIOS_INCLUDE_INSTRUMENTATION
218 counter = PIOS_Instrumentation_CreateCounter(0xAC700001);
219 #endif
220 /* Read initial values of ActuatorSettings */
222 ActuatorSettingsGet(&actuatorSettings);
224 /* Read initial values of MixerSettings */
225 MixerSettingsGet(&mixerSettings);
227 /* Force an initial configuration of the actuator update rates */
228 actuator_update_rate_if_changed(true);
230 // Go to the neutral (failsafe) values until an ActuatorDesired update is received
231 setFailsafe();
233 // Main task loop
234 lastSysTime = xTaskGetTickCount();
235 while (1) {
236 #ifdef PIOS_INCLUDE_WDG
237 PIOS_WDG_UpdateFlag(PIOS_WDG_ACTUATOR);
238 #endif
240 // Wait until the ActuatorDesired object is updated
241 uint8_t rc = xQueueReceive(queue, &ev, FAILSAFE_TIMEOUT_MS / portTICK_RATE_MS);
242 #ifdef PIOS_INCLUDE_INSTRUMENTATION
243 PIOS_Instrumentation_TimeStart(counter);
244 #endif
246 if (rc != pdTRUE) {
247 /* Update of ActuatorDesired timed out. Go to failsafe */
248 setFailsafe();
249 continue;
252 // Check how long since last update
253 thisSysTime = xTaskGetTickCount();
254 dTMilliseconds = (thisSysTime == lastSysTime) ? 1 : (thisSysTime - lastSysTime) * portTICK_RATE_MS;
255 lastSysTime = thisSysTime;
257 FlightStatusGet(&flightStatus);
258 FlightModeSettingsGet(&settings);
259 ActuatorDesiredGet(&desired);
260 ActuatorCommandGet(&command);
262 // read in throttle and collective -demultiplex thrust
263 switch (thrustType) {
264 case SYSTEMSETTINGS_THRUSTCONTROL_THROTTLE:
265 throttleDesired = desired.Thrust;
266 ManualControlCommandCollectiveGet(&collectiveDesired);
267 break;
268 case SYSTEMSETTINGS_THRUSTCONTROL_COLLECTIVE:
269 ManualControlCommandThrottleGet(&throttleDesired);
270 collectiveDesired = desired.Thrust;
271 break;
272 default:
273 ManualControlCommandThrottleGet(&throttleDesired);
274 ManualControlCommandCollectiveGet(&collectiveDesired);
277 bool armed = flightStatus.Armed == FLIGHTSTATUS_ARMED_ARMED;
278 bool activeThrottle = (throttleDesired < -0.001f || throttleDesired > 0.001f); // for ground and reversible motors
279 bool positiveThrottle = (throttleDesired > 0.00f);
280 bool multirotor = (GetCurrentFrameType() == FRAME_TYPE_MULTIROTOR); // check if frame is a multirotor.
281 bool fixedwing = (GetCurrentFrameType() == FRAME_TYPE_FIXED_WING); // check if frame is a fixedwing.
282 bool alwaysArmed = settings.Arming == FLIGHTMODESETTINGS_ARMING_ALWAYSARMED;
283 bool alwaysStabilizeWhenArmed = flightStatus.AlwaysStabilizeWhenArmed == FLIGHTSTATUS_ALWAYSSTABILIZEWHENARMED_TRUE;
285 if (alwaysArmed) {
286 alwaysStabilizeWhenArmed = false; // Do not allow always stabilize when alwaysArmed is active. This is dangerous.
288 // safety settings
289 if (!armed) {
290 throttleDesired = 0.00f; // this also happens in scaleMotors as a per axis check
293 if ((frameType == FRAME_TYPE_GROUND && !activeThrottle) || (frameType != FRAME_TYPE_GROUND && throttleDesired <= 0.00f) || !armed) {
294 // throttleDesired should never be 0 or go below 0.
295 // force set all other controls to zero if throttle is cut (previously set in Stabilization)
296 // todo: can probably remove this
297 if (!(multirotor && alwaysStabilizeWhenArmed && armed)) { // we don't do this if this is a multirotor AND AlwaysStabilizeWhenArmed is true and the model is armed
298 if (actuatorSettings.LowThrottleZeroAxis.Roll == ACTUATORSETTINGS_LOWTHROTTLEZEROAXIS_TRUE) {
299 desired.Roll = 0.00f;
301 if (actuatorSettings.LowThrottleZeroAxis.Pitch == ACTUATORSETTINGS_LOWTHROTTLEZEROAXIS_TRUE) {
302 desired.Pitch = 0.00f;
304 if (actuatorSettings.LowThrottleZeroAxis.Yaw == ACTUATORSETTINGS_LOWTHROTTLEZEROAXIS_TRUE) {
305 desired.Yaw = 0.00f;
310 #ifdef DIAG_MIXERSTATUS
311 MixerStatusGet(&mixerStatus);
312 #endif
314 if ((mixer_settings_count < 2) && !ActuatorCommandReadOnly()) { // Nothing can fly with less than two mixers.
315 setFailsafe();
316 continue;
319 AlarmsClear(SYSTEMALARMS_ALARM_ACTUATOR);
321 float curve1 = 0.0f; // curve 1 is the throttle curve applied to all motors.
322 float curve2 = 0.0f;
324 // Interpolate curve 1 from throttleDesired as input.
325 // assume reversible motor/mixer initially. We can later reverse this. The difference is simply that -ve throttleDesired values
326 // map differently
327 curve1 = MixerCurveFullRangeProportional(throttleDesired, mixerSettings.ThrottleCurve1, MIXERSETTINGS_THROTTLECURVE1_NUMELEM, multirotor);
329 // The source for the secondary curve is selectable
330 AccessoryDesiredData accessory;
331 uint8_t curve2Source = mixerSettings.Curve2Source;
332 switch (curve2Source) {
333 case MIXERSETTINGS_CURVE2SOURCE_THROTTLE:
334 // assume reversible motor/mixer initially
335 curve2 = MixerCurveFullRangeProportional(throttleDesired, mixerSettings.ThrottleCurve2, MIXERSETTINGS_THROTTLECURVE2_NUMELEM, multirotor);
336 break;
337 case MIXERSETTINGS_CURVE2SOURCE_ROLL:
338 // Throttle curve contribution the same for +ve vs -ve roll
339 if (multirotor) {
340 curve2 = MixerCurveFullRangeProportional(desired.Roll, mixerSettings.ThrottleCurve2, MIXERSETTINGS_THROTTLECURVE2_NUMELEM, multirotor);
341 } else {
342 curve2 = MixerCurveFullRangeAbsolute(desired.Roll, mixerSettings.ThrottleCurve2, MIXERSETTINGS_THROTTLECURVE2_NUMELEM, multirotor);
344 break;
345 case MIXERSETTINGS_CURVE2SOURCE_PITCH:
346 // Throttle curve contribution the same for +ve vs -ve pitch
347 if (multirotor) {
348 curve2 = MixerCurveFullRangeProportional(desired.Pitch, mixerSettings.ThrottleCurve2,
349 MIXERSETTINGS_THROTTLECURVE2_NUMELEM, multirotor);
350 } else {
351 curve2 = MixerCurveFullRangeAbsolute(desired.Pitch, mixerSettings.ThrottleCurve2,
352 MIXERSETTINGS_THROTTLECURVE2_NUMELEM, multirotor);
354 break;
355 case MIXERSETTINGS_CURVE2SOURCE_YAW:
356 // Throttle curve contribution the same for +ve vs -ve yaw
357 if (multirotor) {
358 curve2 = MixerCurveFullRangeProportional(desired.Yaw, mixerSettings.ThrottleCurve2, MIXERSETTINGS_THROTTLECURVE2_NUMELEM, multirotor);
359 } else {
360 curve2 = MixerCurveFullRangeAbsolute(desired.Yaw, mixerSettings.ThrottleCurve2, MIXERSETTINGS_THROTTLECURVE2_NUMELEM, multirotor);
362 break;
363 case MIXERSETTINGS_CURVE2SOURCE_COLLECTIVE:
364 // assume reversible motor/mixer initially
365 curve2 = MixerCurveFullRangeProportional(collectiveDesired, mixerSettings.ThrottleCurve2,
366 MIXERSETTINGS_THROTTLECURVE2_NUMELEM, multirotor);
367 break;
368 case MIXERSETTINGS_CURVE2SOURCE_ACCESSORY0:
369 case MIXERSETTINGS_CURVE2SOURCE_ACCESSORY1:
370 case MIXERSETTINGS_CURVE2SOURCE_ACCESSORY2:
371 case MIXERSETTINGS_CURVE2SOURCE_ACCESSORY3:
372 case MIXERSETTINGS_CURVE2SOURCE_ACCESSORY4:
373 case MIXERSETTINGS_CURVE2SOURCE_ACCESSORY5:
374 if (AccessoryDesiredInstGet(mixerSettings.Curve2Source - MIXERSETTINGS_CURVE2SOURCE_ACCESSORY0, &accessory) == 0) {
375 // Throttle curve contribution the same for +ve vs -ve accessory....maybe not want we want.
376 curve2 = MixerCurveFullRangeAbsolute(accessory.AccessoryVal, mixerSettings.ThrottleCurve2, MIXERSETTINGS_THROTTLECURVE2_NUMELEM, multirotor);
377 } else {
378 curve2 = 0.0f;
380 break;
381 default:
382 curve2 = 0.0f;
383 break;
386 float *status = (float *)&mixerStatus; // access status objects as an array of floats
387 Mixer_t *mixers = (Mixer_t *)&mixerSettings.Mixer1Type;
388 float maxMotor = -1.0f; // highest motor value. Addition method needs this to be -1.0f, division method needs this to be 1.0f
389 float minMotor = 1.0f; // lowest motor value Addition method needs this to be 1.0f, division method needs this to be -1.0f
391 for (int ct = 0; ct < MAX_MIX_ACTUATORS; ct++) {
392 // During boot all camera actuators should be completely disabled (PWM pulse = 0).
393 // command.Channel[i] is reused below as a channel PWM activity flag:
394 // 0 - PWM disabled, >0 - PWM set to real mixer value using scaleChannel() later.
395 // Setting it to 1 by default means "Rescale this channel and enable PWM on its output".
396 command.Channel[ct] = 1;
398 uint8_t mixer_type = mixers[ct].type;
400 if (mixer_type == MIXERSETTINGS_MIXER1TYPE_DISABLED) {
401 // Set to minimum if disabled. This is not the same as saying PWM pulse = 0 us
402 status[ct] = -1;
403 continue;
406 if ((mixer_type == MIXERSETTINGS_MIXER1TYPE_MOTOR)) {
407 float nonreversible_curve1 = curve1;
408 float nonreversible_curve2 = curve2;
409 if (nonreversible_curve1 < 0.0f) {
410 nonreversible_curve1 = 0.0f;
412 if (nonreversible_curve2 < 0.0f) {
413 if (!multirotor) { // allow negative throttle if multirotor. function scaleMotors handles the sanity checks.
414 nonreversible_curve2 = 0.0f;
417 status[ct] = ProcessMixer(ct, nonreversible_curve1, nonreversible_curve2, &desired, multirotor, fixedwing);
418 // If not armed or motors aren't meant to spin all the time
419 if (!armed ||
420 (!spinWhileArmed && !positiveThrottle)) {
421 status[ct] = -1; // force min throttle
423 // If armed meant to keep spinning,
424 else if ((spinWhileArmed && !positiveThrottle) ||
425 (status[ct] < 0)) {
426 if (!multirotor) {
427 status[ct] = 0;
428 // allow throttle values lower than 0 if multirotor.
429 // Values will be scaled to 0 if they need to be in the scaleMotor function
432 } else if (mixer_type == MIXERSETTINGS_MIXER1TYPE_REVERSABLEMOTOR) {
433 status[ct] = ProcessMixer(ct, curve1, curve2, &desired, multirotor, fixedwing);
434 // Reversable Motors are like Motors but go to neutral instead of minimum
435 // If not armed or motor is inactive - no "spinwhilearmed" for this engine type
436 if (!armed || !activeThrottle) {
437 status[ct] = 0; // force neutral throttle
439 } else if (mixer_type == MIXERSETTINGS_MIXER1TYPE_SERVO) {
440 status[ct] = ProcessMixer(ct, curve1, curve2, &desired, multirotor, fixedwing);
441 } else {
442 status[ct] = -1;
444 // If an accessory channel is selected for direct bypass mode
445 // In this configuration the accessory channel is scaled and mapped
446 // directly to output. Note: THERE IS NO SAFETY CHECK HERE FOR ARMING
447 // these also will not be updated in failsafe mode. I'm not sure what
448 // the correct behavior is since it seems domain specific. I don't love
449 // this code
450 if ((mixer_type >= MIXERSETTINGS_MIXER1TYPE_ACCESSORY0) &&
451 (mixer_type <= MIXERSETTINGS_MIXER1TYPE_ACCESSORY5)) {
452 if (AccessoryDesiredInstGet(mixer_type - MIXERSETTINGS_MIXER1TYPE_ACCESSORY0, &accessory) == 0) {
453 status[ct] = accessory.AccessoryVal;
454 } else {
455 status[ct] = -1;
459 if ((mixer_type >= MIXERSETTINGS_MIXER1TYPE_CAMERAROLLORSERVO1) &&
460 (mixer_type <= MIXERSETTINGS_MIXER1TYPE_CAMERAYAW)) {
461 if (camStabEnabled) {
462 CameraDesiredData cameraDesired;
463 CameraDesiredGet(&cameraDesired);
464 switch (mixer_type) {
465 case MIXERSETTINGS_MIXER1TYPE_CAMERAROLLORSERVO1:
466 status[ct] = cameraDesired.RollOrServo1;
467 break;
468 case MIXERSETTINGS_MIXER1TYPE_CAMERAPITCHORSERVO2:
469 status[ct] = cameraDesired.PitchOrServo2;
470 break;
471 case MIXERSETTINGS_MIXER1TYPE_CAMERAYAW:
472 status[ct] = cameraDesired.Yaw;
473 break;
474 default:
475 break;
477 } else {
478 status[ct] = -1;
481 // Disable camera actuators for CAMERA_BOOT_DELAY_MS after boot
482 if (thisSysTime < (CAMERA_BOOT_DELAY_MS / portTICK_RATE_MS)) {
483 command.Channel[ct] = 0;
488 // If mixer type is motor we need to find which motor has the highest value and which motor has the lowest value.
489 // For use in function scaleMotor
490 if (mixers[ct].type == MIXERSETTINGS_MIXER1TYPE_MOTOR) {
491 if (maxMotor < status[ct]) {
492 maxMotor = status[ct];
494 if (minMotor > status[ct]) {
495 minMotor = status[ct];
500 // Set real actuator output values scaling them from mixers. All channels
501 // will be set except explicitly disabled (which will have PWM pulse = 0).
502 for (int i = 0; i < MAX_MIX_ACTUATORS; i++) {
503 if (command.Channel[i]) {
504 if (mixers[i].type == MIXERSETTINGS_MIXER1TYPE_MOTOR) { // If mixer is for a motor we need to find the highest value of all motors
505 command.Channel[i] = scaleMotor(status[i],
506 actuatorSettings.ChannelMax[i],
507 actuatorSettings.ChannelMin[i],
508 actuatorSettings.ChannelNeutral[i],
509 maxMotor,
510 minMotor,
511 armed,
512 alwaysStabilizeWhenArmed,
513 throttleDesired);
514 } else { // else we scale the channel
515 command.Channel[i] = scaleChannel(status[i],
516 actuatorSettings.ChannelMax[i],
517 actuatorSettings.ChannelMin[i],
518 actuatorSettings.ChannelNeutral[i]);
523 // Store update time
524 command.UpdateTime = dTMilliseconds;
525 if (command.UpdateTime > command.MaxUpdateTime) {
526 command.MaxUpdateTime = command.UpdateTime;
528 // Update output object
529 ActuatorCommandSet(&command);
530 // Update in case read only (eg. during servo configuration)
531 ActuatorCommandGet(&command);
533 #ifdef DIAG_MIXERSTATUS
534 MixerStatusSet(&mixerStatus);
535 #endif
538 // Update servo outputs
539 bool success = true;
541 for (int n = 0; n < ACTUATORCOMMAND_CHANNEL_NUMELEM; ++n) {
542 success &= set_channel(n, command.Channel[n]);
545 PIOS_Servo_Update();
547 if (!success) {
548 command.NumFailedUpdates++;
549 ActuatorCommandSet(&command);
550 AlarmsSet(SYSTEMALARMS_ALARM_ACTUATOR, SYSTEMALARMS_ALARM_CRITICAL);
552 #ifdef PIOS_INCLUDE_INSTRUMENTATION
553 PIOS_Instrumentation_TimeEnd(counter);
554 #endif
560 * Process mixing for one actuator
562 float ProcessMixer(const int index, const float curve1, const float curve2,
563 ActuatorDesiredData *desired, bool multirotor, bool fixedwing)
565 const Mixer_t *mixers = (Mixer_t *)&mixerSettings.Mixer1Type; // pointer to array of mixers in UAVObjects
566 const Mixer_t *mixer = &mixers[index];
567 float differential = 1.0f;
569 // Apply differential only for fixedwing and Roll servos
570 if (fixedwing && (mixerSettings.FirstRollServo > 0) &&
571 (mixer->type == MIXERSETTINGS_MIXER1TYPE_SERVO) &&
572 (mixer->matrix[MIXERSETTINGS_MIXER1VECTOR_ROLL] != 0)) {
573 // Positive differential
574 if (mixerSettings.RollDifferential > 0) {
575 // Check for first Roll servo (should be left aileron or elevon) and Roll desired (positive/negative)
576 if (((index == mixerSettings.FirstRollServo - 1) && (desired->Roll > 0.0f))
577 || ((index != mixerSettings.FirstRollServo - 1) && (desired->Roll < 0.0f))) {
578 differential -= (mixerSettings.RollDifferential * 0.01f);
580 } else if (mixerSettings.RollDifferential < 0) {
581 if (((index == mixerSettings.FirstRollServo - 1) && (desired->Roll < 0.0f))
582 || ((index != mixerSettings.FirstRollServo - 1) && (desired->Roll > 0.0f))) {
583 differential -= (-mixerSettings.RollDifferential * 0.01f);
588 float result = ((((float)mixer->matrix[MIXERSETTINGS_MIXER1VECTOR_THROTTLECURVE1]) * curve1) +
589 (((float)mixer->matrix[MIXERSETTINGS_MIXER1VECTOR_THROTTLECURVE2]) * curve2) +
590 (((float)mixer->matrix[MIXERSETTINGS_MIXER1VECTOR_ROLL]) * desired->Roll * differential) +
591 (((float)mixer->matrix[MIXERSETTINGS_MIXER1VECTOR_PITCH]) * desired->Pitch) +
592 (((float)mixer->matrix[MIXERSETTINGS_MIXER1VECTOR_YAW]) * desired->Yaw)) / 128.0f;
594 if (mixer->type == MIXERSETTINGS_MIXER1TYPE_MOTOR) {
595 if (!multirotor) { // we allow negative throttle with a multirotor
596 if (result < 0.0f) { // zero throttle
597 result = 0.0f;
602 return result;
607 * Interpolate a throttle curve
608 * Full range input (-1 to 1) for yaw, roll, pitch
609 * Output range (-1 to 1) reversible motor/throttle curve
611 * Input of -1 -> -lookup(1)
612 * Input of 0 -> lookup(0)
613 * Input of 1 -> lookup(1)
615 static float MixerCurveFullRangeProportional(const float input, const float *curve, uint8_t elements, bool multirotor)
617 float unsigned_value = MixerCurveFullRangeAbsolute(input, curve, elements, multirotor);
619 if (input < 0.0f) {
620 return -unsigned_value;
621 } else {
622 return unsigned_value;
627 * Interpolate a throttle curve
628 * Full range input (-1 to 1) for yaw, roll, pitch
629 * Output range (0 to 1) non-reversible motor/throttle curve
631 * Input of -1 -> lookup(1)
632 * Input of 0 -> lookup(0)
633 * Input of 1 -> lookup(1)
635 static float MixerCurveFullRangeAbsolute(const float input, const float *curve, uint8_t elements, bool multirotor)
637 float abs_input = fabsf(input);
638 float scale = abs_input * (float)(elements - 1);
639 int idx1 = scale;
641 scale -= (float)idx1; // remainder
642 if (curve[0] < -1) {
643 return abs_input;
645 int idx2 = idx1 + 1;
646 if (idx2 >= elements) {
647 idx2 = elements - 1; // clamp to highest entry in table
648 if (idx1 >= elements) {
649 if (multirotor) {
650 // if multirotor frame we can return throttle values higher than 100%.
651 // Since the we don't have elements in the curve higher than 100% we return
652 // the last element multiplied by the throttle float
653 if (input < 2.0f) { // this limits positive throttle to 200% of max value in table (Maybe this is too much allowance)
654 return curve[idx2] * input;
655 } else {
656 return curve[idx2] * 2.0f; // return 200% of max value in table
659 idx1 = elements - 1;
663 float unsigned_value = curve[idx1] * (1.0f - scale) + curve[idx2] * scale;
664 return unsigned_value;
669 * Convert channel from -1/+1 to servo pulse duration in microseconds
671 static int16_t scaleChannel(float value, int16_t max, int16_t min, int16_t neutral)
673 int16_t valueScaled;
675 // Scale
676 if (value >= 0.0f) {
677 valueScaled = (int16_t)(value * ((float)(max - neutral))) + neutral;
678 } else {
679 valueScaled = (int16_t)(value * ((float)(neutral - min))) + neutral;
682 if (max > min) {
683 if (valueScaled > max) {
684 valueScaled = max;
686 if (valueScaled < min) {
687 valueScaled = min;
689 } else {
690 if (valueScaled < max) {
691 valueScaled = max;
693 if (valueScaled > min) {
694 valueScaled = min;
698 return valueScaled;
702 * Move and compress all motor outputs so that none goes below neutral,
703 * and all motors are below or equal to max.
705 static inline int16_t scaleMotorMoveAndCompress(float valueMotor, int16_t max, int16_t neutral, float maxMotor, float minMotor)
707 // The valueMotor parameter is the desired motor value somewhere in the
708 // [minMotor, maxMotor] range, which is [< -1.00, > 1.00].
710 // Before converting valueMotor to the [neutral, max] range, we scale
711 // valueMotor to a value in the [0.0f, 1.0f] range.
713 // This is done by, first, conceptually moving all three values valueMotor,
714 // minMotor, and maxMotor, equally so that the [minMotor, maxMotor] range,
715 // are contained or overlaps with the [0.0f, 1.0f] range.
717 // Then if the [minMotor, maxMotor] range is larger than 1.0f, the values
718 // are compressed enough to shrink the [minMotor + move, maxMotor + move]
719 // range to fit within the [0.0f, 1.0f] range.
721 // First move the values so that the source range [minMotor, maxMotor]
722 // covers the target range [0.0f, 1.0f] as much as possible.
723 float moveValue = 0.0f;
725 if (minMotor <= 0.0f) {
726 // Negative minMotor always adjust to 0.
727 moveValue = -minMotor;
728 } else if (maxMotor > 1.0f) {
729 // A too large maxMotor value adjust the range down towards, but not past, the minMotor value.
730 float beyondMax = maxMotor - 1.0f;
731 moveValue = -(beyondMax < minMotor ? beyondMax : minMotor);
734 // Then calculate the compress value, if the source range is greater than 1.0f.
735 float compressValue = 1.0f;
737 float rangeMotor = maxMotor - minMotor;
738 if (rangeMotor > 1.0f) {
739 compressValue = rangeMotor;
742 // Combine the movement and compression, to get the value within [0.0f, 1.0f]
743 float movedAndCompressedValue = (valueMotor + moveValue) / compressValue;
745 // And last, convert the value into the [neutral, max] range.
746 int16_t valueScaled = movedAndCompressedValue * ((float)(max - neutral)) + neutral;
748 if (valueScaled > max) {
749 valueScaled = max; // clamp to max value only after scaling is done.
752 PIOS_Assert(valueScaled >= neutral);
754 return valueScaled;
758 * Constrain motor values to keep any one motor value from going too far out of range of another motor
760 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)
762 int16_t valueScaled;
764 if (max > min) {
765 valueScaled = scaleMotorMoveAndCompress(value, max, neutral, maxMotor, minMotor);
766 } else {
767 // not sure what to do about reversed polarity right now. Why would anyone do this?
768 valueScaled = scaleChannel(value, max, min, neutral);
771 // I've added the bool alwaysStabilizeWhenArmed to this function. Right now we command the motors at min or a range between neutral and max.
772 // 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
773 // This prevents motors startup sync issues causing possible ESC failures.
775 // safety checks
776 if (!armed) {
777 // if not armed return min EVERYTIME!
778 valueScaled = min;
779 } else if (!alwaysStabilizeWhenArmed && (throttleDesired <= 0.0f) && spinWhileArmed) {
780 // all motors idle is alwaysStabilizeWhenArmed is false, throttle is less than or equal to neutral and spin while armed
781 // stabilize when armed?
782 valueScaled = neutral;
783 } else if (!spinWhileArmed && (throttleDesired <= 0.0f)) {
784 // soft disarm
785 valueScaled = min;
788 return valueScaled;
792 * Set actuator output to the neutral values (failsafe)
794 static void setFailsafe()
796 /* grab only the parts that we are going to use */
797 int16_t Channel[ACTUATORCOMMAND_CHANNEL_NUMELEM];
799 ActuatorCommandChannelGet(Channel);
801 const Mixer_t *mixers = (Mixer_t *)&mixerSettings.Mixer1Type; // pointer to array of mixers in UAVObjects
803 // Reset ActuatorCommand to safe values
804 for (int n = 0; n < ACTUATORCOMMAND_CHANNEL_NUMELEM; ++n) {
805 if (mixers[n].type == MIXERSETTINGS_MIXER1TYPE_MOTOR) {
806 Channel[n] = actuatorSettings.ChannelMin[n];
807 } else if (mixers[n].type == MIXERSETTINGS_MIXER1TYPE_SERVO || mixers[n].type == MIXERSETTINGS_MIXER1TYPE_REVERSABLEMOTOR) {
808 // reversible motors need calibration wizard that allows channel neutral to be the 0 velocity point
809 Channel[n] = actuatorSettings.ChannelNeutral[n];
810 } else {
811 Channel[n] = 0;
815 // Set alarm
816 AlarmsSet(SYSTEMALARMS_ALARM_ACTUATOR, SYSTEMALARMS_ALARM_CRITICAL);
818 // Update servo outputs
819 for (int n = 0; n < ACTUATORCOMMAND_CHANNEL_NUMELEM; ++n) {
820 set_channel(n, Channel[n]);
822 // Send the updated command
823 PIOS_Servo_Update();
825 // Update output object's parts that we changed
826 ActuatorCommandChannelSet(Channel);
830 * determine buzzer or blink sequence
833 typedef enum { BUZZ_BUZZER = 0, BUZZ_ARMING = 1, BUZZ_INFO = 2, BUZZ_MAX = 3 } buzzertype;
835 static inline bool buzzerState(buzzertype type)
837 // This is for buzzers that take a PWM input
839 static uint32_t tune[BUZZ_MAX] = { 0 };
840 static uint32_t tunestate[BUZZ_MAX] = { 0 };
843 uint32_t newTune = 0;
845 if (type == BUZZ_BUZZER) {
846 // Decide what tune to play
847 if (AlarmsGet(SYSTEMALARMS_ALARM_BATTERY) > SYSTEMALARMS_ALARM_WARNING) {
848 newTune = 0b11110110110000; // pause, short, short, short, long
849 } else if (AlarmsGet(SYSTEMALARMS_ALARM_GPS) >= SYSTEMALARMS_ALARM_WARNING) {
850 newTune = 0x80000000; // pause, short
851 } else {
852 newTune = 0;
854 } else { // BUZZ_ARMING || BUZZ_INFO
855 uint8_t arming;
856 FlightStatusArmedGet(&arming);
857 // base idle tune
858 newTune = 0x80000000; // 0b1000...
860 // Merge the error pattern for InfoLed
861 if (type == BUZZ_INFO) {
862 if (AlarmsGet(SYSTEMALARMS_ALARM_BATTERY) > SYSTEMALARMS_ALARM_WARNING) {
863 newTune |= 0b00000000001111111011111110000000;
864 } else if (AlarmsGet(SYSTEMALARMS_ALARM_GPS) >= SYSTEMALARMS_ALARM_WARNING) {
865 newTune |= 0b00000000000000110110110000000000;
868 // fast double blink pattern if armed
869 if (arming == FLIGHTSTATUS_ARMED_ARMED) {
870 newTune |= 0xA0000000; // 0b101000...
874 // Do we need to change tune?
875 if (newTune != tune[type]) {
876 tune[type] = newTune;
877 // resynchronize all tunes on change, so they stay in sync
878 for (int i = 0; i < BUZZ_MAX; i++) {
879 tunestate[i] = tune[i];
883 // Play tune
884 bool buzzOn = false;
885 static portTickType lastSysTime = 0;
886 portTickType thisSysTime = xTaskGetTickCount();
887 portTickType dT = 0;
889 // For now, only look at the battery alarm, because functions like AlarmsHasCritical() can block for some time; to be discussed
890 if (tune[type]) {
891 if (thisSysTime > lastSysTime) {
892 dT = thisSysTime - lastSysTime;
893 } else {
894 lastSysTime = 0; // avoid the case where SysTimeMax-lastSysTime <80
897 buzzOn = (tunestate[type] & 1);
899 if (dT > 80) {
900 // Go to next bit in alarm_seq_state
901 for (int i = 0; i < BUZZ_MAX; i++) {
902 tunestate[i] >>= 1;
903 if (tunestate[i] == 0) { // All done, re-start the tune
904 tunestate[i] = tune[i];
907 lastSysTime = thisSysTime;
910 return buzzOn;
914 #if defined(ARCH_POSIX) || defined(ARCH_WIN32)
915 static bool set_channel(uint8_t mixer_channel, uint16_t value)
917 return true;
919 #else
920 static bool set_channel(uint8_t mixer_channel, uint16_t value)
922 switch (actuatorSettings.ChannelType[mixer_channel]) {
923 case ACTUATORSETTINGS_CHANNELTYPE_PWMALARMBUZZER:
924 PIOS_Servo_Set(actuatorSettings.ChannelAddr[mixer_channel],
925 buzzerState(BUZZ_BUZZER) ? actuatorSettings.ChannelMax[mixer_channel] : actuatorSettings.ChannelMin[mixer_channel]);
926 return true;
928 case ACTUATORSETTINGS_CHANNELTYPE_ARMINGLED:
929 PIOS_Servo_Set(actuatorSettings.ChannelAddr[mixer_channel],
930 buzzerState(BUZZ_ARMING) ? actuatorSettings.ChannelMax[mixer_channel] : actuatorSettings.ChannelMin[mixer_channel]);
931 return true;
933 case ACTUATORSETTINGS_CHANNELTYPE_INFOLED:
934 PIOS_Servo_Set(actuatorSettings.ChannelAddr[mixer_channel],
935 buzzerState(BUZZ_INFO) ? actuatorSettings.ChannelMax[mixer_channel] : actuatorSettings.ChannelMin[mixer_channel]);
936 return true;
938 case ACTUATORSETTINGS_CHANNELTYPE_PWM:
940 uint8_t mode = pinsMode[actuatorSettings.ChannelAddr[mixer_channel]];
941 switch (mode) {
942 case ACTUATORSETTINGS_BANKMODE_ONESHOT125:
943 // Remap 1000-2000 range to 125-250µs
944 PIOS_Servo_Set(actuatorSettings.ChannelAddr[mixer_channel], value * ACTUATOR_ONESHOT125_PULSE_FACTOR);
945 break;
946 case ACTUATORSETTINGS_BANKMODE_ONESHOT42:
947 // Remap 1000-2000 range to 41,666-83,333µs
948 PIOS_Servo_Set(actuatorSettings.ChannelAddr[mixer_channel], value * ACTUATOR_ONESHOT42_PULSE_FACTOR);
949 break;
950 case ACTUATORSETTINGS_BANKMODE_MULTISHOT:
951 // Remap 1000-2000 range to 5-25µs
952 PIOS_Servo_Set(actuatorSettings.ChannelAddr[mixer_channel], (value * ACTUATOR_MULTISHOT_PULSE_FACTOR) - 180);
953 break;
954 default:
955 PIOS_Servo_Set(actuatorSettings.ChannelAddr[mixer_channel], value);
956 break;
958 return true;
961 #if defined(PIOS_INCLUDE_I2C_ESC)
962 case ACTUATORSETTINGS_CHANNELTYPE_MK:
963 return PIOS_SetMKSpeed(actuatorSettings->ChannelAddr[mixer_channel], value);
965 case ACTUATORSETTINGS_CHANNELTYPE_ASTEC4:
966 return PIOS_SetAstec4Speed(actuatorSettings->ChannelAddr[mixer_channel], value);
968 #endif
969 default:
970 return false;
973 return false;
975 #endif /* if defined(ARCH_POSIX) || defined(ARCH_WIN32) */
978 * @brief Update the servo update rate
980 static void actuator_update_rate_if_changed(bool force_update)
982 static uint16_t prevBankUpdateFreq[ACTUATORSETTINGS_BANKUPDATEFREQ_NUMELEM];
983 static uint8_t prevBankMode[ACTUATORSETTINGS_BANKMODE_NUMELEM];
984 bool updateMode = force_update || (memcmp(prevBankMode, actuatorSettings.BankMode, sizeof(prevBankMode)) != 0);
985 bool updateFreq = force_update || (memcmp(prevBankUpdateFreq, actuatorSettings.BankUpdateFreq, sizeof(prevBankUpdateFreq)) != 0);
987 // check if any setting is changed
988 if (updateMode || updateFreq) {
989 /* Something has changed, apply the settings to HW */
991 uint16_t freq[ACTUATORSETTINGS_BANKUPDATEFREQ_NUMELEM];
992 uint32_t clock[ACTUATORSETTINGS_BANKUPDATEFREQ_NUMELEM] = { 0 };
993 for (uint8_t i = 0; i < ACTUATORSETTINGS_BANKMODE_NUMELEM; i++) {
994 if (force_update || (actuatorSettings.BankMode[i] != prevBankMode[i])) {
995 PIOS_Servo_SetBankMode(i,
996 actuatorSettings.BankMode[i] ==
997 ACTUATORSETTINGS_BANKMODE_PWM ?
998 PIOS_SERVO_BANK_MODE_PWM :
999 PIOS_SERVO_BANK_MODE_SINGLE_PULSE
1002 switch (actuatorSettings.BankMode[i]) {
1003 case ACTUATORSETTINGS_BANKMODE_ONESHOT125:
1004 case ACTUATORSETTINGS_BANKMODE_ONESHOT42:
1005 case ACTUATORSETTINGS_BANKMODE_MULTISHOT:
1006 freq[i] = 100; // Value must be small enough so CCr isn't update until the PIOS_Servo_Update is triggered
1007 clock[i] = ACTUATOR_ONESHOT_CLOCK; // Setup an 12MHz timer clock
1008 break;
1009 case ACTUATORSETTINGS_BANKMODE_PWMSYNC:
1010 freq[i] = 100;
1011 clock[i] = ACTUATOR_PWM_CLOCK;
1012 break;
1013 default: // PWM
1014 freq[i] = actuatorSettings.BankUpdateFreq[i];
1015 clock[i] = ACTUATOR_PWM_CLOCK;
1016 break;
1020 memcpy(prevBankMode,
1021 actuatorSettings.BankMode,
1022 sizeof(prevBankMode));
1024 PIOS_Servo_SetHz(freq, clock, ACTUATORSETTINGS_BANKUPDATEFREQ_NUMELEM);
1026 memcpy(prevBankUpdateFreq,
1027 actuatorSettings.BankUpdateFreq,
1028 sizeof(prevBankUpdateFreq));
1029 // retrieve mode from related bank
1030 for (uint8_t i = 0; i < MAX_MIX_ACTUATORS; i++) {
1031 uint8_t bank = PIOS_Servo_GetPinBank(i);
1032 pinsMode[i] = actuatorSettings.BankMode[bank];
1037 static void ActuatorSettingsUpdatedCb(__attribute__((unused)) UAVObjEvent *ev)
1039 ActuatorSettingsGet(&actuatorSettings);
1040 spinWhileArmed = actuatorSettings.MotorsSpinWhileArmed == ACTUATORSETTINGS_MOTORSSPINWHILEARMED_TRUE;
1041 if (frameType == FRAME_TYPE_GROUND) {
1042 spinWhileArmed = false;
1044 actuator_update_rate_if_changed(false);
1047 static void MixerSettingsUpdatedCb(__attribute__((unused)) UAVObjEvent *ev)
1049 MixerSettingsGet(&mixerSettings);
1050 mixer_settings_count = 0;
1051 Mixer_t *mixers = (Mixer_t *)&mixerSettings.Mixer1Type;
1052 for (int ct = 0; ct < MAX_MIX_ACTUATORS; ct++) {
1053 if (mixers[ct].type != MIXERSETTINGS_MIXER1TYPE_DISABLED) {
1054 mixer_settings_count++;
1058 static void SettingsUpdatedCb(__attribute__((unused)) UAVObjEvent *ev)
1060 frameType = GetCurrentFrameType();
1061 #ifndef PIOS_EXCLUDE_ADVANCED_FEATURES
1062 uint8_t TreatCustomCraftAs;
1063 VtolPathFollowerSettingsTreatCustomCraftAsGet(&TreatCustomCraftAs);
1065 if (frameType == FRAME_TYPE_CUSTOM) {
1066 switch (TreatCustomCraftAs) {
1067 case VTOLPATHFOLLOWERSETTINGS_TREATCUSTOMCRAFTAS_FIXEDWING:
1068 frameType = FRAME_TYPE_FIXED_WING;
1069 break;
1070 case VTOLPATHFOLLOWERSETTINGS_TREATCUSTOMCRAFTAS_VTOL:
1071 frameType = FRAME_TYPE_MULTIROTOR;
1072 break;
1073 case VTOLPATHFOLLOWERSETTINGS_TREATCUSTOMCRAFTAS_GROUND:
1074 frameType = FRAME_TYPE_GROUND;
1075 break;
1078 #endif
1080 SystemSettingsThrustControlGet(&thrustType);
1084 * @}
1085 * @}