創建流程.png
Python編碼不需要修改makefile文件,腳本語言,直接執行。
代碼解釋
- 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
- 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()