PX4 User Guide
  • Introduction
  • Getting Started
    • Basic Concepts
    • Vehicles/Frames
    • Flight Controllers
    • Sensors
    • Radio Systems
    • Flight Modes
    • Vehicle Status Notifications
      • LED Meanings
      • Tune/Sound Meanings
      • Preflight Checks
    • Payloads & Cameras
    • Flight Reporting
  • Basic Assembly
    • Mounting the Flight Controller
    • Mounting the GPS/Compass
    • Vibration Isolation
    • Cable Wiring
    • CUAV Pixhawk V6X Wiring QuickStart
    • CUAV V5+ Wiring Quickstart
    • CUAV V5 nano Wiring Quickstart
    • Holybro Pixhawk 6C Wiring Quickstart
    • Holybro Pixhawk 6X Wiring Quickstart
    • Holybro Pixhawk 5X Wiring Quickstart
    • Holybro Pixhawk 4 Wiring Quickstart - Discontinued
    • Holybro Pixhawk 4 Mini Wiring Quickstart - Discontinued
    • Holybro Durandal Wiring Quickstart
    • Holybro Pix32 v5 Wiring Quickstart
    • Cube Wiring Quickstart
    • Pixracer Wiring Quickstart
    • mRo (3DR) Pixhawk Wiring Quickstart
  • Standard Configuration
    • Firmware
    • Airframe
    • Sensor Orientation
    • Compass
    • Gyroscope
    • Accelerometer
    • Airspeed
    • Level Horizon Calibration
    • Radio Setup
    • Joystick Setup
    • Flight Modes
    • Battery
    • Safety
      • Failsafe Simulation
    • ESC Calibration
    • Actuators
    • Autotune
  • Vehicle Types & Setup
    • Multicopters
      • Multicopter Config/Tuning
        • MC Filter/Control Latency Tuning
        • MC PID Tuning (Manual/Basic)
        • MC PID Tuning Guide (Manual/Advanced)
        • MC Setpoint Tuning (Trajectory Generator)
          • MC Jerk-limited Type Trajectory
        • Multicopter Racer Setup
      • X500 v2 (Pixhawk 6C)
      • X500 v2 (Pixhawk 5X)
      • X500 (Pixhawk 4)
      • S500 V2 (Pixhawk 4)
      • DJI F450 (CUAV v5+)
      • DJI F450 (CUAV v5 nano)
      • QAV250 (Pixhawk4 Mini) - Discontinued
      • DJI F450 + RTK (Pixhawk 3 Pro)
      • QAV250 (Pixhawk Mini)
      • QAV-R 5" Racer (Pixracer)
      • Omnicopter
    • Planes
      • Fixed Wing Config/Tuning
        • Fixedwing PID Tuning Guide
        • Fixedwing Advanced Tuning Guide
        • Fixedwing Trimming Guide
      • Reptile Dragon 2 (ARK6X)
      • Turbo Timber Evolution (Pixhawk 4 Mini)
      • Wing Wing Z84 (Pixracer)
    • VTOL
      • VTOL Config/Tuning
        • QuadPlane Configuration
        • Back-transition Tuning
        • VTOL w/o Airspeed Sensor
        • VTOL Weather Vane
      • Standard VTOL
        • FunCub QuadPlane (Pixhawk)
        • Ranger QuadPlane (Pixhawk)
        • Falcon Vertigo QuadPlane (Dropix)
      • Tailsitter VTOL
        • Build: TBS Caipiroshka Tailsitter Build (Pixracer)
      • Tiltrotor VTOL
        • Build: Convergence Tiltrotor (Pixfalcon)
    • Airships (experimental)
    • Autogyros (experimental)
      • ThunderFly Auto-G2 (Holybro pix32)
    • Balloons (experimental)
    • Helicopter (experimental)
      • Helicopter Config/Tuning
    • Rovers (experimental)
      • Traxxas Stampede
    • Submarines (experimental)
      • BlueROV2
    • Airframes Reference
  • Flying
    • First Flight Guidelines
    • Flying 101
    • Missions
      • Package Delivery Mission
    • GeoFence
    • Safety Point Planning
    • Flight Modes
      • Position Mode (MC)
      • Altitude Mode (MC)
      • Manual/Stabilized Mode (MC)
      • Acro Mode (MC)
      • Orbit Mode (MC)
      • Position Mode (FW)
      • Altitude Mode (FW)
      • Stabilized Mode (FW)
      • Acro Mode (FW)
      • Manual Mode (FW)
      • Takeoff Mode
      • Land Mode
      • Return Mode
      • Hold Mode
      • Mission Mode
      • Follow Me Mode
      • Offboard Mode
    • Terrain Following/Holding
  • Flight Log Analysis
    • Log Analysis using Flight Review
    • Log Analysis using PlotJuggler
  • Advanced Configuration
    • Finding/Updating Parameters
    • Full Parameter Reference
    • ECL/EKF Overview & Tuning
    • Flight Termination Configuration
    • Bootloader Flashing onto Betaflight Systems
    • Land Detector Configuration
    • Prearm/Arm/Disarm Configuration
    • IMU Factory Calibration
    • Sensor Thermal Compensation
    • Compass Power Compensation
    • Advanced Controller Orientation
    • Static Pressure Buildup
    • Serial Port Configuration
    • MAVLink Telemetry (OSD/GCS)
    • PX4 Ethernet Setup
    • Bootloader Update
  • Hardware (Drones&Parts)
    • Complete Vehicles
      • ModalAI Starling
      • PX4 Vision Kit
      • MindRacer BNF & RTF
        • MindRacer 210
        • NanoMind 110
      • Holybro Kopis 2
      • Bitcraze Crazyflie 2.1
    • Flight Controllers (Autopilots)
      • Pixhawk Series
        • Silicon Errata
      • Pixhawk Standard Autopilots
        • CUAV Pixhawk V6X (FMUv6X)
        • Holybro Pixhawk 6X (FMUv6X)
        • Holybro Pixhawk 6C (FMUv6C)
        • Holybro Pixhawk 6C Mini(FMUv6C)
        • Holybro Pix32 v6 (FMUv6C)
        • Holybro Pixhawk 5X (FMUv5X)
        • Holybro Pixhawk 4 (FMUv5) - Discontinued
        • Holybro Pixhawk 4 Mini (FMUv5) - Discontinued
        • Drotek Pixhawk 3 Pro (FMUv4pro)
        • mRo Pixracer (FMUv4)
        • Hex Cube Black (FMUv3)
        • mRo Pixhawk (FMUv3)
        • Holybro Pixhawk Mini (FMUv3) - Discontinued
      • Manufacturer-Supported Autopilots
        • AirMind MindPX
        • AirMind MindRacer
        • ARK Electronics ARKV6X
        • CUAV X7
        • CUAV Nora
        • CUAV V5+ (FMUv5)
        • CUAV V5 nano (FMUv5)
        • CUAV Pixhack v3 (FMUv3)
        • CubePilot Cube Orange+ (CubePilot)
        • CubePilot Cube Orange (CubePilot)
        • CubePilot Cube Yellow (CubePilot)
        • Holybro Kakute H7v2
        • Holybro Kakute H7mini
        • Holybro Kakute H7
        • Holybro Durandal
        • Holybro Pix32 v5
        • ModalAI Flight Core v1
        • ModalAI VOXL Flight
        • ModalAI VOXL 2
        • mRobotics-X2.1 (FMUv2)
        • mRo Control Zero F7)
        • NXP RDDRONE-FMUK66 FMU
        • Sky-Drones AIRLink
        • SPRacing SPRacingH7EXTREME
        • ThePeach FCC-K1
        • ThePeach FCC-R1
      • Experimental Autopilots
        • BeagleBone Blue
        • Raspberry Pi 2/3 Navio2
        • Raspberry Pi 2/3/4 PilotPi
          • PilotPi with Raspberry Pi OS
          • PilotPi with Ubuntu Server
      • Discontinued Autopilots/Vehicles
        • Drotek Dropix (FMUv2)
        • Omnibus F4 SD
        • BetaFPV Beta75X 2S Brushless Whoop
        • Bitcraze Crazyflie 2.0
        • Aerotenna OcPoC-Zynq Mini
        • CUAV v5
        • Holybro Kakute F7 (Discontinued)
        • Holybro Pixfalcon
        • Holybro pix32 (FMUv2)
        • mRo AUAV-X2
        • 3DR Pixhawk 1
        • Snapdragon Flight
        • Intel® Aero RTF Drone (Discontinued)
      • Pixhawk Autopilot Bus (PAB) & Carriers
        • ARK Electronics Pixhawk Autopilot Bus Carrier
    • Flight Controller Peripherals
      • ADSB/FLARM (Traffic Avoidance)
      • Air Traffic Avoidance: ADSB/FLARM
      • Air Traffic Avoidance: UTM
      • Airspeed Sensors
        • TFSlot Airspeed Sensor
      • Barometers
      • Camera
      • Distance Sensors (Rangefinders)
        • Lightware SFxx Lidar
        • Ainstein US-D1 Standard Radar Altimeter
        • LeddarOne Lidar
        • Benewake TFmini Lidar
        • Lidar-Lite
        • TeraRanger
        • Lanbao PSK-CM8JL65-CC5
        • Avionics Anonymous Laser Altimeter UAVCAN Interface
      • ESCs & Motors
        • PWM ESCs and Servos
        • DShot ESCs
        • OneShot ESCs and Servos
        • DroneCAN ESCs
          • Zubax Telega
          • PX4 Sapog ESC Firmware
            • Holybro Kotleta
            • Zubax Orel
        • VESC
      • TBS Crossfire (CRSF) Telemetry
      • FrSky Telemetry
      • Gimbal (Mount) Configuration
      • GPS/Compass
        • ARK GPS
        • Holybro DroneCAN M8N GPS
        • LOCOSYS Hawk A1 GNSS
        • Hex Here2
        • Holybro M8N & M9N GPS
        • Sky-Drones SmartAP GPS
      • Grippers
        • Servo Gripper
      • Optical Flow
        • ARK Flow
        • PMW3901
        • PX4FLOW (Deprecated)
      • Precision Landing
      • Parachute
      • Power Modules/PDB
        • CUAV HV pm
        • CUAV CAN PMU
        • Holybro PM02
        • Holybro PM07
        • Holybro PM06 V2
        • Holybro PM02D (digital)
        • Holybro PM03D (digital)
        • Pomegranate Systems Power Module
        • Sky-Drones SmartAP PDB
      • Satellite Coms (Iridium/RockBlock)
      • Telemetry Radios
        • SiK Radio
          • RFD900 (SiK) Telemetry Radio
          • HolyBro (SIK) Telemetry Radio
        • Telemetry Wifi
          • ESP8266 WiFi Module
          • ESP32 WiFi Module
          • 3DR Telemetry Wifi (Discontinued)
        • Microhard Serial Telemetry Radio
          • ARK Electron Microhard Serial Telemetry Radio
          • Holybro Microhard P900 Telemetry Radio
        • CUAV P8 Telemetry Radio
        • HolyBro XBP9X - Discontinued
      • RTK GPS
        • ARK RTK GPS
        • RTK GPS Heading with Dual u-blox F9P
        • CUAV C-RTK
        • CUAV C-RTK2 PPK/RTK GNSS
        • CUAV C-RTK 9Ps
        • Femtones MINI2 Receiver
        • Freefly RTK GPS
        • Holybro H-RTK-F9P
        • Holybro H-RTK-M8P
        • Holybro H-RTK Unicore UM982 GPS
        • Locosys Hawk R1
        • Locosys Hawk R2
        • Septentrio AsteRx-RIB
        • Septentrio mosaic-go
        • Trimble MB-Two
        • CubePilot Here+ (Discontined)
      • Remote ID
      • Smart Batteries
        • Rotoye Batmon Battery Smartification Kit
      • Tachometers (Revolution Counters)
        • ThunderFly TFRPM01 Tachometer Sensor
      • I2C Peripherals
        • I2C bus accelerators
        • TFI2CADT01 I2C address translator
      • CAN Peripherals
      • DroneCAN Peripherals
        • PX4 DroneCAN Firmware
        • ARK CANnode
    • Companion Computers
      • Pixhawk + Companion Setup
        • RasPi Pixhawk Companion
      • Companion Computer Peripherals
      • Holybro Pixhawk RPI CM4 Baseboard
      • Auterion Skynode
      • Computer Vision
        • Obstacle Avoidance
        • Safe Landing
        • Collision Prevention
        • Path Planning Interface
        • Motion Capture (MoCap)
        • Visual Inertial Odometry (VIO)
          • Realsense T265 Tracking Camera (VIO)
      • Video Streaming
  • Development
    • Getting Started
      • Recommended Hardware/Setup
      • Toolchain Installation
        • MacOS Setup
        • Ubuntu Setup
        • Windows Setup
        • Visual Studio Code IDE
        • Other/Generic Tools
      • Building the Code
      • Writing your First Application
      • Application/Module Template
    • Concepts
      • PX4 Architecture
      • PX4 Flight Stack Architecture
        • Controller Diagrams
      • Events Interface
      • Flight Modes
      • Flight Tasks
      • Control Allocation
      • PWM limit state machine
      • System Startup
      • SD Card Layout
    • Simulation
      • jMAVSim Simulation
        • Multi-Vehicle Sim with JMAVSim
      • Gazebo Simulation
        • Vehicles
        • Multi-Vehicle Sim
      • Gazebo Classic Simulation
        • Vehicles
        • Worlds
        • Multi-Vehicle Sim
      • FlightGear Simulation
        • FlightGear Vehicles
        • Multi-Vehicle Sim with FlightGear
      • JSBSim Simulation
      • AirSim Simulation
      • Multi-Vehicle Simulation
      • Simulate Failsafes
      • HITL Simulation
      • Simulation-In-Hardware
    • Hardware
      • Flight Controller Reference Design
      • Manufacturer’s Board Support Guide
      • Flight Controller Porting Guide
        • PX4 Board Configuration (kconfig)
        • NuttX Board Porting Guide
      • Serial Port Mapping
      • Airframes
        • Adding a New Airframe
      • Device Drivers
      • Telemetry Radio
        • SiK Radio
      • Sensor and Actuator I/O
        • DroneCAN
        • I2C Bus
        • UART/Serial Ports
          • Port-Configurable Serial Drivers
      • RTK GPS (Integration)
    • Middleware
      • uORB Messaging
      • uORB Graph
      • uORB Message Reference
        • ActionRequest
        • ActuatorArmed
        • ActuatorControlsStatus
        • ActuatorMotors
        • ActuatorOutputs
        • ActuatorServos
        • ActuatorServosTrim
        • ActuatorTest
        • AdcReport
        • Airspeed
        • AirspeedValidated
        • AirspeedWind
        • AutotuneAttitudeControlStatus
        • BatteryStatus
        • ButtonEvent
        • CameraCapture
        • CameraStatus
        • CameraTrigger
        • CellularStatus
        • CollisionConstraints
        • CollisionReport
        • ControlAllocatorStatus
        • Cpuload
        • DebugArray
        • DebugKeyValue
        • DebugValue
        • DebugVect
        • DifferentialPressure
        • DistanceSensor
        • Ekf2Timestamps
        • EscReport
        • EscStatus
        • EstimatorAidSource1d
        • EstimatorAidSource2d
        • EstimatorAidSource3d
        • EstimatorBias
        • EstimatorBias3d
        • EstimatorEventFlags
        • EstimatorGpsStatus
        • EstimatorInnovations
        • EstimatorSelectorStatus
        • EstimatorSensorBias
        • EstimatorStates
        • EstimatorStatus
        • EstimatorStatusFlags
        • Event
        • FailsafeFlags
        • FailureDetectorStatus
        • FollowTarget
        • FollowTargetEstimator
        • FollowTargetStatus
        • GeneratorStatus
        • GeofenceResult
        • GimbalControls
        • GimbalDeviceAttitudeStatus
        • GimbalDeviceInformation
        • GimbalDeviceSetAttitude
        • GimbalManagerInformation
        • GimbalManagerSetAttitude
        • GimbalManagerSetManualControl
        • GimbalManagerStatus
        • GpioConfig
        • GpioIn
        • GpioOut
        • GpioRequest
        • GpsDump
        • GpsInjectData
        • Gripper
        • HealthReport
        • HeaterStatus
        • HomePosition
        • HoverThrustEstimate
        • InputRc
        • InternalCombustionEngineStatus
        • IridiumsbdStatus
        • IrlockReport
        • LandingGear
        • LandingGearWheel
        • LandingTargetInnovations
        • LandingTargetPose
        • LaunchDetectionStatus
        • LedControl
        • LogMessage
        • LoggerStatus
        • MagWorkerData
        • MagnetometerBiasEstimate
        • ManualControlSetpoint
        • ManualControlSwitches
        • MavlinkLog
        • MavlinkTunnel
        • Mission
        • MissionResult
        • ModeCompleted
        • MountOrientation
        • NavigatorMissionItem
        • NormalizedUnsignedSetpoint
        • NpfgStatus
        • ObstacleDistance
        • OffboardControlMode
        • OnboardComputerStatus
        • OrbTest
        • OrbTestLarge
        • OrbTestMedium
        • OrbitStatus
        • ParameterUpdate
        • Ping
        • PositionControllerLandingStatus
        • PositionControllerStatus
        • PositionSetpoint
        • PositionSetpointTriplet
        • PowerButtonState
        • PowerMonitor
        • PpsCapture
        • PwmInput
        • Px4ioStatus
        • QshellReq
        • QshellRetval
        • RadioStatus
        • RateCtrlStatus
        • RcChannels
        • RcParameterMap
        • Rpm
        • RtlTimeEstimate
        • SatelliteInfo
        • SensorAccel
        • SensorAccelFifo
        • SensorBaro
        • SensorCombined
        • SensorCorrection
        • SensorGnssRelative
        • SensorGps
        • SensorGyro
        • SensorGyroFft
        • SensorGyroFifo
        • SensorHygrometer
        • SensorMag
        • SensorOpticalFlow
        • SensorPreflightMag
        • SensorUwb
        • SensorSelection
        • SensorsStatus
        • SensorsStatusImu
        • SystemPower
        • TakeoffStatus
        • TaskStackInfo
        • TecsStatus
        • TelemetryStatus
        • TiltrotorExtraControls
        • TimesyncStatus
        • TrajectoryBezier
        • TrajectorySetpoint
        • TrajectoryWaypoint
        • TransponderReport
        • TuneControl
        • UavcanParameterRequest
        • UavcanParameterValue
        • UlogStream
        • UlogStreamAck
        • UwbDistance
        • UwbGrid
        • VehicleAcceleration
        • VehicleAirData
        • VehicleAngularAccelerationSetpoint
        • VehicleAngularVelocity
        • VehicleAttitude
        • VehicleAttitudeSetpoint
        • VehicleCommand
        • VehicleCommandAck
        • VehicleConstraints
        • VehicleControlMode
        • VehicleGlobalPosition
        • VehicleImu
        • VehicleImuStatus
        • VehicleLandDetected
        • VehicleLocalPosition
        • VehicleLocalPositionSetpoint
        • VehicleMagnetometer
        • VehicleOdometry
        • VehicleOpticalFlow
        • VehicleOpticalFlowVel
        • VehicleRatesSetpoint
        • VehicleRoi
        • VehicleStatus
        • VehicleThrustSetpoint
        • VehicleTorqueSetpoint
        • VehicleTrajectoryBezier
        • VehicleTrajectoryWaypoint
        • VtolVehicleStatus
        • Wind
        • YawEstimatorStatus
      • MAVLink Messaging
      • uXRCE-DDS (PX4-ROS 2/DDS Bridge)
    • Modules & Commands
      • Autotune
      • Commands
      • Communication
      • Controllers
      • Drivers
        • Airspeed Sensor
        • Baro
        • Distance Sensor
        • IMU
        • INS
        • Magnetometer
        • Optical Flow
        • Rpm Sensor
        • Transponder
      • Estimators
      • Simulations
      • System
      • Template
    • Debugging/Logging
      • FAQ
      • Consoles/Shells
        • MAVLink Shell
        • System Console
      • Debugging with GDB
        • SWD Debug Port
        • JLink Probe
        • Black Magic/DroneCode Probe
        • STLink Probe
        • Hardfault Debugging
      • Debugging with Eclipse
      • Failure Injection
      • Sensor/Topic Debugging
      • Simulation Debugging
      • Sending Debug Values
      • System-wide Replay
      • Profiling
      • Binary Size Profiling
      • Logging
      • Flight Log Analysis
      • ULog File Format
    • Tutorials
      • Long-distance Video Streaming
      • Connecting an RC Receiver on Linux
    • Advanced Topics
      • Parameters & Configs
      • Package Delivery Architecture
      • Computer Vision
        • Motion Capture (VICON, Optitrack, NOKOV)
      • Installing driver for Intel RealSense R200
      • Switching State Estimators
      • Out-of-Tree Modules
      • STM32 Bootloader
      • System Tunes
      • Advanced Linux Installation Cases
      • Windows Cygwin Toolchain Maintenance
      • Unsupported Developer Setup
        • CentOS Linux
        • Arch Linux
        • Windows VM Toolchain
        • Windows Cygwin Toolchain
        • Qt Creator IDE
    • Platform Testing and CI
      • Test Flights
        • Test MC_01 - Manual Modes
        • Test MC_02 - Full Autonomous
        • Test MC_03 - Auto Manual Mix
        • Test MC_04 - Failsafe Testing
        • Test MC_05 - Indoor Flight (Manual Modes)
      • Unit Tests
      • Continuous Integration
      • MAVSDK Integration Testing
      • ROS Integration Testing
      • Docker Containers
      • Maintenance
  • Drone Apps & APIs
    • Offboard Control from Linux
    • ROS
      • ROS 2
        • ROS 2 User Guide
        • ROS 2 Offboard Control Example
        • ROS 2 Multi Vehicle Simulation
      • ROS 1 with MAVROS
        • ROS/MAVROS Installation Guide
        • ROS/MAVROS Offboard Example (C++)
        • ROS/MAVROS Offboard Example (Python)
        • ROS/MAVROS Sending Custom Messages
        • ROS/MAVROS with Gazebo Classic Simulation
        • Gazebo Classic OctoMap Models with ROS 1
        • ROS/MAVROS Installation on RPi
        • External Position Estimation (Vision/Motion based)
    • DroneKit
  • Contribution (&Dev Call)
    • Dev Call
    • Support
    • Source Code Management
      • GIT Examples
    • Documentation
    • Translation
    • Terminology/Notation
    • Licenses
  • Releases
    • 1.14
    • 1.13
    • 1.12
Powered by GitBook
On this page
  • Overview
  • Installation & Setup
  • Install PX4
  • Install ROS 2
  • Setup Micro XRCE-DDS Agent & Client
  • Build ROS 2 Workspace
  • Controlling a Vehicle
  • Compatibility Issues
  • ROS 2 Subscriber QoS Settings
  • ROS 2 & PX4 Frame Conventions
  • ROS 2 Example Applications
  • ROS 2 Listener
  • ROS 2 Advertiser
  • Offboard Control
  • Using Flight Controller Hardware
  • Custom uORB Topics
  • Customizing the Topic Namespace
  • ros2 CLI
  • ros2 topic list
  • ros2 topic echo
  • ros2 topic hz
  • ros2 launch
  • Troubleshooting
  • Missing dependencies
  • Additional information
  1. Drone Apps & APIs
  2. ROS
  3. ROS 2

ROS 2 User Guide

PreviousROS 2NextROS 2 Offboard Control Example

Last updated 1 year ago

The ROS 2-PX4 architecture provides a deep integration between ROS 2 and PX4, allowing ROS 2 subscribers or publisher nodes to interface directly with PX4 uORB topics.

This topic provides an overview of the architecture and application pipeline, and explains how to setup and use ROS 2 with PX4.

:::note From PX4 v1.14, ROS 2 uses middleware, replacing the FastRTPS middleware that was used in version 1.13 (v1.13 does not support uXRCE-DDS).

The explains what you need to do in order to migrate ROS 2 apps from PX4 v1.13 to PX4 v1.14.

If you're still working on PX4 v1.13, please follow the instructions in the .

:::

Overview

The application pipeline for ROS 2 is very straightforward, thanks to the use of the communications middleware.

The uXRCE-DDS middleware consists of a client running on PX4 and an agent running on the companion computer, with bi-directional data exchange between them over a serial, UDP, TCP or custom link. The agent acts as a proxy for the client to publish and subscribe to topics in the global DDS data space.

You will normally need to start both the client and agent when using ROS 2. Note that the uXRCE-DDS client is built into firmware by default but not started automatically except for simulator builds.

Installation & Setup

The supported ROS 2 platforms for PX4 development are ROS 2 "Humble" on Ubuntu 22.04, and ROS 2 "Foxy" on Ubuntu 20.04.

ROS 2 "Humble" is recommended because it is the current ROS 2 LTS distribution. ROS 2 "Foxy" reached end-of-life in May 2023, but is still stable and works with PX4.

To setup ROS 2 for use with PX4:

Other dependencies of the architecture that are installed automatically, such as Fast DDS, are not covered.

Install PX4

You need to install the PX4 development toolchain in order to use the simulator.

Set up a PX4 development environment on Ubuntu in the normal way:

cd
git clone https://github.com/PX4/PX4-Autopilot.git --recursive
bash ./PX4-Autopilot/Tools/setup/ubuntu.sh
cd PX4-Autopilot/
make px4_sitl

Note that the above commands will install the recommended simulator for your version of Ubuntu. If you want to install PX4 but keep your existing simulator installation, run ubuntu.sh above with the --no-sim-tools flag.

Install ROS 2

To install ROS 2 and its dependencies:

  1. Install ROS 2.

    :::: tabs

    ::: tab humble To install ROS 2 "Humble" on Ubuntu 22.04:

    sudo apt update && sudo apt install locales
    sudo locale-gen en_US en_US.UTF-8
    sudo update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8
    export LANG=en_US.UTF-8
    sudo apt install software-properties-common
    sudo add-apt-repository universe
    sudo apt update && sudo apt install curl -y
    sudo curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o /usr/share/keyrings/ros-archive-keyring.gpg
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/ros-archive-keyring.gpg] http://packages.ros.org/ros2/ubuntu $(. /etc/os-release && echo $UBUNTU_CODENAME) main" | sudo tee /etc/apt/sources.list.d/ros2.list > /dev/null
    sudo apt update && sudo apt upgrade -y
    sudo apt install ros-humble-desktop
    sudo apt install ros-dev-tools
    source /opt/ros/humble/setup.bash && echo "source /opt/ros/humble/setup.bash" >> .bashrc

    ::: tab foxy To install ROS 2 "Foxy" on Ubuntu 20.04:

    You can install either the desktop (ros-foxy-desktop) or bare-bones versions (ros-foxy-ros-base), and the development tools (ros-dev-tools). :::

    ::::

  2. Some Python dependencies must also be installed (using pip or apt):

    pip install --user -U empy pyros-genmsg setuptools

Setup Micro XRCE-DDS Agent & Client

Setup the Agent

To setup and start the agent:

  1. Open a terminal.

  2. Enter the following commands to fetch and build the agent from source:

    git clone https://github.com/eProsima/Micro-XRCE-DDS-Agent.git
    cd Micro-XRCE-DDS-Agent
    mkdir build
    cd build
    cmake ..
    make
    sudo make install
    sudo ldconfig /usr/local/lib/
  3. Start the agent with settings for connecting to the uXRCE-DDS client running on the simulator:

    MicroXRCEAgent udp4 -p 8888

The agent is now running, but you won't see much until we start PX4 (in the next step).

:::note You can leave the agent running in this terminal! Note that only one agent is allowed per connection channel. :::

Start the Client

The PX4 simulator starts the uXRCE-DDS client automatically, connecting to UDP port 8888 on the local host.

To start the simulator (and client):

  1. Open a new terminal in the root of the PX4 Autopilot repo that was installed above.

    :::: tabs

    ::: tab humble

    • make px4_sitl gz_x500

    :::

    ::: tab foxy

    • make px4_sitl gazebo-classic

    :::

    ::::

The agent and client are now running they should connect.

...
INFO  [uxrce_dds_client] synchronized with time offset 1675929429203524us
INFO  [uxrce_dds_client] successfully created rt/fmu/out/failsafe_flags data writer, topic id: 83
INFO  [uxrce_dds_client] successfully created rt/fmu/out/sensor_combined data writer, topic id: 168
INFO  [uxrce_dds_client] successfully created rt/fmu/out/timesync_status data writer, topic id: 188
...

The micro XRCE-DDS agent terminal should also start to show output, as equivalent topics are created in the DDS network:

...
[1675929445.268957] info     | ProxyClient.cpp    | create_publisher         | publisher created      | client_key: 0x00000001, publisher_id: 0x0DA(3), participant_id: 0x001(1)
[1675929445.269521] info     | ProxyClient.cpp    | create_datawriter        | datawriter created     | client_key: 0x00000001, datawriter_id: 0x0DA(5), publisher_id: 0x0DA(3)
[1675929445.270412] info     | ProxyClient.cpp    | create_topic             | topic created          | client_key: 0x00000001, topic_id: 0x0DF(2), participant_id: 0x001(1)
...

Build ROS 2 Workspace

This section shows how create a ROS 2 workspace hosted in your home directory (modify the commands as needed to put the source code elsewhere).

Building the Workspace

To create and build the workspace:

  1. Open a new terminal.

  2. Create and navigate into a new workspace directory using:

    mkdir -p ~/ws_sensor_combined/src/
    cd ~/ws_sensor_combined/src/

    :::note A naming convention for workspace folders can make it easier to manage workspaces. :::

  3. git clone https://github.com/PX4/px4_msgs.git
    git clone https://github.com/PX4/px4_ros_com.git
  4. Source the ROS 2 development environment into the current terminal and compile the workspace using colcon:

    :::: tabs

    ::: tab humble

    cd ..
    source /opt/ros/humble/setup.bash
    colcon build

    :::

    ::: tab foxy

    cd ..
    source /opt/ros/foxy/setup.bash
    colcon build

    :::

    ::::

    This builds all the folders under /src using the sourced toolchain.

Running the Example

To run the executables that you just built, you need to source local_setup.bash. This provides access to the "environment hooks" for the current workspace. In other words, it makes the executables that were just built available in the current terminal.

In a new terminal:

  1. Navigate into the top level of your workspace directory and source the ROS 2 environment (in this case "Humble"):

    :::: tabs

    ::: tab humble

    cd ~/ws_sensor_combined/
    source /opt/ros/humble/setup.bash

    :::

    ::: tab foxy

    cd ~/ws_sensor_combined/
    source /opt/ros/foxy/setup.bash

    :::

    ::::

  2. Source the local_setup.bash.

    source install/local_setup.bash
  3. Now launch the example. Note here that we use ros2 launch, which is described below.

    ros2 launch px4_ros_com sensor_combined_listener.launch.py

If this is working you should see data being printed on the terminal/console where you launched the ROS listener:

RECEIVED DATA FROM SENSOR COMBINED
================================
ts: 870938190
gyro_rad[0]: 0.00341645
gyro_rad[1]: 0.00626475
gyro_rad[2]: -0.000515705
gyro_integral_dt: 4739
accelerometer_timestamp_relative: 0
accelerometer_m_s2[0]: -0.273381
accelerometer_m_s2[1]: 0.0949186
accelerometer_m_s2[2]: -9.76044
accelerometer_integral_dt: 4739

Controlling a Vehicle

To control applications, ROS 2 applications:

  • subscribe to (listen to) telemetry topics published by PX4

  • publish to topics that cause PX4 to perform some action.

Compatibility Issues

This section contains information that may affect how you write your ROS code.

ROS 2 Subscriber QoS Settings

...
rmw_qos_profile_t qos_profile = rmw_qos_profile_sensor_data;
auto qos = rclcpp::QoS(rclcpp::QoSInitialization(qos_profile.history, 5), qos_profile);

subscription_ = this->create_subscription<px4_msgs::msg::SensorCombined>("/fmu/out/sensor_combined", qos,
...

ROS 2 & PX4 Frame Conventions

The local/world and body frames used by ROS and PX4 are different.

Frame
PX4
ROS

Body

FRD (X Forward, Y Right, Z Down)

FLU (X Forward, Y Left, Z Up)

World

FRD or NED (X North, Y East, Z Down)

FLU or ENU (X East, Y North, Z Up)

Both frames are shown in the image below (FRD on the left/FLU on the right).

The FRD (NED) conventions are adopted on all PX4 topics unless explicitly specified in the associated message definition. Therefore, ROS 2 nodes that want to interface with PX4 must take care of the frames conventions.

  • To rotate a vector from ENU to NED two basic rotations must be performed:

    • first a pi/2 rotation around the Z-axis (up),

    • then a pi rotation around the X-axis (old East/new North).

  • To rotate a vector from NED to ENU two basic rotations must be performed:

    • first a pi/2 rotation around the Z-axis (down),

    • then a pi rotation around the X-axis (old North/new East). Note that the two resulting operations are mathematically equivalent.

  • To rotate a vector from FLU to FRD a pi rotation around the X-axis (front) is sufficient.

  • To rotate a vector from FRD to FLU a pi rotation around the X-axis (front) is sufficient.

Examples of vectors that require rotation are:

Similarly to vectors, also quanternions representing the attitude of the vehicle (body frame) w.r.t. the world frame require conversion.

ROS 2 Example Applications

ROS 2 Listener

The code first imports the C++ libraries needed to interface with the ROS 2 middleware and the header file for the SensorCombined message to which the node subscribes:

#include <rclcpp/rclcpp.hpp>
#include <px4_msgs/msg/sensor_combined.hpp>

Then it creates a SensorCombinedListener class that subclasses the generic rclcpp::Node base class.

/**
 * @brief Sensor Combined uORB topic data callback
 */
class SensorCombinedListener : public rclcpp::Node
{

This creates a callback function for when the SensorCombined uORB messages are received (now as micro XRCE-DDS messages), and outputs the content of the message fields each time the message is received.

public:
	explicit SensorCombinedListener() : Node("sensor_combined_listener")
	{
		rmw_qos_profile_t qos_profile = rmw_qos_profile_sensor_data;
		auto qos = rclcpp::QoS(rclcpp::QoSInitialization(qos_profile.history, 5), qos_profile);
		
		subscription_ = this->create_subscription<px4_msgs::msg::SensorCombined>("/fmu/out/sensor_combined", qos,
		[this](const px4_msgs::msg::SensorCombined::UniquePtr msg) {
			std::cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
			std::cout << "RECEIVED SENSOR COMBINED DATA"   << std::endl;
			std::cout << "============================="   << std::endl;
			std::cout << "ts: "          << msg->timestamp    << std::endl;
			std::cout << "gyro_rad[0]: " << msg->gyro_rad[0]  << std::endl;
			std::cout << "gyro_rad[1]: " << msg->gyro_rad[1]  << std::endl;
			std::cout << "gyro_rad[2]: " << msg->gyro_rad[2]  << std::endl;
			std::cout << "gyro_integral_dt: " << msg->gyro_integral_dt << std::endl;
			std::cout << "accelerometer_timestamp_relative: " << msg->accelerometer_timestamp_relative << std::endl;
			std::cout << "accelerometer_m_s2[0]: " << msg->accelerometer_m_s2[0] << std::endl;
			std::cout << "accelerometer_m_s2[1]: " << msg->accelerometer_m_s2[1] << std::endl;
			std::cout << "accelerometer_m_s2[2]: " << msg->accelerometer_m_s2[2] << std::endl;
			std::cout << "accelerometer_integral_dt: " << msg->accelerometer_integral_dt << std::endl;
		});
	}

The lines below create a publisher to the SensorCombined uORB topic, which can be matched with one or more compatible ROS 2 subscribers to the fmu/sensor_combined/out ROS 2 topic.

private:
	rclcpp::Subscription<px4_msgs::msg::SensorCombined>::SharedPtr subscription_;
};

The instantiation of the SensorCombinedListener class as a ROS node is done on the main function.

int main(int argc, char *argv[])
{
	std::cout << "Starting sensor_combined listener node..." << std::endl;
	setvbuf(stdout, NULL, _IONBF, BUFSIZ);
	rclcpp::init(argc, argv);
	rclcpp::spin(std::make_shared<SensorCombinedListener>());

	rclcpp::shutdown();
	return 0;
}

ROS 2 Advertiser

A ROS 2 advertiser node publishes data into the DDS/RTPS network (and hence to the PX4 Autopilot).

Taking as an example the debug_vect_advertiser.cpp under px4_ros_com/src/advertisers, first we import required headers, including the debug_vect msg header.

#include <chrono>
#include <rclcpp/rclcpp.hpp>
#include <px4_msgs/msg/debug_vect.hpp>

using namespace std::chrono_literals;

Then the code creates a DebugVectAdvertiser class that subclasses the generic rclcpp::Node base class.

class DebugVectAdvertiser : public rclcpp::Node
{

The code below creates a function for when messages are to be sent. The messages are sent based on a timed callback, which sends two messages per second based on a timer.

public:
	DebugVectAdvertiser() : Node("debug_vect_advertiser") {
		publisher_ = this->create_publisher<px4_msgs::msg::DebugVect>("fmu/debug_vect/in", 10);
		auto timer_callback =
		[this]()->void {
			auto debug_vect = px4_msgs::msg::DebugVect();
			debug_vect.timestamp = std::chrono::time_point_cast<std::chrono::microseconds>(std::chrono::steady_clock::now()).time_since_epoch().count();
			std::string name = "test";
			std::copy(name.begin(), name.end(), debug_vect.name.begin());
			debug_vect.x = 1.0;
			debug_vect.y = 2.0;
			debug_vect.z = 3.0;
			RCLCPP_INFO(this->get_logger(), "\033[97m Publishing debug_vect: time: %llu x: %f y: %f z: %f \033[0m",
                                debug_vect.timestamp, debug_vect.x, debug_vect.y, debug_vect.z);
			this->publisher_->publish(debug_vect);
		};
		timer_ = this->create_wall_timer(500ms, timer_callback);
	}

private:
	rclcpp::TimerBase::SharedPtr timer_;
	rclcpp::Publisher<px4_msgs::msg::DebugVect>::SharedPtr publisher_;
};

The instantiation of the DebugVectAdvertiser class as a ROS node is done on the main function.

int main(int argc, char *argv[])
{
	std::cout << "Starting debug_vect advertiser node..." << std::endl;
	setvbuf(stdout, NULL, _IONBF, BUFSIZ);
	rclcpp::init(argc, argv);
	rclcpp::spin(std::make_shared<DebugVectAdvertiser>());

	rclcpp::shutdown();
	return 0;
}

Offboard Control

Using Flight Controller Hardware

ROS 2 with PX4 running on a flight controller is almost the same as working with PX4 on the simulator. The only difference is that you need to start both the agent and the client, with settings appropriate for the communication channel.

Custom uORB Topics

  • rm ~/px4_ros_com/src/px4_msgs/msg/*.msg
    cp ~/PX4-Autopilot/mgs/*.msg ~/px4_ros_com/src/px4_msgs/msg/

Customizing the Topic Namespace

  • A custom namespace can be provided for simulations (only) by setting the environment variable PX4_UXRCE_DDS_NS before starting the simulation.

uxrce_dds_client start -n uav_1

or

PX4_UXRCE_DDS_NS=uav_1 make px4_sitl gz_x500

will generate topics under the namespaces:

/uav_1/fmu/in/  # for subscribers
/uav_1/fmu/out/ # for publishers

:::

ros2 CLI

ros2 topic list

Use ros2 topic list to list the topics visible to ROS 2:

ros2 topic list

If PX4 is connected to the agent, the result will be a list of topic types:

/fmu/in/obstacle_distance
/fmu/in/offboard_control_mode
/fmu/in/onboard_computer_status
...

Note that the workspace does not need to build with px4_msgs for this to succeed; topic type information is part of the message payload.

ros2 topic echo

Use ros2 topic echo to show the details of a particular topic.

Unlike with ros2 topic list, for this to work you must be in a workspace has built the px4_msgs and sourced local_setup.bash so that ROS can interpret the messages.

ros2 topic echo /fmu/out/vehicle_status

The command will echo the topic details as they update.

---
timestamp: 1675931593364359
armed_time: 0
takeoff_time: 0
arming_state: 1
latest_arming_reason: 0
latest_disarming_reason: 0
nav_state_timestamp: 3296000
nav_state_user_intention: 4
nav_state: 4
failure_detector_status: 0
hil_state: 0
...
---

ros2 topic hz

You can get statistics about the rates of messages using ros2 topic hz. For example, to get the rates for SensorCombined:

ros2 topic hz /fmu/out/sensor_combined

The output will look something like:

average rate: 248.187
  min: 0.000s max: 0.012s std dev: 0.00147s window: 2724
average rate: 248.006
  min: 0.000s max: 0.012s std dev: 0.00147s window: 2972
average rate: 247.330
  min: 0.000s max: 0.012s std dev: 0.00148s window: 3212
average rate: 247.497
  min: 0.000s max: 0.012s std dev: 0.00149s window: 3464
average rate: 247.458
  min: 0.000s max: 0.012s std dev: 0.00149s window: 3712
average rate: 247.485
  min: 0.000s max: 0.012s std dev: 0.00148s window: 3960

ros2 launch

The ros2 launch command is used to start a ROS 2 launch file. For example, above we used ros2 launch px4_ros_com sensor_combined_listener.launch.py to start the listener example.

You don't need to have a launch file, but they are very useful if you have a complex ROS 2 system that needs to start several components.

Troubleshooting

Missing dependencies

The standard installation should include all the tools needed by ROS 2.

If any are missing, they can be added separately:

  • colcon build tools should be in the development tools. It can be installed using:

    sudo apt install python3-colcon-common-extensions
  • The Eigen3 library used by the transforms library should be in the both the desktop and base packages. It should be installed as shown:

    :::: tabs

    ::: tab humble

    sudo apt install ros-humble-eigen3-cmake-module

    :::

    ::: tab foxy

    sudo apt install ros-foxy-eigen3-cmake-module

    :::

    ::::

Additional information

The PX4 is generated at build time and included in PX4 firmware by default. It includes both the "generic" micro XRCE-DDS client code, and PX4-specific translation code that it uses to publish to/from uORB topics. The subset of uORB messages that are generated into the client are listed in . The generator uses the uORB message definitions in the source tree: to create the code for sending ROS 2 messages.

ROS 2 applications need to be built in a workspace that has the same message definitions that were used to create the uXRCE-DDS client module in the PX4 Firmware. You can include these by cloning the interface package into your ROS 2 workspace (branches in the repo correspond to the messages for different PX4 releases).

Note that the micro XRCE-DDS agent itself has no dependency on client-side code. It can be built from either standalone or as part of a ROS build, or installed as a snap.

:::note In PX4v1.13 and earlier, ROS 2 was dependent on definitions in . This repo is no longer needed, but does contain useful examples. :::

:::note PX4 is not as well tested on Ubuntu 22.04 as it is on Ubuntu 20.04 (at time of writing), and Ubuntu 20.04 is needed if you want to use . :::

(to use the PX4 simulator)

:::note The only dependency ROS 2 has on PX4 is the set of message definitions, which it gets from . You only need to install PX4 if you need the simulator (as we do in this guide), or if you are creating a build that publishes custom uORB topics. :::

For more information and troubleshooting see: and .

The instructions above are reproduced from the official installation guide: . You can install either the desktop (ros-humble-desktop) or bare-bones versions (ros-humble-ros-base), and the development tools (ros-dev-tools). :::

Follow the official installation guide: .

For ROS 2 to communicate with PX4, must be running on PX4, connected to a micro XRCE-DDS agent running on the companion computer.

The agent can be installed onto the companion computer in a . Below we show how to build the agent "standalone" from source and connect to a client running on the PX4 simulator.

Start a PX4 simulation using:

Start a PX4 simulation using:

The PX4 terminal displays the output as PX4 boots and runs. As soon as the agent connects the output should include INFO messages showing creation of data writers:

The and packages are cloned to a workspace folder, and then the colcon tool is used to build the workspace. The example is run using ros2 launch.

:::note The example builds the example application, located in . is needed too so that the example can interpret PX4 ROS 2 topics. :::

Clone the example repository and to the /src directory (the main branch is cloned by default, which corresponds to the version of PX4 we are running):

:::note The recommend that you open a new terminal for running your executables. :::

The topics that you can use are defined in , and you can get more information about their data in the . For example, can be used to get the vehicle global position, while can be used to command actions such as takeoff and land.

The examples below provide concrete examples of how to use these topics.

ROS 2 code that subscribes to topics published by PX4 must specify a appropriate (compatible) QoS setting in order to listen to topics. Specifically, nodes should subscribe using the ROS 2 predefined QoS sensor data (from the ):

This is needed because the ROS 2 default are different from the settings used by PX4. Not all combinations of publisher-subscriber , and it turns out that the default ROS 2 settings for subscribing are not! Note that ROS code does not have to set QoS settings when publishing (the PX4 settings are compatible with ROS defaults in this case).

:::tip See for more information about ROS frames. :::

all fields in message; ENU to NED conversion is required before sending them.

all fields in message; FLU to FRD conversion is required before sending them.

provides the shared library to easily perform such conversions.

The ROS 2 in the repo demonstrate how to write ROS nodes to listen to topics published by PX4.

Here we consider the node under px4_ros_com/src/examples/listeners, which subscribes to the message.

:::note shows how to build and run this example. :::

:::note The subscription sets a QoS profile based on rmw_qos_profile_sensor_data. This is needed because the default ROS 2 QoS profile for subscribers is incompatible with the PX4 profile for publishers. For more information see: , :::

This particular example has an associated launch file at . This allows it to be launched using the command.

For a complete reference example on how to use Offboard control with PX4, see: .

For more information see .

ROS 2 needs to have the same message definitions that were used to create the uXRCE-DDS client module in the PX4 Firmware in order to interpret the messages. The definition are stored in the ROS 2 interface package and they are automatically synchronized by CI on the main and release branches. Note that all the messages from PX4 source code are present in the repository, but only those listed in dds_topics.yaml will be available as ROS 2 topics. Therefore,

If you're using a main or release version of PX4 you can get the message definitions by cloning the interface package into your workspace.

If you're creating or modifying uORB messages you must manually update the messages in your workspace from your PX4 source tree. Generally this means that you would update , clone the interface package, and then manually synchronize it by copying the new/modified message definitions from to its msg folders. Assuming that PX4-Autopilot is in your home directory ~, while px4_msgs is in ~/px4_ros_com/src/, then the command might be:

:::note Technically, completely defines the relationship between PX4 uORB topics and ROS 2 messages. For more information see . :::

Custom topic namespaces can be applied at build time (changing ) or at runtime (useful for multi vehicle operations):

One possibility is to use the -n option when starting the from command line. This technique can be used both in simulation and real vehicles.

:::note Changing the namespace at runtime will append the desired namespace as a prefix to all topic fields in . Therefore, commands like:

The is a useful tool for working with ROS. You can use it, for example, to quickly check whether topics are being published, and also inspect them in detail if you have px4_msg in the workspace. The command also lets you launch more complex ROS systems via a launch file. A few possibilities are demonstrated below.

For information about launch files see

- Pablo Garrido & Nuno Marques (youtube)

PX4/px4_msgs
source
px4_ros_com
Gazebo Classic
px4_msgs
Ubuntu Development Environment
Download PX4 source
Install ROS 2 Humble
Install ROS 2 Foxy
Gazebo
Gazebo Classic
NuttShell/PX4 System Console
px4_ros_com
px4_msgs
px4_msgs
ROS2 beginner tutorials
dds_topics.yaml
uORB Message Reference
VehicleGlobalPosition
VehicleCommand
Quality of Service (QoS) settings
Qos settings are possible
REP105: Coordinate Frames for Mobile Platforms
TrajectorySetpoint
VehicleThrustSetpoint
PX4/px4_ros_com
frame_transforms
listener examples
px4_ros_com
sensor_combined_listener.cpp
SensorCombined
ROS 2 Offboard control example
PX4/px4_msgs
PX4/px4_msgs
dds_topics.yaml
PX4-Autopilot/msg
dds_topics.yaml
dds_topics.yaml
ros2 CLI
ROS 2 Tutorials > Creating launch files
ROS 2 in PX4: Technical Details of a Seamless Transition to XRCE-DDS
DDS and ROS middleware implementations
Install PX4
Install ROS 2
Setup Micro XRCE-DDS Agent & Client
Build & Run ROS 2 Workspace
px4_ros_com
px4_msgs
ROS 2 Listener
ROS 2 Example applications
listener example source code
Build ROS 2 Workspace
ROS 2 Subscriber QoS Settings
launch/sensor_combined_listener.launch.py
ros2 launch
uXRCE-DDS
PX4 v1.13 Docs
uXRCE-DDS
PX4-Autopilot/src/modules/uxrce_dds_client/dds_topics.yaml
PX4-Autopilot/msg
dds_topics.yaml
number of ways
Starting uXRCE-DDS
uXRCE-DDS > DDS Topics YAML
migration guide
Architecture uXRCE-DDS with ROS 2
Reference frames
uxrce_dds_client
uXRCE-DDS client
uxrce_dds_client