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

3 篇文章 0 订阅

因为着急做出东西来糊弄人,所以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五花八门的库真是新年吧多啊!!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值