【ROS】rospy 发布器和订阅器(Publisher and Subscriber)

rospy L1: Publisher and Subscriber

参考(http://wiki.ros.org/rospy_tutorials/Tutorials/WritingPublisherSubscriber)

1 准备开发环境

1.1 创建功能包beginner_tutorials

catkin_create_pkg beginner_tutorials std_msgs rospy roscpp

如果没有工作空间需要创建catkin workspace 参考(http://wiki.ros.org/ROS/Tutorials/CreatingPackage)

1.2 创建脚本文件夹

在包文件夹beginner_tutorials下创建脚本文件夹

$ mkdir scripts
$ cd scripts

注意: scripts下的文件需要可执行权限chmod +x file

2 talker节点

文件:talker.py

#!/usr/bin/env python
import rospy
from std_msgs.msg import String
	
def talker():
    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        hello_str = "hello world %s" % rospy.get_time()
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
        rate.sleep()

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass

3 listener节点

文件:listener.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():

    # In ROS, nodes are uniquely named. If two nodes with the same
    # node are launched, the previous one is kicked off. The
    # anonymous=True flag means that rospy will choose a unique
    # name for our 'listener' node so that multiple listeners can
    # run simultaneously.
    rospy.init_node('listener', anonymous=True)

    rospy.Subscriber("chatter", String, callback)

    # spin() simply keeps python from exiting until this node is stopped
    rospy.spin()

if __name__ == '__main__':
    listener()

4 编译

$ cd ~/catkin_ws
$ catkin_make

5 运行

$ roscore
$ rosrun beginner_tutorials talker.py
$ rosrun beginner_tutorials listener.py

猜你喜欢

转载自blog.csdn.net/JasonZhu_csdn/article/details/84198134