【问题标题】:Graph figure not displayed when live plotting arduino data with matplotlib使用 matplotlib 实时绘制 arduino 数据时不显示图形
【发布时间】:2016-04-03 20:43:14
【问题描述】:

我正在尝试使用 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

【问题讨论】:

标签: python matplotlib arduino


【解决方案1】:

这是一个使用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()

【讨论】:

  • 非常感谢!这几乎可以正常工作:初始行保留在显示屏中,而来自 arduino 的值在其他不同行中正确显示和更新。我该如何纠正这个问题?
  • 我还修改了以下代码 (github.com/eliben/code-for-blog/blob/master/2008/…),它工作正常,虽然不是那么简单,您需要安装 wxPython 模块。不过有更多的功能。
  • 这很容易解决:将初始化设置为pData = [None] * n
猜你喜欢
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
  • 2015-06-20
  • 2020-07-16
  • 2011-04-21
  • 2020-09-17
  • 2018-12-03
  • 2012-10-22
相关资源
最近更新 更多