I am trying to display data from a sensor on a Matplotlib live chart.
I want to create a thread which reads the sensor continuously. I then use matplotlib.animation to update the graphs with whatever data is in the sensor reading list at that time.
The problem is that the matplotlib.animation only seems to read data from the sensor once, then freezes. Any idea on how to fix this ?
import random
import threading
import matplotlib.animation as animation
import matplotlib.pyplot as plt
def ReadSensors():
global listXData
global listTemp
# Should be sensor data. Using dummy random data for now...
listTemp = [ random.randint(0,5) for x in listXData ]
def UpdateFigure(oFrame):
global listXData
oCurve_Temp.set_data(listXData, listTemp)
return oCurve_Temp,
# Initialize data lists
listXData = range(0,100)
listTemp = [0 for x in listXData]
# Initialize graph
fig, ax = plt.subplots()
ax.set_title('Temperature')
ax.set_xlabel('Data Point')
ax.set_ylabel('[oC]')
ax.set_xlim( 0, 100)
ax.set_ylim( 0, 5)
oCurve_Temp, = ax.plot([],[])
# Starts reading sensor
oThread_ReadSensors = threading.Thread(target = ReadSensors)
oThread_ReadSensors.daemon = True
oThread_ReadSensors.start()
# Update graph
ani = animation.FuncAnimation(fig, UpdateFigure, interval=500)
plt.show()