2015-12-29 153 views
2

我想從Arduino UNO的matplotlib模擬輸入中繪製實時講座。 我的問題:該圖不會顯示。只有當我停止運行代碼(Ctrl + C)時,它纔會顯示最後一個值的圖形。使用matplotlib實時繪製arduino數據時不顯示圖形圖

將「print pData」行添加到代碼以檢查值是否正確到達計算機時,它們在python終端上正確顯示(每秒顯示25個值數組)。

#!/usr/bin/python 

from matplotlib import pyplot 
import pyfirmata 
from time import sleep 

# Associate port and board with pyFirmata 
port = '/dev/ttyACM0' 
board = pyfirmata.Arduino(port) 

# Using iterator thread to avoid buffer overflow 
it = pyfirmata.util.Iterator(board) 
it.start() 

# Assign a role and variable to analog pin 0 
a0 = board.get_pin('a:0:i') 

pyplot.ion() 

pData = [0.0] * 25 
fig = pyplot.figure() 
pyplot.title('Real-time Potentiometer reading') 
ax1 = pyplot.axes() 
l1, = pyplot.plot(pData) 
pyplot.ylim([0, 1]) 

while True: 
    try: 
     sleep(1) 
     pData.append(float(a0.read())) 
     pyplot.ylim([0, 1]) 
     del pData[0] 
     l1.set_xdata([i for i in xrange(25)]) 
     l1.set_ydata(pData) # update the data 
     #print pData 
     pyplot.draw() # update the plot 
    except KeyboardInterrupt: 
     board.exit() 
     break 
+0

的可能的複製[交互式經由命令行與Python繪製](http://stackoverflow.com/questions/15991968/interactive-plotting-with-python-via-command-line) – tyleha

+0

@tyleha你不'不需要show()'如果你使用'draw()' – Jason

+0

@Jason @tyleha Jason是對的。使用'show()'不能解決問題。 – Paco

回答

0

這是一個使用matplotlib.animation進行實時繪圖的模型。

from matplotlib import pyplot 
import matplotlib.animation as animation 
import random 

# Generate sample data 
class Pin: 
    def read(self): 
     return random.random() 
a0 = Pin() 

n = 25 
pData = [None] * n 

fig, ax = pyplot.subplots() 
pyplot.title('Real-time Potentiometer reading') 
l1, = ax.plot(pData) 
# Display past sampling times as negative, with 0 meaning "now" 
l1.set_xdata(range(-n + 1, 1)) 
ax.set(ylim=(0, 1), xlim=(-n + 1, 0)) 

def update(data): 
    del pData[0] 
    pData.append(float(a0.read())) 
    l1.set_ydata(pData) # update the data 
    return l1, 

ani = animation.FuncAnimation(fig, update, interval=1000, blit=True) 

try: 
    pyplot.show() 
finally: 
    pass 
    #board.exit() 
+0

非常感謝!這幾乎可以正常工作:初始行保留在顯示屏中,而arduino的值在其他不同的行中正確顯示和更新。我怎麼能糾正這個? – Paco

+0

我也修改了下面的代碼(https://github.com/eliben/code-for-blog/blob/master/2008/wx_mpl_dynamic_graph.py),它工作正常,雖然不是那麼簡單,你需要安裝wxPython模塊。雖然有更多的功能。 – Paco

+0

這很簡單:將初始化設置爲'pData = [None] * n'。 –

相關問題