2.7 获取激光雷达数据与避障
1.获取激光雷达数据
首先介绍介绍一下激光雷达的角度,方向“前”是机器人正方向
进入wpr_simulation进行更新
cd ~/catkin_ws/src/wpr_simulation/
进行更新
git pull
然后回退到catkin_ws
cd ~/catkin_ws/
进行编译
catkin_make
终端执行以下命令
roslaunch wpr_simulation wpb_simple.launch
分屏执行以下程序
rosrun wpr_simulation demo_lidar_data
获得机器人前方障碍物距离
接下来我们来实现该功能 ,先进入~/catkin/src/
创建雷达包
catkin_create_pkg lidar_pkg roscpp rospy sensor_msgs
在节点文件键入以下代码
#include<ros/ros.h>
#include<sensor_msgs/LaserScan.h>void LidarCallback(const sensor_msgs::LaserScan msg)
{float fMidDist = msg.ranges[180];ROS_INFO("前方测距ranges[180]=%f米",fMidDist);
}int main(int argc, char *argv[])
{//设置中文编码setlocale(LC_ALL,"");//初始化节点ros::init(argc,argv,"lidar_node");ros::NodeHandle n;ros::Subscriber lidar_sub = n.subscribe("/scan",10,&LidarCallback);ros::spin();return 0;
}
在仿真环境运行的基础上执行以下命令
rosrun lidar_pkg lidar_node
运行结果为:
2.实现避障功能
由于发布的速度在回调函数中使用,所以发布的变量是全局变量
ros::Publisher vel_pub;
所有代码如下:
#include<ros/ros.h>
#include<sensor_msgs/LaserScan.h>
#include<geometry_msgs/Twist.h>ros::Publisher vel_pub;void LidarCallback(const sensor_msgs::LaserScan msg)
{float fMidDist = msg.ranges[180];ROS_INFO("前方测距ranges[180]=%f米",fMidDist);geometry_msgs::Twist vel_cmd;if (fMidDist<1.5){vel_cmd.angular.z=0.3;}else{vel_cmd.linear.x=0.05;}vel_pub.publish(vel_cmd);
}int main(int argc, char *argv[])
{//设置中文编码setlocale(LC_ALL,"");//初始化节点ros::init(argc,argv,"lidar_node");ros::NodeHandle n;ros::Subscriber lidar_sub = n.subscribe("/scan",10,&LidarCallback);vel_pub=n.advertise<geometry_msgs::Twist>("/cmd_vel",10);ros::spin();return 0;
}
避障成功