ROS学习笔记——简单的消息发布器和订阅器 (Python版)

写一个简单的消息发布器和订阅器 (Python)

1.创建ROS功能包

切换到src文件夹下

cd ~/catkin_ws/src    

在src文件夹下创建一个名为hello_world的包

cakin_create_pkg hello_world std_msgs rospy

在hello_world包被成功创建之后,需要添加两个Python文件或脚本,用于演示主题的订阅和发布。
首先,在hello_world文件夹下创建一个名为scripts的文件夹:

mkdir scripts

切换到scripts文件夹下,并创建两个Python文件:

  • hello_world_publisher.py
  • hello_world_subscriber.py

2.发布者节点(hello_world_publisher.py)

该节点主要发布一个欢迎消息hello world到主题hello_pub

#!/usr/bin/env python 
#Every Python ROS Node will have this declaration at the top. The first line makes sure your script is executed as a Python script.
import rospy   #导入rospy包
from std_msgs.msg import String   #需要从std_msgs包导入一个String类型
def talker():
    pub = rospy.Publisher('hello_pub',String,queue_size=10)   #创建一个对象发布到主题hello_pub上去
    rospy.init_node('hello_world_publisher',anonymous=True)   
#init_node(NAME, ...), is very important as it tells rospy the name of your node -- until rospy #has this information, it cannot start communicating with the ROS Master. In this case, your #node will take on the name talker. NOTE: the name must be a base name, i.e. it cannot contain #any slashes "/".
#anonymous = True ensures that your node has a unique name by adding random numbers to the end #of NAME. Refer to Initialization and Shutdown - Initializing your ROS Node in the rospy #documentation for more information about node initialization options.
    r = rospy.Rate(10)    #设定速率为10
    while not rospy.is_shutdown():      #在Ctrl+C时,退出循环
        str = "hello world %s"%rospy.get_time()   
        rospy.loginfo(str)
        pub.publish(str)
        r.sleep()
if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:pass

3.订阅者节点(hello_world_subscriber.py)

#!/usr/bin/env python
import rospy
from std_msgs.msg import String
def callback(data):
    rospy.loginfo(rospy.get_caller_id()+"I heard %s",data.data)
def listener():
    rospy.init_node('hello_world_subscriber',anonymous=True)
    rospy.Subscriber("hello_pub",String,callback)
    rospy.spin()
if __name__=='__main__':
    listener()

在保存了两个Python节点之后,需要使用chmod命令更改权限:

chmod +x hello_world_publisher.py
chmod +x hello_world_subscriber.py

4.编译节点

使用catkin_make工具来编译节点

cd ~/catkin_ws
catkin_make

也可以单独短衣hello_world包

cd ~/catkin_ws
catkin_make --pkg hello_world

5.运行节点

首先,启动ros

roscore

运行发布者节点:

rosrun hello_world hello_world_publisher.py

运行订阅者节点:

rosrun hello_world hello_world_subscriber.py

运行效果如下图所示:
ROS学习笔记——简单的消息发布器和订阅器 (Python版)_第1张图片

你可能感兴趣的:(ROS学习笔记)