python創建一個ros節點

創建流程.png

Python編碼不需要修改makefile文件,腳本語言,直接執行。
代碼解釋

  1. talker.py
#!/usr/bin/env python  #調用的是python2.7編譯器

import rospy 
from std_msgs.msg import String  

def talker():
    pub = rospy.Publisher('chatter', String, queue_size=10)
      #Publisher函數創建發布節點(topic名‘chatter’,消息類型String,queue_size發布消息緩沖區大小都是未被接收走的)
    
    rospy.init_node('talker', anonymous=True)
      #啟動節點talker,同時為節點命名,若anoymous為真則節點會自動補充名字,實際名字以talker_322345等表示,
      #若為假,則系統不會補充名字,采用用戶命名。如果有重名,則最新啟動的節點會注銷掉之前的同名節點
    
    rate = rospy.Rate(10) # 10hz
      #延時的時間變量賦值,通過rate.sleep()實現延時
    
    while not rospy.is_shutdown():
           # 判定開始方式,循環發送,以服務程序跳出為終止點 一般ctrl+c也可
        
        hello_str = "hello world %s" % rospy.get_time()
          # 數據變量的內容 rospy.get_time() 是指ros系統時間,精確到0.01s 
        
        rospy.loginfo(hello_str)
          #在運行的terminal界面info 出信息,可不加,可隨意改
        
        pub.publish(hello_str)
          #發布數據 必須發布
        
        rate.sleep()
          # 按rospy.Rate()設置的速率延遲 

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass

  1. listener.py
#!/usr/bin/env python

import rospy
from std_msgs.msg import String

def callback(data):
    rospy.loginfo(rospy.get_caller_id() + 'I heard %s', data.data)
      #回調函數 收到的參數.data是通信的數據 默認通過這樣的 def callback(data) 取出data.data數據

def listener():

    # In ROS, nodes are uniquely named. If two nodes with the same
    # name are launched, the previous one is kicked off. The
    # anonymous=True flag means that rospy will choose a unique
    # name for our 'listener' node so that multiple listeners can
    # run simultaneously.
    rospy.init_node('listener', anonymous=True)
      #啟動節點并同時為節點命名 

    rospy.Subscriber('chatter', String, callback)
     #啟動訂閱,訂閱主題‘chatter’,及標準字符串格式,同時調用回調函數,當有數據時調用函數,取出數據

    # spin() simply keeps python from exiting until this node is stopped
    rospy.spin()

if __name__ == '__main__':
    listener()

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容