Read-Sensor-Resistances/serial_plot.pyw

70 lines
2.5 KiB
Python
Raw Normal View History

2022-05-15 19:48:22 +00:00
import matplotlib.pyplot as plt
import matplotlib.animation as animate
import math, json, traceback
try:
import matplotlib
matplotlib.use("QtAgg") # to force use one of the matplot's UI backend instead of an IDE's choice
except ImportError:
traceback.print_exc()
def plotter():
a = json.load(open('settings.json', 'r'))
sensors = len(a['sensor_ports'])
windowsize = a['winSize']
delay = a["delay"] / 1000
file = open(a["file_name"], "r")
colors = ['blue', 'orange', 'green', 'yellow']
fig, axs = plt.subplots(1, 1)
timeStamps = []
sensorsData = []
i = 0
while i <= sensors:
sensorsData.append([])
i = i + 1
def animation(t):
next_line = file.readline()
if next_line:
line = next_line.split(',')
if len(line) >= sensors:
i = 1
timeStamps.append(line[0])
# idk what this condition does.... Nathan wrote this without saying much
if windowsize != 0 and len(timeStamps) > math.ceil(windowsize / delay):
timeStamps.pop(0)
val_lists = []
while i <= sensors:
if not line[i]: # pass on invalid values
continue
sensorsData[i - 1].append(float(line[i])) # cast it to float so the y-axis will not jump around
# idk what this condition does.... Nathan wrote this without saying much
if windowsize != 0 and len(sensorsData[i - 1]) > math.ceil(windowsize / delay):
sensorsData[i - 1].pop(0)
val_lists.append(sensorsData[i - 1])
i += 1
for j in range(len(val_lists)):
axs.plot(val_lists[j], color=colors[j],
label=f'sensor {j + 1}') # TODO: display sensor number to the actual arduino's port &
# axs.annotate('%0.2f' % val_lists[j][-1], xy=(1, val_lists[j][-1]), xytext=(8, 0),
# xycoords=('axes fraction', 'data'), textcoords='offset points')
# Acknowledgement: https://stackoverflow.com/a/13589144
handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
axs.legend(by_label.values(), by_label.keys(), loc='best')
ani = animate.FuncAnimation(plt.gcf(), func=animation) # , interval=delay * 500)
# ani.save("plot.gif")
# plt.ion()
plt.show(block=True)
plotter()