繁体   English   中英

Python-实时传感器数据绘图

[英]Python- Real time sensor data graphing

我正在从 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() 函数,但它不允许我使用。

谢谢!

为了使 y 轴按升序排列,我认为您必须使 ys 浮点值而不是字符串值: ys.append(float(accel_data['x']))将 y 轴中的数字四舍五入为 5 个ys.append(float(accel_data['x']))您可以查看此问题的答案: Matplotlib: Specify format of floats for tick labels

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM