我想繪製使用arduino和pyserial,numpy和matplotlib的加速度計的串行數據。問題是每當GUI打開時,傳入數據速率變得非常慢,並且圖也非常慢,如果我沒有打開GUI並只是在命令窗口上打印數據,則接收到的數據很快。 Plz幫忙!使用arduino和pyserial繪製串行數據
這裏是我的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(*不用Python)*。我無法確定減速/延遲的特定原因。你有沒有試過分析代碼? –