PX4 Offboard Control Using MAVROS on ROS

本文详细介绍了如何在Ubuntu环境中配置并利用PX4飞控的offboard模式,配合外部设备控制无人机在2米高度自主飞行。步骤包括安装依赖、创建工作空间、编写并编译offboard_node.cpp,以及在实际环境中通过jmavsim进行软件在环仿真和地面站控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pixhawk4飞控作为一款开源且流行的飞控,在其硬件版本上可以支持APM固件与PX4原生固件。本文针对PX4原生固件进行介绍。PX4中的offboard模式能够接受来自外部的控制指令,搭配机载或支持MAVROS的协同计算机(如tx1,tx2,树莓派,dji妙算等等),可在PX4飞控平台上加入视觉处理或人工智能,以实现无人机自动控制功能。这里详细介绍一个offboard的例程,外部控制飞机自主飞行2m的高度。

首先需要在Ubuntu的环境下安装好ros,mavros以及px4原生固件

1.为外部控制例程建立一个工作空间   

mkdir -p px4_offboard_ws/src

2.新建一个用于offboard的功能包

cd px4_offboard_ws/src
catkin_create_pkg offboard roscpp std_msgs geometry_msgs mavros_msgs

3.建立好ros包过后,新建一个可cpp源文件用来作为这个功能包的执行文件

cd offboard/src
gedit offboard_node.cpp

4.offboard_node.cpp中的代码如下

#include <ros/ros.h>
#include <geometry_msgs/PoseStamped.h>
#include <mavros_msgs/CommandBool.h>
#include <mavros_msgs/SetMode.h>
#include <mavros_msgs/State.h>

mavros_msgs::State current_state;
void state_cb(const mavros_msgs::State::ConstPtr& msg){
    current_state = *msg;
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "offb_node");
    ros::NodeHandle nh;

    ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State>
            ("mavros/state", 10, state_cb);
    ros::Publisher local_pos_pub = nh.advertise<geometry_msgs::PoseStamped>
            ("mavros/setpoint_position/local", 10);
    ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool>
            ("mavros/cmd/arming");
    ros::ServiceClient set_mode_client = nh.serviceClient<mavros_msgs::SetMode>
            ("mavros/set_mode");

    //the setpoint publishing rate MUST be faster than 2Hz
    ros::Rate rate(20.0);

    // wait for FCU connection
    while(ros::ok() && !current_state.connected){
        ros::spinOnce();
        rate.sleep();
    }

    geometry_msgs::PoseStamped pose;
    pose.pose.position.x = 0;
    pose.pose.position.y = 0;
    pose.pose.position.z = 2;

    //send a few setpoints before starting
    for(int i = 100; ros::ok() && i > 0; --i){
        local_pos_pub.publish(pose);
        ros::spinOnce();
        rate.sleep();
    }

    mavros_msgs::SetMode offb_set_mode;
    offb_set_mode.request.custom_mode = "OFFBOARD";

    mavros_msgs::CommandBool arm_cmd;
    arm_cmd.request.value = true;

    ros::Time last_request = ros::Time::now();

    while(ros::ok()){
        if( current_state.mode != "OFFBOARD" &&
            (ros::Time::now() - last_request > ros::Duration(5.0))){
            if( set_mode_client.call(offb_set_mode) &&
                offb_set_mode.response.mode_sent){
                ROS_INFO("Offboard enabled");
            }
            last_request = ros::Time::now();
        } else {
            if( !current_state.armed &&
                (ros::Time::now() - last_request > ros::Duration(5.0))){
                if( arming_client.call(arm_cmd) &&
                    arm_cmd.response.success){
                    ROS_INFO("Vehicle armed");
                }
                last_request = ros::Time::now();
            }
        }

        local_pos_pub.publish(pose);

        ros::spinOnce();
        rate.sleep();
    }

    return 0;
}

5.修改CMakeLists.txt为编译做准备

cd ..
gedit CMakeLists.txt

6.在CMakeLists.txt最末尾添加如下内容后保存退出

add_executable(${PROJECT_NAME}_node src/offboard_node.cpp)
target_link_libraries(${PROJECT_NAME}_node
  ${catkin_LIBRARIES}
)

7.开始编译

cd ~/px4_offboard_ws
catkin_make

8.把这个工作空间添加到.bashrc里面方便启动节点

echo "source ~/px4_offboard_ws/devel/setup.bash" >> ~/.bashrc

9.通过jmavsim进行软件在环仿真,打开一个终端启动仿真

cd px4_source_code/Firmware
make px4_sitl_default jmavsim

10.再开一个终端运行mavros

roslaunch mavros px4.launch fcu_url:="udp://:14540@127.0.0.1:14557"

11.打开一个终端运行外部控制的节点

rosrun offboard offboard_node

12.打开qgc地面站,可以观察此时飞机飞行高度为2m

### MavLink SITL Configuration Tutorial For configuring a drone simulation using MAVLink with Software-In-the-Loop (SITL), several key components need attention. The process involves setting up the environment where simulations can run effectively. The command to start flying a simulated drone is provided through Python scripts that interact directly with the PX4 flight stack or similar systems[^2]. This indicates an established method for initiating flights within a controlled testing environment. To configure SITL properly: #### Setting Up Environment Variables Ensure all necessary environment variables are set correctly so that the system recognizes paths required by MAVLink and other dependencies. ```bash source /opt/ros/noetic/setup.bash cd ~/catkin_ws && catkin_make source devel/setup.bash ``` #### Running Simulation Scripts Use predefined scripts located typically under directories like `/home/user/catkin_ws/GAAS/demo/tutorial_2/`. These scripts handle initialization of parameters needed for running simulations including takeoff sequences as shown below: ```python import rospy from mavros_msgs.msg import State rospy.init_node('mavlink_sitl') state_msg = rospy.wait_for_message("/mavros/state", State) if not state_msg.armed: arming_client(True) takeoff_altitude = 10 arming_client = rospy.ServiceProxy('/mavros/cmd/arming', CommandBool) set_mode_client = rospy.ServiceProxy('/mavros/set_mode', SetMode) set_mode_client(custom_mode="OFFBOARD") con.move(0, 0, takeoff_altitude) # Move upward by specified altitude rospy.sleep(2) # Wait before proceeding further actions ``` This script demonstrates how one might prepare a virtual drone for operation at a specific height after ensuring it has armed successfully and switched into offboard mode which allows external control via MAVLink messages[^1]. #### Configuring Parameters Adjusting various settings such as telemetry rates, mission items, etc., ensures smooth communication between ground station software and the simulated vehicle during tests.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值