Aerial Robotics and ROS 2
local graph
Chapter 11 — Aerial Robotics and ROS 2
Section titled “Chapter 11 — Aerial Robotics and ROS 2”So far in this book, we have explored various methods for interacting with and controlling mobile ground robots and manipulators. However, another important class of mobile robots has emerged over the past few decades: aerial robots. These are often referred to by different names, such as drones, multicopters, or, more commonly, Unmanned Aerial Vehicles (UAVs). Like ground-based robots, UAVs can perform service tasks, such as area exploration or inventory management. Because they can fly, UAVs are often faster and more reliable for certain tasks. However, their autonomy introduces additional challenges.
In this chapter, we will first examine the basic structure and equipment of aerial robots. Then, we will demonstrate how to simulate a UAV using Gazebo, integrated with ROS 2, along with the most used control stack for managing these advanced robotic systems: the PX4 control stack.
We will cover the following main topics in the chapter:
- Introducing aerial robotics
- Understanding the hardware and software architecture of unmanned aerial vehicles
- Simulating an aerial robot using Gazebo and the PX4 control stack
- Controlling a UAV using ROS 2
Technical requirements
Section titled “Technical requirements”To follow this chapter, you should have one of the following setups on your computer:
- A standard computer running the Ubuntu 24.04 LTS operating system
- A Linux machine with the ROS 2 Jazzy version installed or with a running Docker container configured as discussed in Chapter 2.
The reference code for this chapter can be found in the Chapter011 folder of the following code repository: https://github.com/PacktPublishing/Mastering-ROS-2-for-Robotics-Programming/tree/main/Chapter11.
Introducing aerial robotics
Section titled “Introducing aerial robotics”Aerial robotics has been an emerging research field for over two decades, gaining significant momentum since the early 2000s. Today, despite many ongoing challenges, numerous tech companies develop and deploy UAVs to perform a variety of service robotics tasks, such as delivery, agricultural operations, and other specialized applications.
Leading companies in aerial robotics and their objectives
Section titled “Leading companies in aerial robotics and their objectives”To provide an overview of the activities these companies are involved in, the following section includes a list of key companies and their primary objectives in the field of aerial robotics:
- DJI: DJI [1] is the global leader in civilian drones and aerial imaging technology. They offer a wide range of drones for photography, agriculture, inspection, and more.
- Autel Robotics: Autel Robotics [2] provides advanced drones for aerial photography, inspection, and public safety applications. They are known for their high-quality cameras and robust flight performance.
- Zipline: Zipline [3] specializes in using drones for medical supply deliveries, particularly in remote or hard-to-reach areas, enhancing healthcare logistics.
- Delair: Delair [4] offers professional-grade drones and data processing solutions for applications like agriculture, mining, construction, and environmental monitoring.
- Flyability: Flyability [5] is a pioneer in designing drones for industrial inspections, particularly in areas that are hard to reach, dangerous, or confined, such as inside industrial plants, power generation facilities, and mines. Their drones are designed to be collision-tolerant, allowing them to operate in complex indoor environments without the risk of damage.
Of course, the above mentioned are only a small portion of the hi-tech companies currently working with aerial robots. Before discussing how to program such systems, let’s briefly compare them to the ground robotics problem.
Comparison of ground and aerial systems
Section titled “Comparison of ground and aerial systems”Although both aerial and ground robots face challenges such as navigating unstructured environments, avoiding obstacles, and planning paths, UAVs encounter significantly greater difficulties in achieving autonomy. This is mainly due to the complexities of operating in three-dimensional space, as well as the overall complexity of their flight systems. Let’s see a brief comparison of ground and aerial systems:
- UAVs must constantly adjust to maintain stable flight in the air. Unlike ground robots that move on a stable surface, UAVs need to control their altitude, pitch, roll, and yaw in real time (the Eulerian angles defining the attitude of a UAV). These movements must be continuously adjusted based on sensor feedback and environmental conditions, requiring advanced algorithms for flight dynamics control. Small errors in control can lead to instability or crashes, making autonomy particularly challenging.
- While ground robots navigate primarily in two dimensions, UAVs operate in a 3D environment. This adds complexity to navigation and path planning since they must consider obstacles not only around them but also above and below. Autonomous UAVs must integrate multiple sensors (e.g., GPS, LiDAR, cameras) to accurately perceive their environment and plan collision-free trajectories. Path planning in 3D space is computationally intensive, and real-time adjustments are often necessary to avoid dynamic obstacles like birds or other UAVs.
- From a low-level control view perspective, UAVs are highly sensitive to external environmental factors like wind, rain, and air pressure. Autonomous flight systems must constantly compensate for these factors. For example, wind gusts can destabilize a UAV, requiring rapid corrections to maintain course and altitude. The UAV’s control system must adapt autonomously to changes in weather conditions without human intervention, which adds complexity to its autonomy software.
- Achieving reliable autonomy in UAVs requires the integration of multiple sensors. Aerial robots rely on a combination of GPS, IMUs (short for inertial measurement units), barometers, and visual sensors to estimate their position and orientation. However, GPS signals can be lost or degraded in urban areas or indoors, and visual sensors can be affected by poor lighting or dust. UAVs must use sensor fusion algorithms to combine data from multiple sensors to maintain accurate situational awareness. This requires complex software to manage sensor data, detect failures, and switch to backup systems in case of sensor malfunctions.
- UAVs need to make decisions in real time, often in rapidly changing environments. For example, if an obstacle appears suddenly or weather conditions worsen, the UAV’s onboard system must quickly decide how to react—whether to adjust its flight path, hover, or return to its base. These decisions must be made autonomously without relying on constant human input. Designing algorithms that can handle such real-time decision-making is a significant challenge, especially when balancing multiple objectives like safety, efficiency, and power consumption.
- In dynamic environments, UAVs must be able to detect and avoid obstacles autonomously. This includes both stationary objects (like buildings or trees) and moving obstacles (like other drones or vehicles). Advanced UAVs use technologies such as LiDAR, optical cameras, and ultrasonic sensors to map their surroundings and detect obstacles. The complexity lies in processing this data in real time, interpreting it, and making split-second decisions on how to navigate around hazards. In confined spaces or environments with complex structures, this becomes particularly challenging, as the margin for error is smaller.
Due to the complexity involved in managing an aerial system, it is essential to use a control stack to ensure stable and secure flight. One of the most widely used control stacks in both hobbyist and industrial applications is the PX4 control stack. It offers a comprehensive set of algorithms for flight control, such as attitude, position, and velocity control, along with features for navigation, mission planning, and sensor integration. The PX4 stack communicates directly with ROS 2 and can be used to simulate a multi-copter realistically, which we will explore later in this chapter. However, before introducing the PX4 stack and interfacing a simulated UAV, in the next section, we will first briefly discuss the components of a UAV.
Understanding the hardware and software architecture of a UAV
Section titled “Understanding the hardware and software architecture of a UAV”Aerial robots are composed of different sensors and different shapes. Moreover, the main component of these devices is the autopilot, the central component of a UAV, responsible for initializing and interfacing with onboard sensors. The autopilot, also known as the Flight Control Unit (FCU) is a micro-controller board that processes input to control the UAV’s actuators, such as its brushless motors. UAVs can have different platform configurations, with the quadrotor being the simplest. Quadrotors typically have four motors arranged in either an (x) or (+) pattern. In coaxial configurations, two motors and propellers are mounted on each axis, resulting in eight in total. This setup is similar for hexacopters and octocopters. Regardless of the airframe design, control strategies remain the same, as the autopilot translates control signals directly into motor actions.
Another key component of the UAV hardware is the onboard computer. While the FCU manages the basic flight operations of the UAV, the onboard computer handles more complex tasks that require high-level computation, such as those involving ROS 2 or other advanced programming frameworks. The onboard computer and the FCU are connected via a wired interface, which ensures safer and more reliable communication with better performance compared to wireless connections. The relationship among the two computation units is schematized in Figure 11.1.

Figure 11.1: UAV hardware/software architecture
Figure 11.1: UAV hardware/software architecture
Here, the UAV is directly connected with the FCU. Additional hardware and software elements associated with UAVs are:
- IMU: The key hardware in the autopilot system is the inertial measurement units (IMU), which helps determine the UAV’s attitude, altitude, and flight direction. Actually, an IMU does not directly measure motion, orientation, or forces—instead, it measures linear accelerations and angular velocities. These measurements are integrated over time to estimate the vehicle’s motion and orientation and can be used, together with dynamic models, to infer external forces acting on the UAV. The IMU typically consists of an accelerometer, a gyroscope, and often a magnetometer.
- GPS receiver: Another essential sensor for UAVs is the Global Positioning System (GPS), which helps estimate the robot’s global position in terms of latitude, longitude, and altitude, allowing it to stabilize its location. However, GPS receivers can provide positioning accuracy in the range of 1 to 3 meters. When using Real-Time Kinematic (RTK) correction with a base station, this accuracy can be improved to within several centimeters. However, it’s important to note that performance can be significantly degraded in cluttered environments, such as urban canyons or areas with dense foliage, where signal reflections and obstructions can introduce substantial errors.
- I/O: The FCU handles communication with external software. Not only the onboard computer but also the remote controller and the Ground Control Station (GCS).
- Low-level control: The FCU is responsible for the low-level control of the UAV, which includes all the tasks necessary to ensure stable and safe flights. The FCU achieves this by using data from sensors or the onboard computer to make real-time adjustments and maintain flight stability.
As for the onboard calculation unit, it is represented by a small and light computer that runs a Linux operating system. The hardware and software modules used on this laptop are:
- LIDARs/camera/optical flow sensor: All the sensors that can provide visual or lidar odometry. Using these sensors, the UAV can overcome its main limitation: lack of stability in indoor environments. In addition, the LIDAR sensor can be used to map the area surrounding the robot and avoid obstacles.
- Sensor fusion: Different sensors can be integrated to estimate the current position of the UAV. In this context, SLAM algorithms can be implemented using depth sensors, lidar sensors, IMUs, and similar. This approach allows the UAV to properly navigate environments in which the GPS signal is not working or is weak.
- Planners: Using the information of the autopilot and the sensor connected with the onboard computer, a set of planner modules implement the robot autonomy. For example, a 3D obstacle-free path can be generated to drive the motion of the robot in a narrow space.
Another key component of UAV architectures is the GCS software. This is usually a program installed on a ground-based computer that communicates wirelessly with the FCU. The GCS enables developers to monitor and track the UAV’s status. In some cases, it also allows them to directly control basic operations, such as takeoff, landing, or navigating to a specific point.
In this chapter, we will cover some of these modules. When it comes to autopilots, we will introduce the Pixhawk, one of the most widely used autopilots for both hobbyist and professional applications, as discussed in the next section.
Pixhawk autopilot and PX4 control stack
Section titled “Pixhawk autopilot and PX4 control stack”The Pixhawk autopilot is an open-source hardware platform widely used in both hobbyist and professional UAV applications. It serves as the brain of the UAV, providing the hardware needed to support flight control stacks. Basically, the Pixhawk integrates an IMU sensor and all the communication ports to directly integrate GPS and other similar sensors used to fly. One of the reasons for its popularity is its compatibility with various flight control software systems, such as ArduPilot [6] or PX4 [7], which offer advanced flight modes, autonomous navigation, and customizable options.
This flexibility makes Pixhawk ideal for a wide range of applications, from recreational drones to industrial and research purposes. Additionally, Pixhawk’s modular design supports various accessories like GPS, cameras, and communication modules, enhancing the drone’s capabilities. The Pixhawk project was started by Lorenz Meier in 2008 as part of his work at ETH Zurich, a leading Swiss university. Pixhawk has since grown into a widely used platform in the UAV industry, and the project is now managed by the Dronecode Foundation, a non-profit organization that promotes open-source software and hardware for drone development. The fact that Pixhawk is open-source means that both the hardware designs and the flight control software are publicly available for anyone to use, modify, or improve. This transparency allows developers, hobbyists, and companies to customize and enhance the system to fit their specific needs.
Different versions of the autopilot are now available on the market, for example, in Figure 11.2, the Cube version of Pixhawk is shown, an advanced version of the Pixhawk autopilot, known for its modularity and enhanced performance. Also referred to as the Cube Autopilot, it features a cube-shaped design that houses high-end sensors, processors, and connectors, making it more robust and versatile compared to earlier versions of Pixhawk.

Figure 11.2: Pixhawk autopilot (Cube model)
Figure 11.2: Pixhawk autopilot (Cube model)
The Cube’s modular design allows it to be easily integrated into different UAV platforms. It connects to a carrier board that expands its functionality by adding ports for GPS, telemetry, power modules, and more. One of its key advantages is its built-in redundancy, with multiple sensors (such as accelerometers, gyroscopes, and magnetometers) to ensure flight stability and safety. This redundancy allows the autopilot to continue functioning even if one sensor fails.
In this chapter, we focus on the PX4 control stack. PX4 is composed of two primary layers:
- Flight stack: This layer implements the flight control system.
- Middleware: This general-purpose layer supports any type of autonomous robot by managing internal and external communications, as well as hardware integration.
The PX4 control stack is versatile, supporting various airframes that all share the same underlying code. The flight stack itself includes guidance, navigation, and control algorithms designed for autonomous vehicles. It features controllers for different types of airframes, such as fixed-wing, multirotor, and Vertical Takeoff and Landing (VTOL) aircraft, and also includes estimators for both attitude and position. Even if a physical aerial platform and autopilot are unavailable, it’s possible to modify, compile, and run the autopilot’s code by connecting it to the Gazebo simulator. In the upcoming section, we will install the PX4 flight stack and explore how to simulate and program autopilot code on a laptop.
The source code of the control stack can be modified to suit specific needs. For most standard applications, the default version of the PX4 control stack is already sufficient. However, understanding its architecture is important for gaining insight into how PX4 integrates with ROS 2. The architecture is shown in Figure 11.3.

Figure 11.3: PX4 software architecture
Figure 11.3: PX4 software architecture
The controller’s source code is divided into independent modules, with each module representing a specific building block (as shown in Figure 11.3). These modules can be found within the firmware’s main directory under the source folder. Like ROS 2, PX4 modules communicate using a publish/subscribe message bus called uORB. This publish/subscribe system offers the following advantages:
- Reactivity: The system operates asynchronously, instantly updating whenever new data is available, with all operations and communication happening in parallel.
- Thread-safe data access: System components can safely consume data from any source without threading issues.
The flight stack is made up of guidance, navigation, and control algorithms designed for autonomous drones. It includes controllers for various UAV airframes, including fixed-wing and multirotor configurations, as well as attitude and position estimators. The main modules of the PX4 architecture are:
- Estimator: This module processes inputs from one or more sensors, combining them to compute the vehicle’s state, such as calculating its attitude from IMU data.
- Controller: A controller receives a setpoint and an estimated state (the process variable) and adjusts the process variable to match the setpoint. For example, the position controller takes desired position setpoints as input, uses the current estimated position as the process variable, and outputs attitude and thrust setpoints to guide the vehicle toward the desired location.
- Mixer: The mixer translates motion commands (such as turning right) into specific motor commands while ensuring system constraints are respected. These translations depend on factors like motor arrangement relative to the vehicle’s center of gravity and rotational inertia.
The use of uORB messages has proven effective for integrating with ROS 2. Unlike earlier versions of ROS, where a custom serial communication layer was needed to translate uORB messages into ROS messages, ROS 2 allows direct connection between uORB messages and ROS topics. This direct connection improves communication speed and enhances overall system performance. In addition, PX4 supports different control modes that define the way in which the UAV is operated. The most important ones are:
- Stabilized mode: The autopilot stabilizes the aircraft’s attitude (pitch, roll, and yaw) while the pilot controls the throttle and direction.
- Position mode: Both position and altitude are maintained by the autopilot. The pilot controls the direction and speed.
- Offboard mode: External commands are sent to the UAV from a companion computer, enabling real-time control through custom algorithms or scripts.
We will learn how to properly change the control mode to have the requested level of autonomy before discussing the communication between ROS 2 and aerial robots using the PX4 Software-In-The-Loop (SITL)
Simulating an aerial robot using Gazebo and the PX4 control stack
Section titled “Simulating an aerial robot using Gazebo and the PX4 control stack”Operating UAVs comes with challenges, including instability during flight and the risk of crashes. To mitigate these risks, control algorithms should be tested in reliable simulators before implementation on real hardware. Simulators help developers identify and address issues without risking damage or incurring high operational costs. They also allow for the simulation of various environments and scenarios that may be hard to replicate in real life, ensuring better performance when transitioning to actual UAVs.
A key feature of the PX4 control stack is its ability to operate in Software-In-The-Loop (SITL) mode. In this mode, the PX4 flight control software runs on a computer rather than a physical drone, simulating all aspects of flight control, sensor inputs, and external conditions. This allows developers to test and validate algorithms without needing actual hardware, which is essential for identifying bugs, optimizing performance, and experimenting with control strategies in a safe environment. However, SITL has some limitations: it simplifies aerodynamic effects, uses idealized sensor and actuator models, and lacks real-world disturbances like wind, GPS signal variability, or hardware faults. Therefore, while SITL is invaluable for development, real-world testing remains necessary for full validation.
To compile and run the PX4 autopilot code, we must first clone the repository and install the needed dependencies, as discussed in the following:
- To start the PX4 stack in SITL mode, you first need to download and compile the PX4 firmware. The cloning process may take some time as it downloads additional sub-repositories:
$ git clone https://github.com/PX4/PX4-Autopilot.git --recursive
This repository contains the control firmware’s source code, compilation files, and models for simulating drones in Gazebo. It also includes a script to install the dependencies required for simulation with various simulators.
- Next, prepare your environment by running the following command, which installs the necessary dependencies and configures the environment:
$ bash ./PX4-Autopilot/Tools/setup/ubuntu.sh
- After the script finishes, reload your environment by opening a new terminal or restarting Docker. Then, compile the PX4 software in SITL mode:
$ cd PX4-Autopilot/$ make px4_sitl
- Once compiled, you can start Gazebo with a simulated UAV using the command:
$ make px4_sitl gz_x500
This command launches a simulation of a drone model called x500, as shown in Figure 11.4.

Figure 11.4: UAV simulated in Gazebo using the PX4 SITL
Figure 11.4: UAV simulated in Gazebo using the PX4 SITL
Although we can’t directly interact with the UAV without a specific application, the code in the PX4 control stack is currently running and is prepared to handle all requests from external programs. Let’s start interacting with the simulated UAV by using a common Ground Control Station program: QGroundControl.
QGroundControl is open-source ground control station software designed for operating and managing UAVs. It supports the PX4 control stack and provides various tools for drone control, mission planning, and real-time monitoring. Before using QGroundControl, it needs to be installed. The easiest way to install it on Ubuntu is by using the .AppImage file, which includes all necessary dependencies. This method simplifies the installation process by eliminating the need for additional packages or complicated setups. To install QGroundControl, download the AppImage file from the official download page at the following link: https://docs.qgroundcontrol.com/master/en/qgc-user-guide/getting_started/download_and_install.html.
Once downloaded, open a terminal and navigate to the directory containing the .AppImage file (assuming it’s in the Downloads folder), and execute the following commands:
$ cd ~/Downloads$ chmod +x QGroundControl.AppImage$ ./QGroundControl.AppImageThis allows you to run QGroundControl without fully installing it on your system. After launching the application, the main page of the control station will appear. Whether you are using a real drone or a simulated one via Gazebo, the user interface remains consistent, as shown in Figure 11.5.

Figure 11.5: Main QGroundControl window
Figure 11.5: Main QGroundControl window
In Figure 11.5, the main elements of the GCS are contained. At the top of the window is the Fly toolbar. Next to the Q icon, there is a text indicator that shows whether the UAV is properly configured and ready to fly. This indicator uses color codes: green for ready, yellow for warnings, and red for issues that prevent flight. In the Fly toolbar, you can also view the current flight mode and change it by clicking on the mode indicator. Additionally, the panel displays the UAV’s current attitude, with a horizontal plane for monitoring roll and pitch, and a compass for yaw orientation. Finally, In the left part of the window, a horizontal panel containing some buttons is contained. Using these buttons, we can request some flight tasks, like requesting takeoff/landing or activating a new flight plan.
Try to use QGroundControl to drive the actions of the simulated UAV. It will act exactly like it will in the real system. However, we are not interested in using the GCS to drive the robot, but we want to use ROS 2 nodes. For this reason, let’s discuss in the next section how to interface ROS 2 and PX4.
Interfacing ROS 2 and PX4
Section titled “Interfacing ROS 2 and PX4”To properly interface ROS 2 and PX4, we must access the internal uORB topics of the UAV controller. In this way, we can read the information generated from autopilot, sending control input or additional information in a transparent way. To implement this, PX4 uses the uXRCE-DDS middleware. The communication process is shown in the pipeline depicted in Figure 11.6. Put simply, the uXRCE-DDS middleware consists of a client operating on PX4 and an agent running on the companion computer, facilitating bi-directional data exchange via a serial or UDP connection. The agent serves as a proxy for the client, allowing it to publish and subscribe to topics within the global DDS data space.

Figure 11.6: ROS 2-PX4 integration
Figure 11.6: ROS 2-PX4 integration
After connecting the client, the uORB messages are streamed toward ROS 2 using the px4_msgs package. Let’s install both messages and the uXRCE-DDS library to enable the message exchange between the autopilot code and ROS 2:
- Install the PX4 messages by cloning and compiling the following package:
$ git clone https://github.com/PX4/px4_msgs.git
- Compile and install the Micro XRCE-DDS Agent. You can do it by using the following commands to install it; the installation can be done in any system directory, as it is independent of the ROS 2 workspace:
git clone https://github.com/eProsima/Micro-XRCE-DDS-Agent.gitcd Micro-XRCE-DDS-Agentmkdir build && cd build && cmake ..makesudo make installsudo ldconfig /usr/local/lib/
We can now use the commands listed in the next two steps to start the Gazebo simulation and the ROS 2 communication bridge.
- Start Gazebo using the following command:
make px4_sitl gz_x500
- Start the communication bridge:
MicroXRCEAgent udp4 -p 8888
In this case, the bridge communicates with the PX4 modules using the UDP protocol instantized on port 8888.
You can check that the ROS 2 system correctly communicates with PX4 by checking the active topics. By default, the namespace associated with the topics is fmu (Flight Management Unit). We can distinguish two types of topics, the input for the FCU (/fmu/in/*) and the output of the FCU (/fmu/out/*). Among the different topics, the most interesting ones are:
/fmu/in/offboard_control_mode: To trigger the offboard control mode. If you don’t publish on this topic, the PX4 will not allow you to switch on the offboard control mode to start autonomous navigation./fmu/in/vehicle_command: To request the navigation towards a new setpoint./fmu/out/vehicle_local_position:To read the local position reconstructed from the Px4 based on information like GPS or external position source.
Additionally, the ROS 2-PX4 interface also instantiates a service to request specific commands from the UAV. This service is called /fmu/vehicle_command and as an example, it is used to change to UAV control mode.
We will use the topics and the service in the next example of this chapter, where we will control the UAV to perform specific trajectories and basic arm, disarm, and take-off operations.
Controlling a UAV using ROS 2
Section titled “Controlling a UAV using ROS 2”We are now ready to implement our first ROS 2 application to control a simulated UAV. As previously mentioned, the interface between Gazebo and ROS 2 mimics that of a real autopilot. This means the program presented in this chapter will work the same way with a real robot. The goal of this example is to demonstrate how to perform basic UAV operations. Specifically, we will implement the following functions:
- Arm: Start the propellers spinning.
- Disarm: Stop the propellers from spinning.
- Take off: Lift the UAV to an altitude of 5 meters at its current position.
Additionally, during these operations, the ROS 2 system will monitor the UAV’s local position in Cartesian space. After takeoff, the user will be able to specify a target position for the UAV to reach. The UAV will then plan and execute a time-sampled trajectory from its current position to the specified goal. To achieve this, we need to select the OFFBOARD control mode. PX4 includes a safety mechanism to prevent accidentally switching to this mode.
Engaging the OFFBOARD mode
Section titled “Engaging the OFFBOARD mode”To engage OFFBOARD mode, we must continuously send a trigger message requesting the desired control mode, as shown in the example below:
- Start creating a ROS 2 package containing our ROS 2 node. As dependencies, we will specify the
px4_msgsto use the data generated by theuXRCE-DDSlayer:$ ros2 pkg create px4_ctrl --dependencies rclcpp std_msgs geometry_msgs px4_msgs - To implement the ROS 2 node, we will define a header file, the
px4_ctrl.hfile, where we include the headers and define the class of the node. As for the headers, let’s include the interface types to communicate with the autopilot.#include <rclcpp/rclcpp.hpp>#include <px4_msgs/msg/offboard_control_mode.hpp>#include <px4_msgs/msg/trajectory_setpoint.hpp>#include <px4_msgs/msg/vehicle_control_mode.hpp>#include <px4_msgs/msg/vehicle_local_position.hpp>#include <px4_msgs/srv/vehicle_command.hpp> - In the class constructor, link the input and output of the node. First, set up the service for changing the control mode, which uses the
px4_msgs::srv::VehicleCommandtype. Additionally, we need to publish a trigger to enable offboard control mode. After that, we will publish the desired setpoint that the UAV should reach (we will explain how to properly format these messages later in the example):class Px4Control : public rclcpp::Node {public:Px4Control() : Node("px4_ctrl") {cmd_client_ = create_client<px4_msgs::srv::VehicleCommand>("/fmu/vehicle_command");traj_cmd_pub_ = create_publisher<px4_msgs::msg::TrajectorySetpoint>("/fmu/in/trajectory_setpoint", 10);offboard_ctrl_mode_publisher_ = create_publisher<px4_msgs::msg::OffboardControlMode>("fmu/in/offboard_control_mode", 10); - Alternatively, to receive the estimated position of the UAV in a local frame in Cartesian space, to correctly receive the topic, we have to set the quality of service, as shown below:
rclcpp::QoS qos_profile(rclcpp::QoSInitialization::from_rmw(rmw_qos_profile_default));qos_profile.reliability(RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT);qos_profile.durability(RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL);qos_profile.liveliness(RMW_QOS_POLICY_LIVELINESS_AUTOMATIC);qos_profile.history(RMW_QOS_POLICY_HISTORY_KEEP_LASTqos_profile.keep_last(10);uav_pose_sub_ = this->create_subscription<px4_msgs::msg::VehicleLocalPosition>("/fmu/out/vehicle_local_position", qos_profile, std::bind(&Px4Control::uav_pose_cb, this, std::placeholders::_1));
- Before completing the constructor, we wait for the service to come online. Without this service, we cannot ask the PX4 to switch on the offboard control mode:
while (!cmd_client_->wait_for_service(1s)) {if (!rclcpp::ok()) {RCLCPP_ERROR(this->get_logger(), "Interrupted while waiting for the service. Exiting.");return;}RCLCPP_INFO(this->get_logger(), "service not available, waiting again...");}action_done_.store(false);
As you can see from the last line of the header file, the action_done_ variable has the shape of boolean data; however, its value is set with the store function. This is an atomic variable that can be used to safely update a shared flag between multiple threads. Atomic variables, like std::atomic<bool>, ensure thread-safe read/write operations without needing a mutex. In this case, action_done_ acts as a flag to indicate whether an action has been completed or not. Since multiple threads may read or modify this flag (e.g., one thread sets it to true when an action is done, while another checks its value), using an atomic variable ensures that no data races or inconsistent reads occur.
In the rest of the class definition, we just define the methods implemented in the .cpp file and some class variables. Let’s discuss the content of the source file next.
Exploring the px4_ctrl.cpp file
Section titled “Exploring the px4_ctrl.cpp file”Here’s a breakdown of the px4_ctrl.cpp file:
- The first function to discuss is
send_cmd. This is used to fill the fields of the service:void Px4Control::send_cmd(uint16_t command, float param1, float param2) {auto request = std::make_shared<px4_msgs::srv::VehicleCommand::Request>();VehicleCommand cmd{};- Based on two parameters, we can select the desired command, namely, arm or disarm, or change the control mode:
cmd.param1 = param1;cmd.param2 = param2;cmd.command = command;cmd.target_system = 1;cmd.target_component = 1;cmd.source_system = 1;cmd.source_component = 1;cmd.from_external = true;cmd.timestamp = this->get_clock()->now().nanoseconds() / 1000;request->request = cmd;
- Based on two parameters, we can select the desired command, namely, arm or disarm, or change the control mode:
- When we call the client, we also provide a callback function, which is triggered when the service response is ready:
auto result = _cmd_client->async_send_request(request, std::bind(&Px4Control::srv_callback, this, std::placeholders::_1));
- The service callback function is used to wait for the service to return with a value. When it returns, we can consider the requested command executed:
void Px4Control::srv_callback(rclcpp::Client<px4_msgs::srv::VehicleCommand>::SharedFuture future) {auto status = future.wait_for(1s);if (status == std::future_status::ready) {auto reply = future.get()->reply;uint8_t service_result_ = reply.result;action_done_.store(true);}else {RCLCPP_INFO(this->get_logger(), "Service In-Progress...");}}
- The
send_cmdfunction is used in thearmanddisarmfunctions. In the first case, the first parameter is1and the second is0. In the disarm case, both parameters are0:void Px4Control::arm() {send_cmd(VehicleCommand::VEHICLE_CMD_COMPONENT_ARM_DISARM, VehicleCommand::ARMING_ACTION_ARM, 0.0); }void Px4Control::disarm() {send_cmd(VehicleCommand::VEHICLE_CMD_COMPONENT_ARM_DISARM, 0.0, 0.0);} - In the local pose callback, we collect and save the current coordinates of the UAV:
void Px4Control::uav_pose_cb(const px4_msgs::msg::VehicleLocalPosition::SharedPtr msg) {curr_x_ = msg->x;curr_y_ = msg->y;curr_z_ = msg->z;}
- To trigger the offboard control mode, we must publish the
OffboardControlModedata, specifying the kinds of input data. For example, in this case, we specify that we want to enable the offboard control mode, controlling the desired position. To avoid interruptions, we start this as a thread that runs at 1 Hz:void Px4Control::publish_offboard_ctrl_mode() {rclcpp::Rate loop_rate(1);while( rclcpp::ok() ) {OffboardControlMode data{};data.position = true;data.velocity = false;data.acceleration = false;data.attitude = false;data.body_rate = false;offboard_ctrl_mode_publisher_->publish(data);loop_rate.sleep();}} - To allow the user to request a given action, we implement a basic command-line menu. Here, the user can write the desired action:
arm,disarm,takeoff, ormove:void Px4Control::menu() { - Before asking the user for the desired action, we start the offboard trigger publisher thread:
boost::thread publish_offboard_ctrl_mode_t( &Px4Control::publish_offboard_ctrl_mode, this );string cmd = "";
- The action request terminates when the user inserts the exit word:
while (rclcpp::ok() && cmd != "exit") {action_done_.store(false);RCLCPP_INFO(this->get_logger(), "Insert the desired command");RCLCPP_INFO(this->get_logger(), "arm - to arm the drone");RCLCPP_INFO(this->get_logger(), "disarm - to disarm the drone");RCLCPP_INFO(this->get_logger(), "takeoff - to take the drone");RCLCPP_INFO(this->get_logger(), "move - specify a target point to reach");RCLCPP_INFO(this->get_logger(), "exit - to exit");getline( cin, cmd );
- After receiving the request, we call the desired function:
if( cmd == "arm") {arm();while( !action_done_.load()) usleep(0.1*1e6);}else if ( cmd == "disarm" ) {disarm();while( !action_done_.load()) usleep(0.1*1e6);}
- For the
takeoffcommand, first, we request to switch on the offboard control mode (param2 = 6):else if ( cmd == "takeoff") {send_cmd(VehicleCommand::VEHICLE_CMD_DO_SET_MODE, 1, 6);sleep(1);px4_msgs::msg::TrajectorySetpoint msg{}; - Then, we will set the desired position to perform the takeoff. Such a point will be the current location in
xandy, and the desired displacement over thez-axis, to actually perform the takeoff. In this case, we request 5 meters:msg.position = {curr_x_, curr_y_, curr_z_-5.0};msg.yaw = 0.0;msg.timestamp = this->get_clock()->now().nanoseconds() / 1000 - Finally, we publish the desired setpoint. If the robot is armed, and it is in Offboard control mode, it will start to fly:
traj_cmd_pub_->publish(msg);}
- As for the
moveaction, we must ask the user for additional information: the destination point. We avoid considering the movements over the yaw angle. So, we just ask forx,y, andz:else if( cmd == "move") {float x, y, z;std::string input;RCLCPP_INFO(this->get_logger(), "Insert the destination point as x y z:");std::getline(std::cin, input); // Read entire linestd::istringstream stream(input);stream >> x >> y >> z; - Before sending the target position to the UAV, there is an important consideration. The PX4 stack uses a controller to minimize the position error, meaning when we request the UAV to reach a specific position, the PX4 controller moves the UAV to that point automatically. In the code, we use a Point3D structure to store both the current and desired positions. However, the UAV will attempt to reach the target as quickly as possible. If the target is far away, this could result in abrupt and visually unappealing movements, and it might even cause instability. To avoid this, we need to plan a smooth trajectory by generating intermediate waypoints between the starting position and the destination, ensuring smoother and more stable motion. This trajectory is saturated in velocity, requiring a maximum velocity of 0.5 m/s:
Point3D start = {curr_x_, curr_y_, curr_z_};Point3D end = {x, y, z};double v_max = 0.5;double time_step = 1.0/10.0;
- To plan the trajectory, we use the function
planTrajectory:std::vector<Point3D> trajectory = planTrajectory(start, end, v_max, time_step);px4_msgs::msg::TrajectorySetpoint msg{};rclcpp::Rate loop_rate(10); - After the trajectory is fully generated, we will stream it point by point with the same frequency as the sample time used in the trajectory calculation:
for (const auto& point : trajectory) {msg.position = {point.x, point.y, point.z};msg.yaw = 0.0;msg.timestamp = this->get_clock()->now().nanoseconds() / 1000;traj_cmd_pub_->publish(msg);loop_rate.sleep();}}}}
- To support the trajectory calculation, we define a data structure to store the
x,y, andzcoordinates. In addition, a function to calculate the distance between two points using the Euclidean distance formula is defined:struct Point3D {double x, y, z;};double calculateDistance(const Point3D& start, const Point3D& end) {return std::hypot(end.x - start.x, end.y - start.y, end.z - start.z);} - The linear interpolation method is used to generate a smooth trajectory between two points, with a maximum velocity and a given time step. This method ensures a straight-line path between the start and end points with a constant speed:
std::vector<Point3D> planTrajectory(const Point3D& start, const Point3D& end, double v_max, double time_step) {std::vector<Point3D> waypoints;double total_distance = calculateDistance(start, end);double total_time = total_distance / v_max;int num_steps = std::ceil(total_time / time_step);double v_x = (end.x - start.x) / (num_steps * time_step);double v_y = (end.y - start.y) / (num_steps * time_step);double v_z = (end.z - start.z) / (num_steps * time_step);;for (int i = 0; i <= num_steps; ++i) {double t = i * time_step;Point3D waypoint;waypoint.x = start.x + v_x * t;waypoint.y = start.y + v_y * t;waypoint.z = start.z + v_z * t;waypoints.push_back(waypoint);}return waypoints;}
- In the main function of the node, the defined ROS 2 class is instantized and the
runmethod is called. In therunmethod, we start the menu thread and request the node spin:void Px4Control::run() {std::thread menu_t( &Px4Control::menu, this);rclcpp::spin(shared_from_this());}int main(int argc, char *argv[]) {rclcpp::init(argc, argv);auto node = std::make_shared<Px4Control>();node->run();rclcpp::shutdown();return 0;}
We can now compile and start the node after launching the simulation, as discussed in the next section.
Working with the node
Section titled “Working with the node”To start the ROS 2 developed in the previous section to control the simulated UAV, you need to compile the workspace after modifying the CMakeLists.txt file as shown below:
add_executable(px4_ctrl src/px4_ctrl.cpp)ament_target_dependencies(px4_ctrl rclcpp px4_msgs Boost)install(TARGETS px4_ctrl DESTINATION lib/${PROJECT_NAME})Let’s try our node action. Start the simulation and the ROS 2 communication layer:
$ make px4_sitl gz_x500$ MicroXRCEAgent udp4 -p 8888Start the px4_ctrl node:
$ ros2 run px4_ctrl px4_ctrlNow, you can ask for the desired actions. An example of this interaction is depicted in Figure 11.7, where, after the takeoff, the position 3, 8, -10 is requested.

Figure 11.7: px4_ctrl node executed with the Gazebo simulation
Figure 11.7: px4_ctrl node executed with the Gazebo simulation
However, looking at the coordinates we are sending to the robot, you are probably asking yourself why the altitude is negative. Why –10 meters along the z -axis? The convention adopted by all PX4 systems is called NED or FLU. This means that the axis direction is the following: x -forward, y -left, z -up. Similarly, NED stands for North-East-Down. This frame is shown in Figure 11.8.

Figure 11.8: PX4 frame convention
Figure 11.8: PX4 frame convention
This means that you must operate a proper coordinate system transformation to integrate a PX4-based application with other ROS 2 modules.
This section provides a basic example of controlling UAVs. Although the example is conducted in a simulation environment, the PX4 control stack’s emulation closely mirrors the behavior of a real aerial system. Furthermore, you can explore all the topics published by Autopilot to gather additional information for integrating them into your ROS 2 nodes.
Summary
Section titled “Summary”In this chapter, we demonstrated how to simulate aerial robots and their hardware. Specifically, we used the Software-In-The-Loop (SITL) feature of the PX4 control stack, widely used control software for UAVs, to enable simulation in Gazebo. We also showed how to integrate aerial systems in Gazebo with ROS 2, where control inputs and other information from the autopilot are directly linked to the ROS 2 network. Additionally, we implemented a ROS 2 node to control the UAV’s position, illustrating how to program basic operations such as starting the propellers and taking off.
In the next chapter, we will explore programming another robotic platform—a mobile robot based on a microcontroller—using ROS 2.