Search code examples
pythonmatplotlibgraphreal-timesensors

Python- Real time sensor data graphing


I'm getting sensor data from the MPU6050 accelerometer. The sensor gives me the acceleration of the x,y, and z axes. I'm currently just trying to graph the x acceleration vs time. Ideally, I would graph them all together but I can't make the single x data vs time graph work, so I'm just focusing on that now. My code is as follows:

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()

The csv file saves accurate data. The graph does update with time but it gives me a straight line as a result. This is because of how the y axis updates. See image below: enter image description here

As you can see, the y axis is not in ascending order. Can someone help me fix it? In addition, how can I round the numbers in the y axis of the graph to 5 significant digits? I tried using the round() function but it wouldn't let me.

Thank you!


Solution

  • To make the y-axis in ascending order I think you have to make the ys float values instead of string values: ys.append(float(accel_data['x'])) To round the numbers in the y-axis to 5 significant digits you can check the answer to this question: Matplotlib: Specify format of floats for tick labels.