首页 > 解决方案 > Python:FuncAnimation 在“while True”循环中不起作用

问题描述

我有一个与加速度计连接的 Raspberry Pi。在 Python 中,我想绘制 X 轴值的动画图。这是一个实时图表,显示了当我移动我手中的 Pi 时 X 轴值的变化。然而,该图仅显示初始值。

from mpu6050 import mpu6050
from time import sleep
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style

style.use("fivethirtyeight")

sensor = mpu6050(0x68)
print " waiting for the sensor to callibrate..."

sleep(2)

acc = np.empty((0,3), float) # storage for x, y, z axes values of the accelerometer
t = 0
time = np.empty((0,1), int) # time counter(this becomes the x axis of the graph)

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

axis = 0 # accelerometer x axis. y axis = 1, z axis = 2

def animate(i):
    ax1.clear()
    ax1.plot(time, acc[:,axis])

while True:
    accel_data = sensor.get_accel_data()
    print("Accelerometer data")
    print("x: " + str(accel_data['x']))
    print("y: " + str(accel_data['y']))
    print("z: " + str(accel_data['z']))
    acc = np.append(acc, np.array([[accel_data['x'], accel_data['y'], accel_data['z']]]), axis=0)

    # increment time array
    time = np.append(time, t)
    t = t + 1

    print("acc[:,0]:" + str(acc[:,0]))
    print("time:" + str(time))
    ani = animation.FuncAnimation(fig, animate, interval = 1000)
    plt.show()
    sleep(2)

但是,当我运行脚本时,它只打印第一个循环中的值,如下所示。它还显示了图表,但它是一个空图表,因为在第一个循环中只有一个数据点。

waiting for the sensor to callibrate...
Accelerometer data
x: 6.2009822998
y: 3.36864173584
z: 9.27513723145
acc[:,0]: [ 6.2009823]
time: [0]

在此处输入图像描述

当我关闭图形窗口时,循环从第二个循环恢复并开始打印值,但图形不再显示。

虽然它没有给出任何错误消息,但我认为有问题animation.FuncAnimation或者我应该放在循环中的plt.show()地方while

我将 Raspberry Pi 3b + 与 Python 2.7.13 一起使用。加速度计是 MPU6050。

如果有人能告诉我如何解决这个问题,那就太好了。谢谢!

标签: pythonmatplotlibanimationgraphraspberry-pi

解决方案


推荐阅读