This a very strange problem, where one thing seems to affect a totally different other a lot.
I have an external device (connected through a COM port), that constantly sends the value of a sensor (10 bit sensor = 0-1023).
The code I’m writing takes this data and draws it in a chart.
At present there is a line at the bottom commented out (plt.draw()). Like this, the chart is obviously not drawn properly. In this state though, the input from the serial port is fine, it is as you would expect.
The problem comes when you uncomment that line to allow the chart to be drawn. When you do this, suddenly, the input just comes in as one seemingly random value, and doesn’t change as expected. This random value is printed and logged on the chart.
Here’s the code.
import serial
import matplotlib.pyplot as plt
from collections import deque
size=50
plt.ion()
q=deque([0]*size)
ser=serial.Serial('COM3',57600)
lastbyte=None
line,= plt.plot(range(0,size),list(q))
if ser.isOpen():
while True:
x=ser.readline()
try:
x=int(x)
except ValueError:
x=0
if x!=lastbyte:
print x,
lastbyte=x
q.append(x)
q.popleft()
d=list(q)
plt.axis([size,0,0,1024])
line.set_ydata(d[::-1])
# plt.draw() THIS LINE
ser.close()
plt.ioff()
So is there anything to do with the way I’ve used matplotlib that could mess up the input?
I have tested this extensively with different way to get and process the data, but it alway comes down to the plt.draw() messing it up.
After almost giving up on it, the problem’s been fixed!
I’d noticed that the external device was sending data faster than my program could recieve it, and after fixing this, it worked!
Magic!