ros_Python_Writing a Simple Publisher and Subscriber

编程入门 行业动态 更新时间:2024-10-07 04:33:23

ros_Python_Writing a <a href=https://www.elefans.com/category/jswz/34/1769188.html style=Simple Publisher and Subscriber"/>

ros_Python_Writing a Simple Publisher and Subscriber

/ROS/Tutorials/WritingPublisherSubscriber%28python%29

1.创建工作空间和程序包

roscd beginner_tutorials

2.创建scripts文件夹

mkdir scripts
cd scripts
3.Publisher Node
wget /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 /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

本文发布于:2023-08-03 05:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1284899.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Simple   ros_Python_Writing   Subscriber   Publisher

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!