【发布时间】:2021-12-16 15:22:13
【问题描述】:
我正在从串行端口读取数据(传感器数据,y),并想绘制它与时间 (x) 的关系图。我使用系统时间来计算经过的时间。传感器的读数没有滞后。但是我绘制它的方式引入了几秒钟的延迟,因此它远远落后于传感器的实际状态(因此不能作为实时数据接受)。请帮助我学习如何在此处更好地绘制 x,y 数据。提前非常感谢!
import serial
import time
import matplotlib.pyplot as plt
start = time.time()
x = []
y = []
ser = serial.Serial('COM6', 2000000, timeout=0)
time.sleep(2)
fig = plt.figure()
plt.ion() # turn on interactive mode
fig.canvas.draw()
plt.show(block=False)
while True:
line = ser.readline() # read a byte
if line:
string = line.decode() # convert the byte string to a unicode string
#num = re.findall(r"[-+]?\d*\.\d+|\d+", string)
num = float(string)
end = time.time()
y.append(num)
time_elapsed= end - start
x.append(time_elapsed)
plt.cla()
plt.plot(x, y, 'red')
plt.pause(0.05)
plt.draw()
【问题讨论】:
-
不要每次都清轴。将数据附加到艺术家matplotlib.org/stable/gallery/animation/…
-
感谢您的回复。这里的延迟不是来自读取功能,因为我可以在没有明显延迟的情况下高频打印 x 和 y。阴谋是罪魁祸首。我使用了 PyQtGraph,现在绘图速度要快得多,而且我注意到的几乎没有任何滞后。再次感谢!
标签: python matplotlib graph serial-port real-time