我正在尝试编写一个可以完成一些不同事情的脚本:
1)从传感器数据不断填充的文本文件中读取数据。
2)过滤此数据。
3)绘制未过滤的数据。
目前,我的脚本适用于1)和2),但我无法让情节发挥作用。我认为传感器的采样率非常高,为5376 Hz,这很复杂。
目前,我的脚本每隔0.1毫秒轮询一次文本文件,看看是否用这段代码将新行写入文档:
# Function that continually looks at thefile.
def follow(thefile):
thefile.seek(0,2) # Look at the last line in the file
while True:
line = thefile.readline() # line is now equal to the last line in thefile
if not line: # If the last line in the file was empty, this will be true,
time.sleep(0.0001) # and the function will sleep for 0.1 ms before continuing
continue
yield line # If the last line was not empty, it will be yielded
然后我有我的主脚本分析数据:
import time
from scipy.signal import butter, filtfilt
import matplotlib.pyplot as plt
import numpy as np
import os
import pylab as pl
# Opening text file in subdirectory
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "python_data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
# Vectors for storing unfiltered data in
xar = []
yar = []
zar = []
pl.ion() # Interaction on
x = np.arange(0,10) # x-array
pl.line, = plt.plot(x,np.sin(x)) # Initiate line
logfile = open(abs_file_path,"r") # Open text file
loglines = follow(logfile) # Look for changes in text file
for line in loglines: # For each new line in text file
try:
x,y,z = line.split(' \t ') # Split up x-, y- and z- data into different arrays.
xar.append(int(x))
yar.append(int(y))
zar.append(int(z))
line.set_ydata(int(x)) # Update the line
pl.draw() # Redraw the canvas
except:
pass
# I then perform the filtering of xar, yar and zar when they have reached a certain length, and reset them after filtering is done with xar = [], yar = [], zar = [].
绘制我实施的数据的方法是这里指定的方法:https://scipy-cookbook.readthedocs.io/items/Matplotlib_Animations.html
然而,它不起作用,一旦我执行我的脚本创建了一个数字,但是它被完全冻结,当我开始在文本文件中收集数据时没有任何反应。所以我有几个问题:
1)我是否正确实施了该方法?
2)我经常调用line.set_ydata(int(x))和pl.draw(),这就是它崩溃的原因吗?
3)当我用pl.line,= plt.plot(x,np.sin(x))创建一行时,我真的不明白发生了什么,然后用line更新y元素。 set_ydata(INT(X))。我在pl.line,= plt.plot(x,np.sin(x))的y位置写的是否重要?
4)如果我想以5376 Hz的频率更新我的情节,我应该使用完全不同的方法吗?