2015-12-29 113 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'。 –

相关问题