申明:ROS学习参考了古月居老师的Blibli视频,强烈推荐大家看视频学习,本博客仅记录自己的学习经历和心得,欢迎大家一起讨论!
其中,ROS Master是节点管理器,其下有两个主要节点,Subscriber是订阅者节点,即海龟仿真器(Turtlesim),Publisher是发布者节点,即海龟速度控制。
如何实现一个发布者?
#进入src文件
cd ~/catkin_ws/src/
#创建功能包并添加依赖
catkin_create_pkg learning_topic roscpp rospy std_msgs geometry_msgs turtlesim
在learning_topic下的src文件夹下新建.cpp文件或.py文件,需要在此learning_topic/src文件夹下运行:
(1)创建C++文件
touch velocity_publisher.cpp
(2)编写.cpp文件内容
//发布turtle1/cmd_vel话题,消息类型为geometry_msgs::Twist
#include
#include
int main(int argc,char **argv)//argc和argv都是输入参数
{
//初始化节点
ros::init(argc,argv,"velocity_publisher");
//创建句柄-管理节点资源
ros::NodeHandle n;
//创建一个Publisher,发布名为/turtle1/cmd_vel的tpoic,消息类型是geometry_msgs::Twist,队列长度为10
ros::Publisher turtle_vel_pub = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel",10);
//循环频率
ros::Rate loop_rate(10);
int count =0;
//roscpp会默认安装以SIGINT句柄,这句话就是用来处理由ctrl+c键盘操作、该节点被另一同名节点踢出ROS网络、ros::shutdown()被程序在某个地方调用、所有ros::NodeHandle句柄都被销毁等触发而使ros::ok()返回false值的情况
while (ros::ok())
{
//初始化消息
geometry_msgs::Twist vel_msg;
vel_msg.linear.x=2.0;
vel_msg.angular.z=1.0;
//发布消息
turtle_vel_pub.publish(vel_msg);
ROS_INFO("Publish turtle velocity command[%0.2f m/s,%0.2f rad/s]",vel_msg.linear.x,vel_msg.angular.z);
//设置循环频率
loop_rate.sleep();
}
return 0;
}
(3)配置CMakeLists.txt编译规则
add_executable(velocity_publisher src/velocity_publisher.cpp)#将程序文件生成可执行文件
target_link_libraries(velocity_publisher ${
catkin_LIBRARIES})#将可执行文件与ros库链接
添加上述代码到文件对应位置:
(4)进入catkin_ws进行可执行文件velocity_publisher的编译,运行
cd ~/catkin_ws
catkin_make#编译
注意:需要在.bashrc文件中配置环境变量:source ~/catkin_ws/devel/setup.bash
echo "source ~/catkin_ws/devel/setup.bash" >> ~/.bashrc
(5) 程序测试
roscore
rosrun turtlesim turtlesim_node
rosrun learning_topic velocity_publisher
(1) 创建.py文件
touch velocity_publisher.py
(2)编写.py文件内容
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 该例程将发布turtle1/cmd_vel话题,消息类型geometry_msgs::Twist
import rospy
from geometry_msgs.msg import Twist
def velocity_publisher():
# ROS节点初始化
rospy.init_node('velocity_publisher', anonymous=True)
# 创建一个Publisher,发布名为/turtle1/cmd_vel的topic,消息类型为geometry_msgs::Twist,队列长度10
turtle_vel_pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
#设置循环的频率
rate = rospy.Rate(10)
while not rospy.is_shutdown():
# 初始化geometry_msgs::Twist类型的消息
vel_msg = Twist()
vel_msg.linear.x = 0.5
vel_msg.angular.z = 0.2
# 发布消息
turtle_vel_pub.publish(vel_msg)
rospy.loginfo("Publsh turtle velocity command[%0.2f m/s, %0.2f rad/s]",
vel_msg.linear.x, vel_msg.angular.z)
# 按照循环频率延时
rate.sleep()
if __name__ == '__main__':
try:
velocity_publisher()
except rospy.ROSInterruptException:
pass
pytion开头注释参考
(3) 给文件授权
PS:在ros下运行python文件一定要注意待执行的python文件有可执行权限。对着python文件右键→属性(Properties)→权限(Permissions)→Allow executing file as program打钩。
或者通过命令行修改:(进入learining_topic/src/文件夹中)
chmod +x velocity_publisher.py
(4) 程序运行
roscore
rosrun turtlesim turtlesim_node
rosrun learning_topic velocity_publisher.py
刚看到一篇关于ros:Publisher和Subscriber讲得特别好的博文,推荐给大家:ROS: Publisher and Subscriber,记录一下,继续学习!
本讲完,接下来会持续更新!