ROS中订阅话题获取传感器数据时 如果用Subscriber(topic, topic_type, callback, queue_size = 1)加回调函数来记录数据的话,需要rospy.spin(),而添加了rospy.spin()程序就无法继续执行了,一直在这循环。一种解决方法是使用多线程,一个线程跑rospy.spin()一个线程跑剩余代码。
参考:
https://blog.csdn.net/qq_30193419/article/details/100776075
https://blog.csdn.net/qq_16583687/article/details/55263148
import rospy
import std_msgs.msg
import geometry_msgs.msg
from sensor_msgs.msg import LaserScan
import threading
def thread_job():
rospy.spin()
laser = []
def save_laser(laser_data):
global laser
laser = laser_data.ranges
def listener():
global laser
rospy.init_node('save_image')
add_thread = threading.Thread(target = thread_job)
add_thread.start()
rospy.Subscriber('/scan', LaserScan, save_laser, queue_size=1)
rospy.sleep(1)
while(1):
print(laser)
if __name__ == '__main__':
listener()
使用rospy.wait_for_message(topic, topic_type, timeout)
不需要rospy.spin() ,可以直接获取话题的数据 , 注意要先定义节点
import rospy
from sensor_msgs.msg import LaserScan
def listener():
rospy.init_node('get_laser')
rospy.sleep(2)
data = rospy.wait_for_message("/scan", LaserScan, timeout=None)
print(data.ranges)
if __name__ == '__main__':
listener()