I am reading from a serial port (sensor data, y) and would like to graph it vs time (x). I use system time to calculate elapsed time. The reading from sensor has no lag. But the way I plot it introduces a lag of several seconds so that it is way behind the sensor's actual state (hence not acceptable as real time data). Please help me learn how to better plot the x,y data here. Thanks a lot in advance!
import serial
import time
import matplotlib.pyplot as plt
start = time.time()
x = []
y = []
ser = serial.Serial('COM6', 2000000, timeout=0)
time.sleep(2)
fig = plt.figure()
plt.ion() # turn on interactive mode
fig.canvas.draw()
plt.show(block=False)
while True:
line = ser.readline() # read a byte
if line:
string = line.decode() # convert the byte string to a unicode string
#num = re.findall(r"[- ]?\d*\.\d |\d ", string)
num = float(string)
end = time.time()
y.append(num)
time_elapsed= end - start
x.append(time_elapsed)
plt.cla()
plt.plot(x, y, 'red')
plt.pause(0.05)
plt.draw()
CodePudding user response:
I had the same problem with pyserial. It's the ser.readline
being slow. Please try and use ser.read(ser.in_waiting)
instead. Previously the delay was around 20s, now its down to <2s. Here is the answer from previous question for reference
CodePudding user response:
Thanks for your reply. The lag here is not from read function because I can print out x and y at high frequency without a noticeable delay. Plotting was the culprit. I used PyQtGraph, and the plotting is now much faster and there is barely any lag as much as I could notice. Thanks again!