MAVROS Example — Flight Task Control
Overview
The flight_task_control.py script demonstrates how to perform basic UAV flight operations. It serves as an introductory example for users who are just starting with MAVROS and want to understand how to communicate with copters, planes, or VTOLs through MAVROS services. This example covers the most fundamental flight control commands — including arming, mode switching, takeoff, landing, and setting home position.
Services Used
1. /mavros/cmd/arming — Arm or Disarm the UAV
- Service Type:
mavros_msgs/srv/CommandBool- Purpose:
- Enables or disables the motors of the UAV.
- Usage in Script:
- This service is called to arm the drone before takeoff and to disarm it after landing.
- Request Fields:
-
value (bool): True → Arm the vehicle (enable motors) False → Disarm the vehicle (disable motors) - Example Call:
self.arm_vehicle(True)- Behavior:
-
- The autopilot performs safety checks (e.g., GPS lock, pre-arm conditions).
- If successful, the drone’s motors are powered, and the UAV becomes ready to take off.
2. /mavros/set_mode — Change Flight Mode
- Service Type:
mavros_msgs/srv/SetMode- Purpose:
- Switches the vehicle’s current flight mode (e.g., from
STABILIZEtoGUIDED,LAND, etc.). - Usage in Script:
self.set_mode("GUIDED")
3. /mavros/cmd/takeoff — Command Autonomous Takeoff
- Service Type:
mavros_msgs/srv/CommandTOL- Purpose:
- Commands the UAV to autonomously take off to a specified altitude.
- Usage in Script:
self.takeoff(altitude=5.0)
4. /mavros/cmd/land — Command Autonomous Landing
- Service Type:
mavros_msgs/srv/CommandTOL- Purpose:
- Commands the UAV to perform an autonomous landing sequence.
- Usage in Script:
self.land()
5. /mavros/cmd/set_home — Set Home Position
- Service Type:
mavros_msgs/srv/CommandHome- Purpose:
- Sets or updates the vehicle’s home position, used for Return-to-Launch (RTL) operations.
- Usage in Script:
self.set_home(use_current_gps=True)
Execution Flow
- Waits for MAVROS services to become available.
- Sets the home position using
/mavros/cmd/set_home. - Switches flight mode to
GUIDED. - Arms the vehicle.
- Takes off to the desired altitude.
- Hovers briefly.
- Initiates landing.
- Disarms automatically after landing.
How to Run
- Step 1: Build the Package
-
cd ~/ros2_ws colcon build --packages-select mavros_examples source install/setup.bash - Step 2: Launch MAVROS with SITL (ArduPilot Example)
-
ros2 launch mavros apm.launch.py fcu_url:=udp://:14540@ - Step 3: Run the Example Node
-
ros2 run mavros_examples flight_task_control.py