http://wiki.ros/ROS/Tutorials/WritingPublisherSubscriber%28python%29
1.创建工作空间和程序包
roscd beginner_tutorials
2.创建scripts文件夹
mkdir scripts
cd scripts
3.Publisher Node
wget https://raw.github/ros/ros_tutorials/kinetic-devel/rospy_tutorials/001_talker_listener/talker.py
chmod +x talker.py
代码内容如下:
1 #!/usr/bin/env python
2 # license removed for brevity
3 import rospy
4 from std_msgs.msg import String
5
6 def talker():
7 pub = rospy.Publisher('chatter', String, queue_size=10)
8 rospy.init_node('talker', anonymous=True)
9 rate = rospy.Rate(10) # 10hz
10 while not rospy.is_shutdown():
11 hello_str = "hello world %s" % rospy.get_time()
12 rospy.loginfo(hello_str)
13 pub.publish(hello_str)
14 rate.sleep()
15
16 if __name__ == '__main__':
17 try:
18 talker()
19 except rospy.ROSInterruptException:
20 pass
4.Subscriber Node
roscd beginner_tutorials/scripts/
wget https://raw.github/ros/ros_tutorials/kinetic-devel/rospy_tutorials/001_talker_listener/listener.py
chmod +x listener.py #make the node executable
代码内容如下:
1 #!/usr/bin/env python
2 import rospy
3 from std_msgs.msg import String
4
5 def callback(data):
6 rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
7
8 def listener():
9
10 # In ROS, nodes are uniquely named. If two nodes with the same
11 # node are launched, the previous one is kicked off. The
12 # anonymous=True flag means that rospy will choose a unique
13 # name for our 'listener' node so that multiple listeners can
14 # run simultaneously.
15 rospy.init_node('listener', anonymous=True)
16
17 rospy.Subscriber("chatter", String, callback)
18
19 # spin() simply keeps python from exiting until this node is stopped
20 rospy.spin()
21
22 if __name__ == '__main__':
23 listener()
5.编译
cd ~/catkin_ws
$ catkin_make
5.运行
roscore 不然会出现错误: [ERROR] [WallTime: 1471865459.868853] Unable to immediately register with master node [http://localhost:11311]: master may not be running yet. Will keep trying.cd ~/catkin_ws source ./devel/setup.bash
rosrun beginner_tutorials talker.py
rosrun beginner_tutorials listener.py
更多推荐
ros_Python_Writing a Simple Publisher and Subscriber
发布评论