python - 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。
如果有人能告诉我如何解决这个问题,那就太好了。谢谢!
解决方案
推荐阅读
- java - @Transactional 循环回滚
- javascript - 找不到可靠的赔率解决方案
- javascript - 正则表达式 - RxJS 6 迁移管道
- python-3.x - 如何在python3中使用pickle序列化对象
- vb.net - 即使文件不可用,从文件路径获取默认图标
- ruby - 在没有 require_relative 的情况下测试我的 ruby 模块本地更改
- java - Java JCache 字符串键与复合键
- ruby - 使用rails Axlsx合并多行的多个单元格
- r - 将数据框列中的某些值移动到 R 中的下一列
- excel - 从 Excel 组合框中删除重复项