Python-实时传感器数据绘图

问题描述 投票:0回答:2

我正在从 MPU6050 加速度计获取传感器数据。传感器为我提供 x、y 和 z 轴的加速度。我目前只是想绘制 x 加速度与时间的关系图。理想情况下,我会将它们全部绘制在一起,但我无法使单个 x 数据与时间图一起工作,所以我现在只关注这一点。我的代码如下:

from mpu6050 import mpu6050
import time
import os
from time import sleep
from datetime import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
mpu = mpu6050(0x68)

#create csv file to save the data
file = open("/home/pi/Accelerometer_data.csv", "a")
i=0
if os.stat("/home/pi/Accelerometer_data.csv").st_size == 0:
        file.write("Time,X,Y,Z\n")

# Create figure for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = []
ys = []


def animate(i, xs, ys):

    # Read acceleration from MPU6050
    accel_data = mpu.get_accel_data()
    
    #append data on the csv file
    i=i+1
    now = dt.now()
    file.write(str(now)+","+str(accel_data['x'])+","+str(accel_data['y'])+","+str(accel_data['z'])+"\n")
    file.flush()

    # Add x and y to lists
    xs.append(dt.now().strftime('%H:%M:%S.%f'))
    ys.append(str(accel_data['x']))
    
    # Limit x and y lists to 20 items
    xs = xs[-10:]
    ys = ys[-10:]

    # Draw x and y lists
    ax.clear()
    ax.plot(xs, ys)

    # Format plot
    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    plt.title('MPU6050 X Acceleration over Time')
    plt.ylabel('X-Acceleration')

#show real-time graph
ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys), interval=1000)
plt.show()

csv文件保存准确的数据。该图确实随着时间更新,但结果却给了我一条直线。这是因为 y 轴的更新方式所致。见下图:

如您所见,y 轴不是按升序排列的。有人可以帮我解决吗?另外,如何将图表y轴上的数字四舍五入到5位有效数字?我尝试使用 round() 函数,但它不允许我这样做。

谢谢!

python matplotlib graph real-time sensors
2个回答
3
投票

要使 y 轴按升序排列,我认为您必须使 ys 浮点值而不是字符串值:

ys.append(float(accel_data['x']))
要将 y 轴中的数字四舍五入为 5 位有效数字,您可以检查此问题的答案:Matplotlib:指定刻度标签的浮点数格式


0
投票

我遇到了类似的问题,并创建了这个库来绘制多个实时传感器流。仍在开发中

https://github.com/hidara2000/fast_sensor_stream

© www.soinside.com 2019 - 2024. All rights reserved.