Serial data plotting from Matplotlib getting too delayed

32 views Asked by At

I am using Pyserial and Matplotlib to plot a MPU6050 serial data in real time. The code is simple, but my data keep getting delayed by about 15 seconds, so I am not sure what is causing the problem. Here is my code:

import serial
import matplotlib.pyplot as plt
import numpy as np
import re

ser = serial.Serial('COM3', 115200)

#init buffer
num = 10
time = np.zeros(num)
angx = np.zeros(num)
t = np.linspace(1,num, num=num)

#init Figure
plt.figure("X Angle")

plt.grid(True)
plt.ylabel('deg')

#RegEx compile
numbers = re.compile(r"[-+]?\d*\.\d+|\d+")

while True:
    newVals = str(ser.readline())
    #newVals = newVals.split(",")
    newVals = numbers.findall(newVals)
    # adding one item to the array:
    # shift the existing items and add an item to the end
    angx[:-1] = angx[1:]
    angx[-1] = float(newVals[1])
    
    plt.autoscale(enable = False)
    plt.ylim([-200,200])
    plt.xlim([0,10])
    plt.plot(t,angx)
    plt.pause(0.01)
    plt.cla()

At first I thought the problem was that the speed of all the plotting caused the lag, so I increase the wait time of the While loop up to 1 seconds, but the lag remains the same (15 secs). I expected the lag to be at most, equal to the execution time of the while loop (which is faster than 0.1s on my machine). The numbers still display correctly on my Serial Moniter with almost no delay though, so now I am clueless. Any suggestions?

0

There are 0 answers