【发布时间】:2020-02-21 11:57:03
【问题描述】:
我正在使用 SPI 从 IMU LSM9DS1 读取数据。我想将数据存储到文件中。我尝试使用with open as file 和.write 保存为txt 文件。速度为0.002s。
while flag:
file_path_g = '/home/pi/Desktop/LSM9DS1/gyro.txt'
with open(file_path_g, 'a') as out_file_g:
dps = dev.get_gyro()
out_file_g.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
out_file_g.write(" {0:0.3f}, {1:0.3f}, {2:0.3f}\n".format(dps[0], dps[1], dps[2]))
file_path_a = '/home/pi/Desktop/LSM9DS1/accel.txt'
with open(file_path_a, 'a') as out_file_a:
acc = dev.get_acc()
out_file_a.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
out_file_g.write(" {0:0.3f}, {1:0.3f}, {2:0.3f}\n".format(acc[0], acc[1], acc[2]))
# time.sleep(0.2)
print("interrupt occured")
dev.close()
我还尝试使用 pandas 将数据保存为 .csv 文件。速度比第一个慢。
while flag:
t = time.time()
acc = dev.get_acc()
dps = dev.get_gyro()
ax = acc[0]
ay = acc[1]
az = acc[2]
gx = dps[0]
gy = dps[1]
gz = dps[2]
result = pd.DataFrame({'time':t, 'ax':ax,'ay':ay,'az':az,'gx':gx,'gy':gy,'gz':gz},index=[0])
result.to_csv('/home/pi/Desktop/LSM9DS1/result.csv', mode='a', float_format='%.6f',
header=False, index=0)
dev.close()
如何提高阅读速度?
我更新了路径之外的代码。
file_path = '/home/pi/Desktop/LSM9DS1/result.txt'
while flag:
with open(file_path, 'a') as out_file:
acc = dev.get_acc()
dps = dev.get_gyro()
out_file.write(datetime.datetime.now().strftime('%S.%f'))
out_file.write(" {0:0.3f}, {1:0.3f}, {2:0.3f}".format(acc[0], acc[1], acc[2]))
out_file.write(" {0:0.3f}, {1:0.3f}, {2:0.3f}\n".format(dps[0], dps[1], dps[2]))
这是另一种方式
while flag:
t = time.time()
acc = dev.get_acc()
dps = dev.get_gyro()
arr = [t, acc[0], acc[1], acc[2], dps[0], dps[1],dps[2]],
np_data = np.array(arr)
result = pd.DataFrame(np_data,index=[0])
result.to_csv('/home/pi/Desktop/LSM9DS1/result.csv', mode='a', float_format='%.6f', header=False, index=0)
感谢马克的回答。我照他说的做了,改代码如下。
samples=[]
for i in range(100000):
t = time.time()
acc = dev.get_acc()
dps = dev.get_gyro()
# Append a tuple (containing time, acc and dps) onto sample list
samples.append((t, acc, dps))
name = ['t','acc','dps']
f = pd.DataFrame(columns=name,data=samples)
f.to_csv('/home/pi/Desktop/LSM9DS1/result.csv', mode='a', float_format='%.6f', header=False, index=0)
print('done')
我计算了时间空间(前600个数据),平均值为0.000265,比以前快了很多,几乎是以前的10倍。
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
-
我的回答解决了您的问题吗?如果是这样,请考虑接受它作为您的答案 - 通过单击计票旁边的空心对勾/复选标记。如果没有,请说出什么不起作用,以便我或其他人可以进一步为您提供帮助。谢谢。 meta.stackexchange.com/questions/5234/…
标签: python raspberry-pi