使用 MatplotlibAnimation 进行 Arduino 实时串行绘图变慢 [英] Arduino Live Serial Plotting with a MatplotlibAnimation gets slow

查看:48
本文介绍了使用 MatplotlibAnimation 进行 Arduino 实时串行绘图变慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个实时绘图仪来显示来自 Arduino 传感器的模拟变化.Arduino 以 9600 的波特率向串口打印一个值.Python 代码如下所示:

I am making a live plotter to show the analog changes from an Arduino Sensor. The Arduino prints a value to the serial with a Baudrate of 9600. The Python code looks as following:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import serial
import time

ser = serial.Serial("com3", 9600)
ser.readline()

optimal_frequency = 100

fig = plt.figure(figsize=(6, 6))
ax1 = fig.add_subplot(1, 1, 1)

# the following arrays must be initialized outside the loop

xar = []
yar = []

print(time.ctime())

def animate(i):
    global b, xar, yar # otherwise a

    for i in range(optimal_frequency):

        a = str(ser.readline(), 'utf-8')
        try:
            b = float(a)
        except ValueError:
            ser.readline()
        xar.append(str(time.time()))
        yar.append(b)
    ax1.clear()
    ax1.plot(xar, yar)

ani = animation.FuncAnimation(fig, animate, interval=optimal_frequency)
plt.show()

A 在绘图中获得了不错的响应时间,但是当我绘图超过 20 分钟时,反应时间增加到大约 1 分钟.IE.图形需要 1 分钟才能使用新值进行更新.我也尝试过 PyQtGraph,但从一开始就延迟了.

A get an ok response time in the plot, but when I have been plotting over 20 minutes the reaction times increase to about 1 min. I.e. it takes 1 min forthe graph to get updated with the new values. I have also tried with PyQtGraph but that is delayed from a start.

除了超过 20 分钟的延迟之外,我在情节中遇到了一些过冲和欠冲.

Besides the delay for times over 20 minutes, I am getting some overshoots and undershoots in the plot.

有什么帮助吗?

推荐答案

正如评论中提到的,你做错了两件事:

as mentioned in the comments, you are doing two things wrong:

  • 您不断将传入的数据附加到您的数组中,一段时间后这些数据会变得很大
  • 您清除坐标区并在每次迭代时创建一个新的 ax.plot().

你想做的是:

在初始化函数中,创建一个空的 Line2D 对象

in an initialization function, create an empty Line2D object

def init():
    line, = ax.plot([], [], lw=2)
    return line,

然后在更新函数 (animate()) 中,使用 line.set_data() 更新点的坐标.但是,为了保持性能,您必须将数组的大小保持在合理的大小,因此您将不得不在新数据进入时删除旧数据

then in your update function (animate()), you use line.set_data() to update the coordinates of your points. However, to maintain performance, you have to keep the size of your arrays to a reasonable size, and so you will have to drop the older data as newer data comes in

def animate(i):
    (...)
    xar.append(str(time.time()))
    yar.append(b)
    line.set_data(xar, yar)
    return line,

查看一些教程喜欢这个.还有很多关于 SO 的问题已经回答了您的问题.例如,这个答案包含让代码正常工作所需的所有元素.

Check out some tutorials like this one. There are also plenty of questions on SO that already answers your question. For instance, this answer contains all the elements you need to get your code working.

这篇关于使用 MatplotlibAnimation 进行 Arduino 实时串行绘图变慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆