Skip to content
← ESP-Drone

Project files

49 KB

Machine-translated by Robotheca from the original in Chinese (opens in a new tab). License: GPL-3.0-only (opens in a new tab).

1 OLDX-Open Source Multicopter Development Platform Project

Project Honors

ProjectAwardYear
IMAV International Micro Aerial Vehicle Competition3rd Place in Outdoor Competition, Best Automation Indoors2018
AVIC CupThird Prize2018
IMAV International Micro Aerial Vehicle Competition5th Place in Outdoor Competition2017
AVIC CupSecond Prize2017
AVIC CupThird Prize2016

- If this project has been helpful to you, please Star our project - - If you are willing to share your optimizations and improvements for this project, please contact golaced@163.com (opens in a new tab) or join our QQ group 567423074 to accelerate the progress of the open-source project -

2 Basic Function Introduction

____OLDX-FC is a multi-rotor flight control platform based on the STM32F4 series microcontroller. It adopts a dual-processor, dual-IMU redundant design, with flight control and integrated navigation running on different microcontrollers and interacting with high-speed data via serial port DMA.

It carries two sets of 6-axis inertial sensors, one 3-axis magnetometer, one barometer, and supports external compass access. The integrated navigation CPU uses the UCOS II embedded operating system and implements reliable fusion of GPS, optical flow, UWB, and barometer data based on the Kalman filtering algorithm, thereby achieving reliable hovering and waypoint flight both indoors and outdoors. The attitude and altitude control use the Active Disturbance Rejection Control (ADRC) algorithm to achieve reliable control of external disturbances, with the characteristics of fast response and good signal tracking performance. By improving the ADRC algorithm, it achieves sensitivity and rapid parameter adjustment for flight vehicle wheelbase, attitude, heading, and altitude in three channels. The flight control system encapsulates an SDK secondary development interface and some demos internally, enabling quick implementation of one-key takeoff and landing, visual landing, target tracking, and autonomous obstacle avoidance. In addition, multiple expansion interfaces are reserved for use as hardware carriers for ground robots, unmanned vehicles, and unmanned ships.

The flight control system transplanted the Mavlink heading setting source code, which can set waypoints, altitude, and speed arbitrarily based on QGround and MissionPlanner. Based on the Anonymous Ground Station, it can display and adjust parameters in real time for any fusion results, sensor parameters, control feedback expectations, and status information inside the flight control. Based on the onboard NRF2.4 communication chip, it can interact with ground handheld remote controls for data up to 900 meters away, displaying the aircraft's latitude and longitude and attitude in real time, and setting and modifying any parameters online, eliminating the inconvenience of carrying a computer or tablet for outdoor parameter adjustment.

Flight Control Features: *UCOS II Operating System (ALIENTEK) *ADRC Attitude Control *Kalman Integrated Navigation *SDK Rapid Development *Mavlink Waypoint Planning and Anonymous Ground Station for Quick Parameter Tuning *Mobile Remote Control End Status Display and Online Parameter Modification *GPS Navigation, Visual Navigation, Auto Landing, Optical Flow Image Positioning

Flight Control Performance Demonstration Video Links: SDK Development Demo (opens in a new tab) Outdoor GPS Waypoint Mapping and Ground Station Waypoint Setting (opens in a new tab) Visual Fixed Target Landing (opens in a new tab) Visual Moving Car Landing (opens in a new tab) Indoor QR Code Landmark Array Positioning (opens in a new tab) Outdoor Optical Flow Hovering (opens in a new tab) Indoor Barometer Altitude Hold (opens in a new tab)

3 PCB Hardware Parameters

The OLDX-FC hardware uses a 4-layer board design, powered by an external power module supporting 2S~4S battery power. It features up to 12 PWM outputs, 4 analog signal inputs, an onboard NRF2.4 communication chip, and reserves 6 serial ports and 1 CAN interface.

Hardware Parameters:

ItemParameter
ProcessorSTM32F405RGT6-2
Processor Performance32Bit ARM Cortex-M4 168MHz
Gyroscope & AccelerometerICM20602 + LSM6DS33
MagnetometerLIS3MDL
BarometerMS5611
Reserved InterfacesGPS-1 Serial-4 CAN-1 Image-1
PWM Output Channels8-channel PWM + 4 AUX
Power Supply5V input, 5V IO output
Aircraft TypeQuadcopter, Hexacopter, Octocopter, Coaxial Hexacopter
Altitude Hold Accuracy±0.02m (ultrasonic) ±0.1m (barometer)
Position Hold Accuracy±0.2m (GPS) ±0.1m (optical flow)

Flight Controller Case: Provides 3D-printed STL files for the flight controller case, designed with a buffer space for the barometer and a shock-absorbing ball base.

4 Software Description

____OLDX-FC is developed in C language using Keil5. The flight control part is based on the Anonymous early bare-metal program architecture, using a state machine to ensure the operation cycles of different threads. The attitude control part has been modified, using the rotation matrix under SO3 to obtain the outer-loop control error. The inner-loop attitude uses an improved ADRC controller to ensure stable tracking of the given angular velocity. For altitude control, the original complementary filtering fusion algorithm is replaced with an extended Kalman filter to fuse barometer and accelerometer data, and an ADRC controller is also used to control the vertical speed loop. For position control, the combined navigation module is used to receive serial port data to calculate the body velocity and position, employing a triple-loop control (position + velocity + acceleration) to control the aircraft's position.

For communication, in addition to retaining the Anonymous ground station parameter tuning function, 2.4G wireless communication is added, allowing the aircraft to be controlled using body gestures without a remote controller. Additionally, the Mavlink communication protocol is ported to achieve communication with Qground and MissionPlanner ground stations, enabling waypoint setting and trajectory display for outdoor aircraft. An SDK secondary development interface is added, encapsulating various commonly used functions such as velocity commands, position movement commands, heading flight, image target alignment, image target tracking, and landmark-guided landing with multiple sub-APIs. By writing simple procedures, complex intelligent navigation and image navigation functions can be achieved, making it highly suitable for demo development, electronic competitions, drone competitions, and DIY development. ____The combined navigation module is based on the UCOSII operating system and completes the fusion of GPS, UWB, optical flow, and accelerometer sensor data using UKF and KF algorithms. It employs a nonlinear AHRS algorithm to achieve reliable attitude resolution and body acceleration resolution, while reserving a CAN bus interface for easy expansion of other sensor data.

Flight Control Module

ItemParameter
Attitude ResolutionComplementary Filter (Anonymous)
Altitude FusionExtended Kalman (PX4)/Robust Kalman
Attitude ControlSO(3) Error (PX4) + PD (Angle) + ADRC (Angular Velocity)
Altitude ControlPD (Altitude) + ADRC (Vertical Velocity)
Position ControlPD (Altitude) + PID (Body Velocity) + P (Body Acceleration)
Communication Interface2.4G Wireless Communication (Anonymous + OLDX Handheld Remote) Serial Data Transmission (Anonymous + Mavlink)
Control MethodRemote Controller (PPM+SBUS) OLDX Handheld Remote SDK Autonomous Flight
External Control Signal4-Channel Servo Output Supports Using Flight Control for Two-Axis Gimbal Attitude Control and Brushless Gimbal Target Tracking (RobotMaster)
Ground Station SupportAnonymous Ground Station (Parameter Display + Waveform Display + Parameter Setting) Qground/MissionPlanner (Pose Trajectory Display + Waypoint Writing)

Combined Navigation Module

ItemParameter
Attitude ResolutionNonlinear AHRS/Gradient Descent/Extended Kalman/Complementary Filter (Anonymous)
Position FusionRobust Kalman/Unscented Kalman (AutoQuad)
Sensor InterfaceGPS (NEO-8M Radiolink Mini) + UWB (INF) + Optical Flow (Pixflow/OLDX-AMF) + Ultrasonic (Serial/PWM) + Laser Rangefinder (VL53L0X)

5 Flight Controller Usage Tutorial

5.1 PCB Interface Description

InterfaceDescriptionSupported Modules
Flight Controller DownloadFlight controller SWD download portdownload_fc module C->SCLK D->SWD
Navigation DownloadNavigation module SWD download portdownload_stlink module
Navigation UART1GPS and external compass IIC interfaceHolybro M8N Mini GPS C->SCL D->SDA
Navigation UART5Optical flow sensor interfacePixflow OLDX-AMF
Navigation UART3Ultrasonic interfaceUS100 (T->T R->R in UART mode) Benewake TF-Luna LiDAR module
Navigation UART4Reserved sensor interface
Navigation CANReserved CAN bus interface
Flight Controller UART3Image processing interfaceRaspberry Pi Odroid-XU4 (image processor requires separate power supply)
Flight Controller UART1Telemetry interfaceAnonymous telemetry 3DR telemetry CUAV WiFi telemetry
PWM1~8ESC interface400Hz
AUX1~4ESC 9~12/servo control interface 1 pitch 2 roll 3 delivery switch2-axis servo gimbal 2-axis brushless gimbal
AD1~4Analog voltage acquisition interfacePressure sensor AD (0~3.3V)
SBUSReceiver interfaceFlysky receiver Futaba receiver
Servo power selectionR39 external power supply R38 flight controller power supply (choose one)
Power supplyUses 6P self-locking double-head connector to connect with power modulepower module +->DC B->Buzzer signal 5->5V step-down input

Minimum Required Configuration for OLDX Flight Controller

Module CombinationFunctions
Flight Controller + Power ModuleManual flight / Barometric altitude hold
Flight Controller + Power Module + Optical FlowManual flight / Barometric altitude hold / Ultrasonic altitude hold / Optical flow hover / SDK flight
Flight Controller + Power Module + GPSManual flight / Barometric altitude hold / GPS waypoint flight / SDK flight
Flight Controller + Power Module + GPS/Optical Flow + Raspberry Pi / OdroidManual flight / Barometric altitude hold / GPS waypoint flight / SDK flight / Visual navigation / Vision-based landing

Wiring Diagram

5.2 Program Macro Definitions and Flight Controller Configuration Instructions

5.2.1 Remote Control Channels

ChannelFunctionChannel Description
CH1Roll Channel
CH2Pitch Channel
CH3Throttle Channel
CH4Yaw Channel
CH5SDK Mode EnableChannel value <1500 (SDK auto flight disabled) Channel value >1500 (SDK auto flight enabled)
CH6Return-to-Home and Auto TakeoffChannel value <1500 (AUX3 port switch ON) Channel value >1500 (AUX3 port switch OFF)
CH7Position ModeChannel value <1500 (Manual) Channel value =1500 (Speed Hold) Channel value >1500 (Position Hold)
CH8Altitude ModeChannel value <1500 (Ultrasonic/Barometer auto-switch) Channel value =1500 (Barometer) Channel value >1500 (Manual)

Aircraft Unlock/Lock: Perform a "moustache" gesture with the remote control Turn off remote control during flight: Auto return-to-home / auto landing / motor emergency stop Auto takeoff and intelligent flight: CH5>1500 CH6>1500 CH7>1500 CH8<1500 Unlock with a "moustache" gesture while in this state, and place the throttle in the middle position (if any remote stick is not in the middle during autonomous flight, it will enter autonomous flight mode; after returning to the middle position, it will continue executing the current task. To cancel the flight, ensure CH5<1500) Reset autonomous task state machine: After the aircraft completes an autonomous task, whether it lands automatically or is interrupted manually, ensure CH5<1500 CH7<1500 after landing and locking Auto return-to-home during flight: Whether in autonomous flight or manual remote control flight, if the CH6 channel value switches from >1500 to <1500, the failsafe strategy is triggered. The process can be interrupted by manual remote control and triggered again Gyroscope calibration: When CH8<1500, quickly switch CH7 from <1500 to >1500 multiple times Magnetometer calibration: When CH8>1500, quickly switch CH7 from <1500 to >1500 multiple times. After entering the mode, the buzzer will continuously sound and the blue LED will flash at 1-second intervals

5.3 Flight Controller Configuration and Control Parameter Adjustment Instructions

5.3.1 Aircraft Configuration

(1) Flight control module include.h

Macro DefinitionDescription
USE_OLDX_REMOTEUse OLDX handheld remote control instead of traditional remote control
AUTO_MISSIONEnable SDK flight
MAXMOTORSMaximum number of motors (4/6/8/12)
FLASH_USE_STM32Use STM32 internal EEPROM to simulate Flash. If enabled, GPS waypoints cannot be stored.
YAW_INVERYaw control output direction. Used for software adjustment when motor rotation direction does not match the standard direction; no need to reinstall motors.
YAW_FCDo not use magnetometer to correct yaw
MAX_CTRL_ANGLEMaximum controlled attitude angle
MAX_CTRL_YAW_SPEED_RCMaximum controlled yaw angular speed
ESO_AIAttitude control inner-loop ADRC b0 parameter (0 means ADRC controller is not used)
ESO_YIYaw control inner-loop ADRC b0 parameter (0 means ADRC controller is not used)
HOLD_THR_PWMPreset hover throttle
DEBUG_MODEIf indoors, PWM output is closed. After unlocking, motors do not rotate and can be used for indoor debugging.
TUNING_ONE_AXIXIf enabled, parameter tuning only targets one axis
TUNING_X/ TUNING_ZSingle-axis tuning target
USE_KFUse Kalman filter with estimated acceleration bias to estimate altitude; otherwise use PX4's EKF altitude estimation algorithm
USE_CARGOUse servo cargo dropper on AUX3

(2) Flight control module oldx_api.h

Macro DefinitionDescription
LAND_SPDAuto-landing speed
MAX_WAYP_ZMaximum waypoint height limit
WAY_POINT_DEAD1Waypoint arrival dead zone
LAND_CHECK_GGround detection weight acceleration
LAND_CHECK_TIMEGround detection condition judgment time
YAW_LIMIT_RATEMaximum yaw angular speed limit

(3) Navigation module include.h

Macro DefinitionDescription
USE_UKF_FROM_AUTOQUADUse Autoquad's UKF fusion algorithm (has bugs)
UKF_IN_ONE_THREADDo not use UcosII system during UKF fusion
USE_US100/ USE_KS103/ USE_LIDARAltitude sensor data selection
SONAR_SAMPLE1/ SONAR_SAMPLE2/ SONAR_SAMPLE3Altitude sensor data sampling frequency
USE_IMU_BACK_IO_AS_SONARUse UART4 to collect altitude sensor data
SONAR_USE_FLOWDirectly use Pixflow sensor's built-in ultrasonic altitude data

Aircraft Model Settings: (1) Define your aircraft using the following macro definitions

#if defined(M_DRONE)
#define M_DRONE_ID     // MCU id_chip value
#define PX4_SDK 0
//#define PX4_LINK
#define USE_MINI_FC_FLOW_BOARD 0
#define USE_VER_8_PWM 1
#define USE_VER_8 0
#define USE_VER_7 1
#define USE_OLDX_REMOTE 0

#define BLDC_PAN
#define W2C_MARK
#define USE_CIRCLE 0
//#define USE_LED
//#define USE_CARGO     // Can be modified
#define AUTO_MISSION    // Can be modified

//#define USE_KF	    // Can be modified
#define USE_UWB
#define MAXMOTORS 		(4)		// Can be modified
#define FLASH_USE_STM32 0       // Can be modified
#define YAW_INVER 	  0		// Can be modified
#define YAW_FC 0  			// Can be modified
#define MAX_CTRL_ANGLE			30.0f	// Can be modified
#define MAX_CTRL_YAW_SPEED_RC   200	// Can be modified

#define ESO_AI 22  // Can be modified
#define ESO_YI 22  // Can be modified
//
#define TRAJ1_1  2//2 circle 1 line  3 way points   4 jerk  5 car
#define HOLD_THR_PWM  LIMIT(500,0,500)  // Can be modified
#endif
#define M_DRONE
//#define M_DRONE250X4
//#define M_DRONE_330X6
//#define M_DRONE_330
//#define M_DRONE_PX4
//#define M_CAR
switch(id_chip)
{
case M_DRONE_ID: CHE=25;break;
case IMAV2: CHE=22;break;
case IMAV3: CHE=33;break;
default: CHE=11;break;
}
switch(mission_sel_lock)
{
case 0:
switch(id_chip)
{
case M_DRONE_ID: mission_flag=mission_test_gps(T); break;//Your SDK
case IMAV2: mission_flag=mission_search(T); break;
case IMAV3: mission_flag=mission_test_gps(T); break;
default:mission_flag=mission_test_gps(T); break;
}
break;

5.3.2 Parameter Tuning

After completing the flight controller setup and firmware update, the flight controller has integrated basic parameter tuning functions. You can start tuning immediately after sensor calibration, either by taking off right away or by performing parameter tuning.

(1) Remote Parameter Tuning and Waveform Display The flight controller communicates with the OLDX handheld remote control via 2.4G wireless by default. Parameters can be tuned directly through the remote control. Additionally, the handheld remote control also has a USB virtual serial port. After connecting to a PC, you can use the Anonymous Ground Station for parameter tuning (default baud rate 115200) and parameter waveform display. (Note: For the handheld controller, it is recommended to wait until all PID parameter data is fully received before tuning parameters; otherwise, parameter miswriting may occur, leading to crashes. For the ground station, it is also recommended to read the PID parameters at least 5 times after normal data communication to avoid miswriting issues.)

(2) Attitude Parameter Tuning After installing the flight controller, you first need to tune the attitude parameters. It is recommended to secure the aircraft using a gimbal stand or a baking quadcopter frame for parameter tuning. Select the tuning mode to confirm whether it is single-axis or omnidirectional tuning:

TUNING_ONE_AXIX 0
TUNING_X 0
TUNING_Z 0

By default, all are set to 0, meaning all attitude parameters of the aircraft can be tuned. Taking this scenario as an example, set UART_UP_LOAD_SEL=11 to enable the ground station waveform display for attitude parameter tuning sequence. By setting CH6 (>1500 for outer loop), you can choose to display the desired and given parameters of the inner or outer loop. In the waveform, Ax Ay Az represent the desired roll, pitch, and yaw values, while Gx Gy Gz represent the corresponding feedback values, and Hx Hy Hz represent the corresponding errors. During parameter tuning, if the outer loop PID parameters have values, the remote stick will provide the desired angle; otherwise, it will provide the desired angular velocity.

A. If the aircraft frame size is less than 550mm wheelbase, you can directly adjust the sensitivity to quickly complete parameter tuning. Use manual mode to take off and ensure the aircraft is off the ground to observe whether the attitude control responds quickly, whether there is overshoot or jitter. The sensitivity corresponds to the PID parameters as follows:

ParameterDescriptionDefault Value
PID17-PRoll and Pitch Sensitivity (increasing equals increasing aircraft tuning gain)1000
PID17-IYaw Sensitivity1000
PID17-DAltitude Sensitivity1000

Aircraft ModelMain Power ConfigurationAircraft Sensitivity
330X4 Quadcopter3s 4000mah 1500kv*4 T-Motor MN15A 8-inch propellersPitch:1000 Yaw:1000 Altitude:1000 b0:22
450X4 Quadcopter4s 4000mah 920kv*4 T-Motor MN20A 9-inch propellersPitch:820 Yaw:1000 Altitude:1100 b0:22
6-Axis Foam Aircraft3s 10000mah 920kv*6 Emax 40A 8-inch propellersPitch:300 Yaw:200 Altitude:100 b0:3.5
Coaxial Contra-Rotating 6-Axis Ducted Fan6s 10000mah 450kv*12 Emax40A 9-inch propellersPitch:250 Yaw:280 Altitude:68 b0:2.2
6-Axis Aircraft + Small Car Chassis6s 16000mah2 180kv6 Emax40A 14-inch propellersPitch:325 Yaw:168 Altitude:100 b0:0 II:400 ID:4500 OP:368 P_GAIN:100

B. If the aircraft has a larger wheelbase and lower motor KV values, it is not recommended to use the takeoff tuning method. Secure the aircraft on a test stand, use manual mode to unlock and tune, and observe the inner and outer loop waveform curves. During tuning, first set the ADRC controller b0 to 0 to disable its control output, and clear the outer loop PID to only adjust the angular rate loop. After unlocking, observe whether the aircraft can track the remote control's given speed well. Once basic tracking is ensured, adjust the attitude ADRC b0 within the range of 22-300 (default 220). If the aircraft oscillates, reduce the value; if it feels sluggish, increase it. After achieving basic tracking of the desired speed (some lag is acceptable, especially for large aircraft), determine whether to increase the D gain by pulling the aircraft's axis to create external disturbances and controller saturation. If there is overshoot when pressing, increase the D gain to ensure a smooth rebound.

After completing the inner loop parameter tuning, set the outer loop P gain (default 500-700). Ensure some overshoot occurs with the P gain, then increase the D gain to achieve final centering without rapid overshoot (small aircraft below 550 may not need D). Similarly, use manual pulling or pressing tests to check if the controller saturates and returns to center without overshoot or oscillation to determine if the parameters are appropriate.

For yaw, generally only adjusting the sensitivity is sufficient for general applications. For higher performance requirements, you can use a similar method for parameter tuning. Additionally, the yaw ADRC b0 parameter is recommended for use only on small wheelbase aircraft. The corresponding PID parameters for attitude tuning are as follows:

ParameterDescriptionDefault Value
PID1-PRoll and Pitch Inner Loop P700
PID1-IRoll and Pitch Inner Loop I200
PID1-DRoll and Pitch Inner Loop D2200
PID2-PAttitude ADRC b0220
PID2-IYaw ADRC b0220
PID2-DADRC Control Dead Zone268
PID3-PYaw Inner Loop P1200
PID3-IYaw Inner Loop I100
PID3-DYaw Inner Loop D1200
PID4-PRoll and Pitch Outer Loop P700
PID4-IRoll and Pitch Outer Loop I0
PID4-DRoll and Pitch Outer Loop D0
PID6-PYaw Outer Loop P800
PID6-IYaw Outer Loop I50
PID6-DYaw Outer Loop D300

After completing parameter tuning, you can save them to Flash in two ways. For sensitivity, you can use the remote control to trigger the gyroscope to write (keep it level and stationary), but it is still recommended to modify them in the code. For the ADRC b0 parameters, modify them in the aircraft model macro definition. For aircraft sensitivity, modify them in the Debug watch and then select gyroscope calibration (see section 6.4.2) to save. For attitude PID parameters, modify them in parameter.c line 40:

float pid_att_out[3]={0.7,0.0,0.0};
float pid_att_in[3]={0.7,0.2,2.2};

float pid_att_out_yaw[3]={0.8,0.05,0.3};
float pid_att_in_yaw[3]={1.2,0.1,1.2};

(3) Altitude Parameter Tuning The altitude parameter tuning method is similar to attitude tuning. If high performance is not required, you can use the default parameters and adjust the sensitivity for quick takeoff. Alternatively, you can use the ground station to compare the desired waveform for tuning. Set UART_UP_LOAD_SEL=2 to display the altitude control waveform sequence. Similarly, first set the ADRC b0 to 0, then tune the inner loop followed by the outer loop. Ensure the attitude parameters are reliable during tuning. If oscillations occur, quickly switch to manual mode to land.

scheduler.c line 282
case 2://Altitude control, speed z control and speed xy
data_per_uart1(
ALT_POS_BMP_UKF_OLDX*1000,ultra_ctrl.exp,baro.h_flt*100,
ALT_VEL_BMP_UKF_OLDX*1000, wz_speed_pid_v.exp,wz_speed_pid_v.now,
VEL_UKF_Y*100,VEL_UKF_X*100,0,
(int16_t)(Yaw_fc*10),(int16_t)(Pit_fc*10.0),(int16_t)(Rol_fc*10.0),thr_value,0,0/10,0);break;
ParameterDescriptionDefault Value
PID7-PAltitude Inner Loop P500
PID7-IAltitude Inner Loop I300
PID7-DAltitude Inner Loop D1680
PID8-PAltitude Outer Loop P1000
PID8-IAltitude Outer Loop I100
PID8-DAltitude Outer Loop D0
PID12-PAltitude ADRC b015
PID12-I
PID12-DAltitude ADRC Dead Zone10

Saving parameters is similar to attitude control. The parameters in the program are as follows:

height_ctrl.c line 41

ultra_pid.kp = 1.0;
ultra_pid.ki = 0.1;
ultra_pid.kd = 0.0;

wz_speed_pid.kp = 0.5;
wz_speed_pid.ki = 0.3;
wz_speed_pid.kd = 1.68;
wz_speed_pid.fp=0.2;

//adrc
eso_pos_spd[Zr].b0=15;
eso_pos_spd[Zr].eso_dead=0.01*1000;
eso_pos_spd[Zr].eso_for_z=1;

(4) Position Parameter Tuning The position parameter tuning method can use the above tuning method. The waveform sequences are UART_UP_LOAD_SEL=3 (speed) and UART_UP_LOAD_SEL=5 (position). Ensure the attitude parameters are reliable during tuning. If oscillations occur, quickly switch to manual mode to land. If the altitude parameters are stable, you can use barometric altitude hold for takeoff. After reaching chest height, switch to speed mode, give an attitude command, and observe whether it returns to center reliably and whether there is jitter during braking. If the angle is too large, reduce the speed inner loop P gain (other parameters do not need to be adjusted). After the speed loop braking is smooth and hover has no obvious jitter, switch to position mode to observe if there is any drift. By giving a speed command to brake, observe the aircraft's control effect. For small aircraft, you can still use manual pulling to verify.

ParameterDescriptionDefault Value
PID9-PPosition Inner Loop P330 (For large wheelbase aircraft, it can be reduced to 180)
PID9-IPosition Inner Loop I0
PID9-DPosition Inner Loop D0
PID10-PPosition Outer Loop P360
PID10-IPosition Outer Loop I50
PID10-DPosition Outer Loop D0

Saving parameters is similar to attitude control. The parameters in the program are as follows:

pos_ctrl.c line 321

nav_pos_pid.kp=0.36;
nav_pos_pid.ki=0.0500;
nav_pos_pid.kd=0.0;
nav_pos_pid.dead=0.01;

nav_spd_pid.f_kp=0.2;
nav_spd_pid.kp=0.33;
nav_spd_pid.ki=0;
nav_spd_pid.kd=0;
nav_spd_pid.max_exp=0;

nav_spd_pid.flt_nav=1;//Change to around 0.356 for smooth braking feel. Currently, an S-function has been added in the program to ensure smooth braking

5.4 Introduction to the Handheld Remote Controller (OLDX-Remote)

To improve parameter adjustment speed and reduce the need for a PC and ground station software during outdoor flights, the OLDX flight controller is equipped with a handheld remote controller. In addition to allowing control of the aircraft via motion sensing mode, it can also replace the PC ground station for real-time parameter adjustments. It also provides real-time feedback on the main and sub-state machines of the SDK, expected altitude and speed information, and waypoint route data. This enables users to monitor the current SDK operation status and the aircraft's target tasks for the next moment, addressing the challenge of obtaining internal state information during autonomous flight.

5.4.1 Interface Introduction

After powering on, OLDX-Remote will display the current remote control channel. Please ensure it matches the flight controller (previously modified online). The remote control currently has three types of interfaces:

  1. Main Interface: Displays commonly used data such as the aircraft's altitude, attitude, voltage, and flight time.
  2. PID Parameter Interface: Displays the internal parameters of the aircraft, corresponding to the PC ground station.
  3. SDK Interface: Displays the route and autonomous mission commands, as well as the state machine status.

The abbreviations for each interface are as follows:

Main Interface

AbbreviationDescription
POLDX-Remote pitch stick value (body sensing)
ROLDX-Remote roll stick value (body sensing)
TOLDX-Remote throttle stick value (stick)
YOLDX-Remote yaw stick value (stick)
SRCommunication strength between flight controller and OLDX-Remote
BROLDX-Remote battery level
BFAircraft battery level (below 25% during flight requires immediate landing)
MAircraft mode: Mual -> Manual, ALT B -> Barometer, ALT S -> Ultrasonic, Pos -> Position parameter adjustment
Bad PosPositioning mode status: Bad Pos -> No positioning, GPS -> Number of satellites (recommended to take off with more than 8), Opt -> Optical flow quality (recommended to take off with more than 120 on the ground)
lockAircraft lock status
Rectangle interface PAircraft pitch angle
Rectangle interface RAircraft roll angle
Rectangle interface YAircraft yaw angle
Rectangle interface 0:0Flight time after unlocking
Rectangle interface X, Y, ZAircraft local X-axis position (meters)
Rectangle interface three square dotsFrom top to bottom: *GPS connection, *image device connection, *optical flow module connection
Center circle and solid dotIn single imaging, if the c2c structure pix_x, y has data, the origin will be displayed. It can be used to determine the pixel position of the image target and its recognition in the image

PID Parameter Interface

AbbreviationDescription
PIDX-XCorresponding parameter in the upper computer
Toggle the remote stick left and right to the end for about 2 seconds to switch interfaces
Toggle left and right/up and down to select PID parameters
Click the remote control to display * to select the parameterAfter selection, toggle left to increase the parameter by 100, toggle up and down to increase by 10
Select again and click to exit selection —The remote control reads the flight control data every 5 seconds. No reading when selected
Long press the remote control to emit a "BB" sound, indicating parameter write-inFor CHE remote control channel, write-in requires the same operation in the main interface, and the remote control IMU will be calibrated simultaneously

SDK Interface

AbbreviationDescription
mainIdle (default state of the state machine, this state will only run the SDK after automatic takeoff), Mission (SDK mode), Safe (state machine protection enters normal hover mode, requires landing and locking, then resetting the remote control switch to clear)
% to the right of RCAircraft battery level
SubsSub-state machine status
WayRemaining waypoints
Vertical bar to the leftHeight expectation and feedback: Position mode (expectation is a horizontal line, current is the center of the rectangle), Speed mode (displays expected ascending/descending speed)
Rectangle framePosition expectation and feedback: The center is the current aircraft position, the origin is the expected position (coordinate system is x-y, East-North), the coordinate system scale is automatically zoomed, and the small horizontal line indicates the aircraft's body direction
DisDistance to the next waypoint (meters)

5.4.2 Introduction to Remote Control Mode

The OLDX-Remote board is equipped with an MPU6050 IMU sensor, enabling motion-controlled operation. Modify the following in include.h:

#define USE_RECIVER_MINE 1

In motion-controlled operation:

  • The up and down movements of the remote control joystick correspond to throttle.
  • Left and right movements correspond to yaw.
  • Tilting forward and backward corresponds to pitch.
  • Tilting sideways corresponds to roll.

To unlock the aircraft, hold the joystick in the bottom-right position for 2 seconds. You can perform zero-bias calibration of the remote control's neutral position by long-pressing the joystick button on the main interface.

6 First Flight Instructions (Taking a Quadcopter as an Example)

6.1 Flight Controller Installation and Firmware Download

First, install the OLDX flight controller along the nose direction at the center of the aircraft body. It is recommended to use vibration damping (misalignment may introduce additional acceleration due to rotational effects, affecting braking or hovering). The image below shows the typical wiring order of the ESC PWM signal lines and propeller rotation directions for a drone. If the motor rotation direction is opposite to the image, you can either reinstall the motors or set YAW_INVER to 1:

After installing the ESCs and flight controller, connect the Power module to the flight controller's power input using a 6P double-headed self-locking connector. At the same time, solder the Power module's DC input to the aircraft's main power input (2S~4S). Remove the propellers and use the following method to connect the flight controller's power supply for downloading via the download tool and ST-Link programmer:

After confirming that the ST-Link driver is installed correctly, first download the firmware to the flight controller's MCU. After downloading, you can run it in Debug mode or power cycle the board. If the system is working properly, the buzzer will sound and the LED will flash. Then, using the same method, download the firmware to the IMU navigation MCU. After running, check the lis3mdl structure in Watch (if it doesn't appear, manually add it; also ensure that Periodic Update is selected under the View menu). Verify that Acc_I16, Gyro_16, and Mag_Adc contain valid numbers. If they do (indicating normal sensor readings), place the board horizontally and set Acc_CALIBRATE and Gyro_CALIBRATE to 1. Check the Acc_Offset and Gyro_Offset values stored in the current sensor offsets. After resetting the chip, verify that the readings remain consistent to confirm that the onboard Flash chip is functioning properly. After completing the IMU firmware download and circuit verification, debug the flight controller's MCU again. At startup, the buzzer should play the startup melody. Check if the sensor parameters in the mpu6050_fc structure are refreshing. Calibrate the sensors and reset the chip to detect whether the calibration parameters from the last session are read from Flash. If everything is normal, the hardware is basically error-free, and you can attempt to fly.

Note: If you modify the following section, the startup buzzer sound can simulate the Pixhawk's sound:

// beep.c line 145
case START_BEEP:
    music_sel = START_BEEP;
    Play_Music(start_music_windows, 0, sizeof(start_music_windows)/2);
    break;

// Modify to:
case START_BEEP:
    music_sel = START_BEEP;
    Play_Music(start_music_px4, 0, sizeof(start_music_px4)/2);
    break;

Additionally, when installing the flight controller, it is best to cover the barometer with black foam and use a 3D-printed case to prevent airflow interference during flight!!

6.2 Flight Controller Configuration and Pre-flight Sensor Calibration

After completing the flight controller installation and circuit verification, define your aircraft and SDK in the flight controller as described earlier, adjust the parameters or fly with the default parameters. The first flight requires sensor calibration again.

(1) First, place the aircraft horizontally on the ground. Use the remote control switch method described earlier to calibrate the accelerometer and gyroscope for zero bias calibration. After completion, check whether the attitude angle in the ground station or handheld remote control slowly returns to 0.

(2) Next, use the remote control switch method to trigger the magnetometer calibration. During the calibration process, the buzzer will beep once per second and the LED will flash blue. At this time, pick up the aircraft and rotate it to ensure that the aircraft is rotated in each direction once, then continue rotating horizontally. Observe whether the LED exits the blue flashing mode to confirm that the calibration is complete. Also check the heading angle in the remote control to ensure it matches the local actual orientation (heading deviation may cause the aircraft to hover in circles or wobble).

After calibration, use the "outer eight" unlocking method to check the motor rotation to confirm it meets the installation requirements. Pushing the throttle stick should change the motor speed. The image below shows a common remote control switch mapping using the "Tiandi Fei 8-channel remote control" as an example.

Note: If using the remote control configuration shown in the image:

(1) When the altitude switch is in the upper position, quickly toggling the POS switch will trigger magnetometer calibration. When the altitude switch is in the lower position, quickly toggling the POS switch will trigger accelerometer and gyroscope calibration.

(2) With SDK switch up, failsafe switch right, altitude switch in the middle, and position switch up (confirm the main state machine is reset), after unlocking, moving the throttle stick to the middle position will trigger automatic takeoff and SDK flight.

(3) After landing from SDK flight, simply switch the failsafe to the left, position switch down, and SDK switch down to reset the state machine.

(4) During flight, rotating the failsafe switch from right to left will activate the failsafe protection strategy.

6.3 LED Status Display

The OLDX flight controller is equipped with a tri-color LED that can display basic flight control system status. The specific LED blinking patterns are shown in the table below:

LED Blinking PatternDescription
Red Fast BlinkingRemote control not connected
White Breathing LightFlight control system normal
Blue Fast BlinkingMagnetometer calibration

6.4 Manual Flight

After completing the flight controller installation, ESC order confirmation, motor rotation direction check, and flight parameter configuration, as well as sensor calibration, you can check whether the parameters are appropriate through the manual flight mode. The specific steps are as follows:

  1. Power on and wait for the remote control to connect (white breathing light).
  2. Check the handheld remote control to confirm that the attitude angle is correct.
  3. Ensure that altitude mode and position mode are in manual state.
  4. Unlock the aircraft, gently push the throttle to confirm that the motor rotation direction is correct.
  5. Push the throttle to find the takeoff throttle of the aircraft.
  6. After ensuring the aircraft is 0.5 meters off the ground, toggle the remote control stick, and observe the feedback data on the ground station or visually check whether the control parameters are appropriate.

6.5 Altitude-hold Flight

After completing manual flight, you can perform altitude-hold testing:

(1) After ensuring the aircraft is working properly, switch to barometric altitude-hold mode. (2) Unlock the aircraft, then push the throttle to above mid-position; the aircraft will take off, and the stick corresponds to upward/downward speed. (3) After ensuring the aircraft is 0.5 meters above the ground, toggle the stick, and observe the feedback data on the ground station or visually check whether the control parameters are appropriate.

6.6 Position Hold

After completing altitude hold flight, you can perform position hold testing:

(1) Ensure the aircraft is functioning properly, then switch to barometric altitude hold mode (2) Ensure GPS positioning has at least 6 satellites or the optical flow sensor is connected with a Qual value greater than 150 and installed in the correct orientation (3) Unlock and take off in altitude hold mode (4) After confirming the aircraft is 0.5 meters above the ground, switch to velocity mode to check if the aircraft has braking capability, then switch to position mode to verify if it can maintain a hover accuracy within 0.2 meters

6.7 Waypoint Flight

____OLDX flight controller has ported the Mavlink communication protocol and currently supports communication with the QGround ground station for waypoint settings. Due to ongoing improvements to the communication protocol, the following functions are currently supported:

(1) Basic status monitoring of the aircraft: attitude angle, altitude, GPS position, number of GPS satellites, aircraft battery level (2) Waypoint writing

____Functions under development include: (1) Waypoint reading (2) Automatic takeoff and RTL return (3) Sensor calibration (4) Parameter adjustment

Below is a detailed explanation of the waypoint parameter writing operation:

Explanation of relevant parameters for each waypoint:

ParameterDescription
AltitudeWaypoint altitude
HoldWaypoint dwell time
HeadingWaypoint heading
AcceptanceFlight speed (Note: Due to protocol issues, waypoint speed cannot be set using Flight Speed)

____To uniformly modify the route altitude, first set the altitude of the first waypoint, and the altitudes of subsequent waypoints will be consistent with it. After writing the waypoints, the upper computer will display the writing process, but due to communication issues, protocol error prompts may appear. At this point, cancel and repeatedly write the waypoints. If the waypoint writing is normal, the flight controller will emit a "BB" beep, and you can check whether the number of written waypoints is consistent in the SDK interface of the handheld remote control.

6.8 SDK Autonomous Flight

The SDK autonomous flight feature is the most unique and important function of the OLDX flight controller compared to all other open-source flight controllers currently on the market. It aims to provide an easy way to quickly implement complex control logic and vision-based navigation programming. In the future, MicroPython will be used as the core of SDK programming, enabling intuitive and simple SDK programming based on a graphical interface. For specific development, please refer to Section 7. The process to enable SDK flight is as follows:

(1) Use #define AUTO_MISSION in the flight controller's macro definitions and define the selected SDK in the Pos_ctrl.c file. (2) Ensure that a GPS or optical flow sensor is connected. (3) Before takeoff, confirm that the main state machine is in IDLE mode. (4) Enable SDK via the remote control switch, and turn on Position Mode and Altitude Hold Mode. (5) After unlocking the aircraft, push the throttle to the middle position. If all other control sticks are centered, the aircraft will automatically take off and execute the SDK flight. (6) During flight, you can observe the execution of the autonomous mission in real time on the SDK interface of the handheld remote control. During autonomous flight, you can interrupt the flight via remote control or use the failsafe return-to-home function.

7 Advanced SDK Development Instructions

7.1 Writing the Main State Machine

For SDK development, you only need to complete the main state machine framework and SDK calls. Define your SDK program in oldx_mission.c and call it in pos_ctrl.c. The specific SDK framework is as follows:

u8 mission_test(float dt)
{
	u8 flag=0,mission_finish=0,temp=0;
	static float mission_time;

	switch(mission_state){
	case 0:
			   flag=take_off_task1(2,1.5,dt);
		   break;
	case 1:
			   flag=set_drone_z_task(5.5,dt);
	       break;
	case 2:mission_finish=1;
	       break;
	default:break;
	}

	if(flag)
		mission_state++;

	mission_time+=dt;

	if(mission_finish)
	  return 1;
  else
      return 0;
}

The above code provides a simple SDK program that automatically takes off and hovers at a height of 5.5 meters. The SDK is driven by a state machine, where each state calls an API to set flag to 1, indicating that the subtask is completed and advancing the state flag mission_state. Multiple tasks can be performed in the same state, but you need to ensure which one triggers the flag. You can also design your own state transition conditions without using APIs. State transitions can also skip sequential execution by directly assigning values to mission_state for special state handling. Several demo examples are provided in this file for reference and modification to implement SDK development.

7.2 SDK Introduction

Here are the detailed descriptions of the input and output for the currently supported API functions in this version:

set_pos_taskSet the global target position of the aircraft
x,y,zGlobal coordinate system position (meters). If a parameter is 0, the current position of that axis is maintained.
Completion conditionGlobal position error is less than WAY_POINT_DEAD

way_point_taskSet the GPS target position of the aircraft
lat,lon,heightDesired GPS position. If a parameter is 0, the current position of that axis is maintained.
loter_timeHover time at this waypoint
modeIf mode==MODE_FAST_WAY, it is the fast flight mode (amplifies the judgment condition for waypoint control error)
Completion conditionTarget error is less than WAY_POINT_DEAD1 and is maintained for MISSION_CHECK_TIME

way_point_missionWaypoint flight
spd_limitOverall heading speed limit (each waypoint speed can be set in the upper computer; if it is 0, this parameter limits the flight speed)
head_to_waypointIf 1, the nose points toward each waypoint
modeIf mode==MODE_FAST_WAY, it is the fast flight mode (amplifies the judgment condition for waypoint control error)
Completion conditionAll waypoints are passed

return_homeReturn to home
set_zReturn altitude
spd_limitSpeed limit
en_landIf 1, automatic landing is executed after return
head_to_homeAircraft orientation toward the return point
Completion conditionReturn mission is completed

spd_move_taskSet speed for the aircraft
x,y,zSet speed. If 0, the axis maintains its current position.
timeDuration of the set speed
Completion conditionSet time is reached

pos_move_global_taskMove forward, backward, left, or right in the global coordinate system
x,y,zDistance to move
Completion conditionSet position is reached

pos_move_body_taskMove forward, backward, left, or right in the body coordinate system
x,y,zDistance to move
Completion conditionSet position is reached

pan_set_taskControl the gimbal pitch angle
pitchSet angle
Completion conditionNone

pan_search_taskGimbal up-down search API
minMinimum angle
maxMaximum angle
daAngle increment
en_yawIf 1, the yaw will also search left and right during the search
en_forwardIf 1, the aircraft moves forward at 0.3 m/s after each search cycle
Completion conditionNone

down_ward_search_taskCircular trajectory search
rCircular trajectory radius
zFlight altitude
d_angleCircular trajectory angle increment
d_rRadius increment
Completion conditionNone

down_ward_search_task_tangleSnake-shaped waypoint trajectory planning
wNumber of waypoints for trajectory width
hNumber of waypoints for trajectory length
wnWidth interval distance
hnLength interval distance
spd_limitFlight speed limit
zFlight altitude
Completion conditionAll waypoints are passed

target_track_downward_taskTarget tracking with downward camera
targetTarget image information structure
spdzDescent speed
end_zStop descent altitude
modeMode MODE_SPD: Use pixel deviation MODE_POS: Use estimated global position
Completion conditionDescent altitude is reached

target_track_pan_taskTarget tracking with front gimbal
targetTarget image information structure
close_paramIn speed mode, it is the minimum gimbal angle; in position mode, it is the distance to the target
en_pitchEnable gimbal pitch axis alignment
en_yawEnable aircraft heading alignment
close_modeMode MODE_SPD: Use pixel deviation MODE_POS: Use estimated global position
Completion conditionGimbal reaches target angle or aircraft reaches set distance to the target

avoid_taskAutonomous obstacle avoidance
targetTarget image recognition result
set_xDesired forward X-axis speed
set_yDesired forward Y-axis speed
set_zNC
deadSpeed dead zone
max_spdMaximum obstacle avoidance speed
Completion condition

avoid_way_point_taskWaypoint autonomous obstacle avoidance
targetTarget image recognition result
tar_latTarget longitude
tar_lonTarget latitude
spdForward speed
deadSpeed dead zone
max_spdMaximum obstacle avoidance speed
modeMode NC
Completion conditionTarget position is reached

set_drone_yaw_taskSet aircraft heading
yawTarget heading angle
rate_limitRotation speed limit
Completion conditionTarget angle is reached

set_drone_z_taskSet aircraft altitude
zTarget altitude
Completion conditionTarget altitude is reached

aux_openAuxiliary channel switch setting
selAuxiliary channel
openSwitch
Completion condition

land_task1Landing
spdDescent speed
Completion conditionTouchdown detection standard is reached

delay_taskIdle wait
delayWait time (seconds)
Completion conditionWait time is reached

draw_heartSmooth heart pattern
timeTotal flight time (seconds)
sizeHeart size (meters)
Completion conditionWait time is reached

7.3 Common SDK Analysis

7.1 Automatic Takeoff → Route Flight → Automatic Return

This SDK is the most commonly used task architecture. By adding state judgments that interrupt route flight, it can quickly achieve target recognition triggered tracking during flight or automatic landing triggered by seeing a landing marker during flight.

u8 takeoff_mission_return(float dt)
{
	u8 flag=0,mission_finish=0,temp=0;
	static float mission_time;

	switch(mission_state){
	case 0:
			   flag=take_off_task1(5,1.5,dt);//Automatically take off at 1.5 m/s to reach 5 m altitude
		   break;
	case 1:
			   flag=delay(2,dt);//Wait for 2 s at this altitude
	       break;
    case 2:
			   flag=way_point_mission(2,NEN_HEAD_WAY,dt);//Fly at 2 m/s along the route; the heading angle during flight is the waypoint's set angle
		   break;
	case 3:
			   flag=return_home(15,2,EN_LAND,NEN_HEAD_WAY,dt);//Return home at 2 m/s from 15 m altitude; fly along the route with the heading angle set by the waypoint and land directly
	break;
	case 4:mission_finish=1;
	       break;
	default:break;
	}

	if(flag)
		mission_state++;

	mission_time+=dt;

	if(mission_finish)
	  return 1;
  else
      return 0;
}

7.2 Auto-takeoff → Area Search → Auto-return

____This SDK is part of a project in the IMAV competition. The project requirements are as follows: Before takeoff, the contestant is given the latitude and longitude of a simulated injured person 5 minutes prior. The drone must autonomously fly to the area above the coordinates, determine the injured person's location based on image information, and drop the medical box attached to the servo hook within a 5-meter radius of the injured person. Afterward, it must automatically return and perform a precise landing within 1 meter of the takeoff point based on image recognition.

float lat_human,lon_human;// Latitude and longitude of the injured person
u8 mission_search1(float dt)
{
	u8 flag=0,mission_finish=0,temp=0;
	float dis=0;
	static float mission_time;
	switch(mission_state){
	case 0:flag=take_off_task1(2,1.5,dt);// Auto-takeoff
		    break;
	case 1:pan_set_task(90,dt);// Gimbal downward
		   flag=set_drone_z_task(6,dt);// Reach takeoff altitude of 6m
		     mission_time=0;
		     break;
  case 2:  mode_oldx.sdk_flag=1;// Switch image recognition to injured person
		   flag=way_point_mission(1.6,NEN_HEAD_WAY,dt);// Begin waypoint mission
	       if(c2c.connect&&c2c.x<160+90&&c2c.x>160-90&&c2c.y<120+90&&c2c.y>120-90)// Injured person detected
				   cnt_task[5]++;

		   if(cnt_task[5]>20&&cnt_task[6]==0)// Switch to target alignment
		  {mission_state=102;cnt_task[0]=cnt_task[1]=cnt_task[2]=cnt_task[5]=flag=0;}
		     break;
	case 3:// If target not found at given coordinates, plan a serpentine search pattern
				 mode_oldx.sdk_flag=1;
				 flag=down_ward_search_task_tangle(10,10,3,3,0.6,7.5,dt);
				 if(c2c.connect&&c2c.x<160+90&&c2c.x>160-90&&c2c.y<120+90&&c2c.y>120-90)// Injured person detected
					 cnt_task[5]++;

				 if(cnt_task[5]>6&&cnt_task[6]==0)// Injured person found, switch to alignment state
					{mission_state=102;cnt_task[0]=cnt_task[1]=cnt_task[2]=flag=0;}

				 if(flag&&cnt_task[6]==0)// After search completion, repeat until timeout
				  {mission_state=2;cnt_mission[MISSION_CNT]=cnt_task[5]=cnt_task[0]=cnt_task[1]=cnt_task[2]=flag=0;}

				 if(cnt_task[6]==1)// If delivery is complete, return home
					 flag=1;
	       break;
  //------------------------------------------------------
	case 4:flag=return_home(12,2,NEN_LAND,NEN_HEAD_WAY,dt);// Return home
				 if(flag)
					cnt_task[0]=cnt_task[1]=cnt_task[2]=0;
	       break;
	case 5:flag=set_drone_z_task(6,dt);// Reach optimal altitude for landing marker recognition
				 break;
	case 6:mode_oldx.sdk_flag=0;// Switch image recognition to landing marker
				 flag=target_track_downward_task(&c2c,0.4,0.66,MODE_SPD,dt);// Use downward camera to align with landing marker
				 if(c2c.check)
				  cnt_task[0]=0;
				 else
				  cnt_task[0]++;

				 if(cnt_task[0]>10/dt)// If target not found during descent, switch to search mode
				 {mission_state=11;cnt_task[0]=cnt_task[1]=cnt_task[2]=0;
				 cnt_mission[C_SEARCH_T_INT]=cnt_mission[C_SEARCH_T_INT1]=flag=0;}

				 if(cnt_task[1]++>15/dt)
				 {flag=1;cnt_task[0]=cnt_task[1]=0;}
				 break;
	case 7:mode_oldx.sdk_flag=0;
				 flag=target_track_downward_task(&c2c,0.25,0.66,MODE_SPD,dt);
	       break;
	case 8:flag=land_task1(LAND_SPD,dt);// Vertical landing
	       break;
	case 9:mission_finish=1;
	       break;
	//-----------------------AUX MISSION----------------------------
	case 11:// Search for landing marker
	      mode_oldx.sdk_flag=0;//
	      flag=down_ward_search_task_tangle(8,8,4,4,0.4,5,dt);//tangle
			  if(c2c.check)
					 cnt_task[0]++;

				if(cnt_task[0]>5)
					{cnt_task[0]=0;mission_state=6;flag=0;}

				if(cnt_task[2]++>60/dt||flag)
				{mission_state=12;cnt_task[2]=0;flag=0;}
	      break;
	case 12:// If landing marker not found after searching one side, return home and auto-land using takeoff coordinates
			 if(return_home(4,0.8,NEN_LAND,NEN_HEAD_WAY,dt))
					mission_state=7;
			 break;
	case 13:// Waypoint mission
				flag=way_point_mission(1,NEN_HEAD_WAY,dt);
        if(flag)
				{flag=0;aux_open(2,1);mission_state=4;}
	break;
	//--------------------
	case 102:// Align with injured person, drop medical box after reaching set altitude
		    mode_oldx.sdk_flag=1;//
		    flag=target_track_downward_task_search(&c2c,0.25,4.5,dt);
				if(cnt_task[2]++>30/dt)
				{mission_state=3;cnt_task[2]=flag=cnt_task[5]=0;}

				if(flag)// Deliver cargo
				{mission_state=4;// to return home
				 cnt_task[2]=flag=0;
				 aux_open(2,1);
				 cnt_task[6]=1;// drop flag
				}
	      break;

	default:break;
	}

	if(flag)
		mission_state++;

	mission_time+=dt;
	if(mission_time>3*60&&(mission_state>=100||mission_state==3))// If mission times out, auto-return
	{mission_state=13;cnt_mission[C_SEARCH_T_INT]=cnt_mission[C_SEARCH_T_INT1]=0;}

	if(mission_finish)
	  return 1;
  else
    return 0;
}

7.3 Automatic Takeoff → LiDAR Obstacle Avoidance → Autonomous Return

This SDK is a project in the IMAV competition. The project requirements are as follows: 5 minutes before takeoff, the organizer provides the latitude and longitude of a previous injured person to the contestants. The drone needs to fly to the area autonomously, but unlike in 7.2, the target is located in dense forest. Therefore, the drone must be able to automatically avoid obstacles during the search. A 2D LiDAR is used to obtain obstacle avoidance velocity for the aircraft, allowing it to advance while searching and dodge trees.

u8 mission_avoid(float dt)
{
	u8 flag=0,mission_finish=0,temp=0;
	float lat,lon;
	static float mission_time;
	pan_set_task(90,dt);
	float dis=0;
	switch(mission_state){
	case 0:
			   flag=take_off_task1(1.68,1.5,dt);//Automatic takeoff
		    break;
	case 1:
				 pan_set_task(90,dt);
				 flag=set_drone_z_task(1.68,dt);//Hover at 1.6 m
				 lat=navData.missionLegs[LIMIT(navData.Leg_num-1,0,99)].targetLat;//Given latitude and longitude
				 lon=navData.missionLegs[LIMIT(navData.Leg_num-1,0,99)].targetLon;
				 mission_time=0;
		     break;
	case 2:
		     mode_oldx.sdk_flag=1;//Switch to image-based injured person detection
		     set_drone_z_task(1.5,dt);//Desired height for terrain-following search
			 flag=avoid_way_point_task(&c2c,lat,lon,0.25,0.2,0.5,0,dt);

			 if(c2c.check)
			  cnt_task[0]++;

			  if(cnt_task[0]>5){//Deliver cargo
				  aux_open(2,1);
				  flag=1;
				}
	       break;
	case 3:return_home(10,2,EN_LAND,NEN_HEAD_WAY,dt);//Autonomous return
	       break;
	default:break;
	}

	if(flag)
		mission_state++;

	mission_time+=dt;
	if(mission_time>7*60&&(mission_state>100||mission_state==2))//Timeout return
		mission_state=3;

	if(mission_finish)
	  return 1;
  else
    return 0;
}

8 Donations and Future Development Plans

____If you find this project helpful and would like to support its continued development, including software and hardware updates, you may make a donation via WeChat!

Files by @HoneyGrant, at commit 6a6fb32, read from GitHub in your browser. Hardware license: GPL-3.0-only; software license: GPL-3.0-only. Robotheca doesn't review code: read it before running it.