ROS-python实现简单的消息发布器和订阅器

来源:互联网 发布:php经常用的代码 编辑:程序博客网 时间:2024/05/16 04:51

因为着急做出东西来糊弄人,所以ROS的wiki看得马马虎虎一目十行,今天有些时间,仔细读了一下tutorials,对ROS有了一种恍然大明白的感觉,记录一下,方便以后操作,懒得再翻手册了:
1,首先要建一个工作空间,这个先不表了
2,其次要创建一个package,一个完整的程序包是这样的my_package/
CMakeLists.txt
package.xml
。这个程序包的路径注意下,在cd ~/dashgo_ws/src中创建。自不自定义你的程序包就看要求了,理解成描述文件就行。
3,编译程序包,首先source一下,source /opt/ros/groovy/setup.bash。在cd ~/catkin_ws/下执行catkin_make来编译一下。
4,用python写消息发布器
打开文件包:roscd beginner_tutorials
创建scripts
mkdirscripts cd scripts
编写talker.py
chmod +x talker.py
编写listener.py
chmod +x listener.py //赋予程序可执行权限
5,执行发布器和订阅器
打开发布器
首先
roscore
然后
cd /catkinws source ./devel/setup.bash
最后
rosrun beginner_tutorials talker.py

打开订阅器
cd /catkinws source ./devel/setup.bash
最后
rosrun beginner_tutorials listener.py


看一下代码吧
listener.py

  1 #!/usr/bin/env python   2 import rospy   3 from std_msgs.msg import String   4 #回调格式 'listener_id heard hello world'    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()

没啥东西,就四个rospy库里面的函数(待补充)
rospy.loginfo
rospy.init_node
rospy.Subscriber
rospy.spin()

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

还是很easy,talker里面还加了个异常,真是严谨。总结完啦,下一篇谢谢ROspy吧。再次感慨一句,python五花八门的库真是新年吧多啊!!

0 0
原创粉丝点击