1. 程式人生 > >ROS-python實現簡單的訊息釋出器和訂閱器

ROS-python實現簡單的訊息釋出器和訂閱器

因為著急做出東西來糊弄人,所以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
m

kdirscripts 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五花八門的庫真是新年吧多啊!!