使用matplotlib实时绘制arduino数据时不显示图形图

时间:2015-12-29 22:15:58

标签: python matplotlib arduino

我试图用matplotlib绘制Arduino UNO模拟输入的实时演讲。 我的问题:图表不会显示。只有当我停止运行代码(Ctrl + C)时,它才会显示最后一个值的图形。

在代码中添加“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

1 个答案:

答案 0 :(得分: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()