「ros自學」07.02 rospy例程——topic例程

透過編寫topic和service兩種通訊方式來熟悉之前介紹的rospy提供給python的API。

與cpp例程類似,實現如下功能以及編寫步驟如下

「ros自學」07.02 rospy例程——topic例程

之前cpp實現方案裡提到catkin_make編譯後會形成。h標頭檔案,這裡同時也會在如下目錄形成。py檔案的python模組。。msg是自定義的通訊格式,是與程式語言無關的通訊協議。

「ros自學」07.02 rospy例程——topic例程

接下來就可以編寫python程式碼。python編寫ros程式需要import rospy。

「ros自學」07.02 rospy例程——topic例程

import rospyimport mathfrom topic_demo。msg import gps#匯入mgs到pkg中,就可以利用gps這個型別#回撥函式輸入的應該是msgdef callback(gps): distance = math。sqrt(math。pow(gps。x, 2)+math。pow(gps。y, 2)) rospy。loginfo(‘Listener: GPS: distance=%f, state=%s’, distance, gps。state)def listener(): rospy。init_node(‘pylistener’, anonymous=True) #Subscriber函式第一個引數是topic的名稱,第二個引數是接受的資料型別 第三個引數是回撥函式的名稱 rospy。Subscriber(‘gps_info’, gps, callback) rospy。spin()if __name__ == ‘__main__’: listener()

「ros自學」07.02 rospy例程——topic例程

import rospy#倒入自定義的資料型別from topic_demo。msg import gpsdef talker(): #Publisher 函式第一個引數是話題名稱,第二個引數 資料型別,現在就是我們定義的msg 最後一個是緩衝區的大小 #queue_size: None(不建議) #這將設定為阻塞式同步收發模式! #queue_size: 0(不建議)#這將設定為無限緩衝區模式,很危險! #queue_size: 10 or more #一般情況下,設為10 。queue_size太大了會導致資料延遲不同步。 pub = rospy。Publisher(‘gps_info’, gps , queue_size=10) rospy。init_node(‘pytalker’, anonymous=True) #更新頻率是1hz rate = rospy。Rate(1) x=1。0 y=2。0 state=‘working’ while not rospy。is_shutdown(): #計算距離 rospy。loginfo(‘Talker: GPS: x=%f ,y= %f’,x,y) pub。publish(gps(state,x,y)) x=1。03*x y=1。01*y rate。sleep()if __name__ == ‘__main__’: talker()

相較於cpp,py編寫更為簡單直觀,但是cpp執行效率更高。到這裡就完成所有工作了,因為python不需要cmake編譯,python本身就是解釋性語言可以直接執行。

但是from topic_demo。msg import gps這個型別需要cmake編譯。

「ros自學」07.02 rospy例程——topic例程

「ros自學」07.02 rospy例程——topic例程

參考資料

https://www。icourse163。org/learn/ISCAS-1002580008?tid=1002759011#/learn/content?type=detail&id=1004060980&cid=1004997770&replay=true

https://github。com/DroidAITech/ROS-Academy-for-Beginners/tree/master/topic_demo