【发布时间】:2014-09-10 09:03:14
【问题描述】:
我正在尝试使用 arduino 和 pyserial、numpy 和 matplotlib 绘制加速度计的串行数据。问题是每当 GUI 打开时,传入的数据速率变得非常慢并且绘图也非常慢,如果我不打开 GUI 并简单地在命令窗口上打印数据,则接收到的数据很快。请帮忙!!
这是我的python代码:
import serial
import matplotlib.pyplot as plt
import numpy as np
import time
ser = serial.Serial('COM3', 9600, timeout=0) #sets up serial connection (make sure baud rate is correct - matches Arduino)
ser.flushInput()
ser.flushOutput()
plt.ion() #sets plot to animation mode
length = 500 #determines length of data taking session (in data points)
x = [0]*length #create empty variable of length of test
y = 0
z = 0
fig, ax = plt.subplots()
line, = ax.plot(np.random.randn(100))
plt.show(block=False)
xline, = plt.plot(x) #sets up future lines to be modified
plt.ylim(30,120) #sets the y axis limits
#for i in range(length): #while you are taking data
tstart = time.time()
n = 0
while time.time()-tstart < 5:
y = (ser.readline().decode('utf-8')[:-2])
if not (len(y)==0):
z = float(y)
x.append(float(z)) #add new value as int to current list
del x[0]
xline.set_xdata(np.arange(len(x))) #sets xdata to new list length
xline.set_ydata(x) #sets ydata to new list
# ax.draw_artist(ax.patch)
# ax.draw_artist(line)
# fig.canvas.update()
fig.canvas.draw()
fig.canvas.flush_events()
#plt.pause(0.0001) #in seconds #draws new plot
#plt.show()
n +=1
print (z)
print(n)
ser.close() #closes serial connection (very important to do this! if you have an error partway through the code, type this into the cmd line to close the connection)
【问题讨论】:
-
希望能帮您解答这个问题。我自己有 Arduino(s) 并且玩过(还没有 Python)。我无法确定减速/延迟的特定原因。您是否尝试过分析代码?
标签: python numpy matplotlib arduino pyserial