基于ROS Melodic,以px4开发者手册实例程序为例,实现gazebo下无人机起飞两米悬停,具体操作分为三步:
1、创建工作空间,建立offboard包
2、构建mavros
3、运行
欢迎阅读专栏:带你用ROS玩转无人机进行前序知识储备,本次操作涉及Ubuntu18.04下安装ROS Melodic详细步骤与填坑指南、Ubuntu18.04下搭建PX4工具链+QGC+在环仿真编译、新建ROS工作空间、Ubuntu18.04+ROS Melodic配置MAVROS
下面进入正题:
一、构建工作空间
//构建ROS工作空间,本次操作的空间名称为uav_offb
mkdir -p ~/uav_offb/src
cd uav_offb/src/
catkin_init_workspace
cd ..
catkin_make
source devel/setup.bash
//创建工作包
cd src/
catkin_create_pkg offb roscpp mavros geometry_msgs
cd offb/src
touch offb_node.cpp
vim offb_node.cpp
//下面插入offboard 模式控制例程
/**
* @file offb_node.cpp
* @brief Offboard control example node, written with MAVROS version 0.19.x, PX4 Pro Flight
* Stack and tested in Gazebo SITL
*/
#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;
}
完成后接前面的步骤:
cd ..
//修改CMakeLists文件,涉及2处,具体可参考文末截图
vim CMakeLists.txt
cd ..
cd ..
catkin_make
二、构建mavros
参考前序知识,因为电脑中已经配置好,此处省略
三、运行
打开三个终端,分别运行如下内容:
1、打开px4在环仿真
cd PX4-Autopilot/
make px4_sitl_default gazebo
2、运行mavros
roslaunch mavros px4.launch fcu_url:="udp://:14540@127.0.0.1:14557"
3、运行offboard节点
cd uav_offb/
rosrun offb offb_node