以下代码中没有绘制任何线条,原因不明。目标是将通过串行端口获取的温度绘制到图形上,X轴表示时间,Y轴表示温度。
$ python -c 'import matplotlib; import matplotlib.pyplot; print(matplotlib.backends.backend)'
TkAgg
$ python3 -c 'import matplotlib; import matplotlib.pyplot; print(matplotlib.backends.backend)'
Qt5Agg
串口数据:
['20.00', '24.00', '22.00', '22.19', '22.25']
['20.00', '24.00', '21.90', '22.19', '22.25']
['20.00', '24.00', '21.90', '22.12', '22.25']
['20.00', '24.00', '21.90', '22.12', '22.25']
['20.00', '24.10', '21.90', '22.19', '22.25']
['20.00', '24.10', '21.90', '22.19', '22.25']
['20.00', '24.10', '21.90', '22.19', '22.25']
['20.00', '24.20', '21.90', '22.19', '22.31']
代码:
import sys, serial, argparse
import datetime
import numpy as np
from time import sleep
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.dates import DateFormatter
class SerialReader:
def __init__(self, port, baudrate, ys=4):
self.ser = serial.Serial(port, baudrate)
self.ax = []
self.ays = {}
for i in range(0, ys):
self.ays[i] = []
def read(self):
line = self.ser.readline()
data = line.decode("utf8").rstrip().split("\t")
if not len(data)==len(self.ays):
return False
return data
def update(self, frameNum, *args):
try:
from pprint import pprint
values = self.read()
# happens only ones due to boot
if not values:
values = self.read()
pprint(values)
data = [float(val) for val in values]
self.ax.append(datetime.datetime.now())
for i in self.ays:
self.ays[i].append(data[i])
i=0
for a in args:
a.set_data(self.ax, self.ays[i])
i+=1
except KeyboardInterrupt:
print('exiting')
return args
def close(self):
self.ser.flush()
self.ser.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Temp reader")
parser.add_argument('-p', '--port', dest='port', default="/dev/ttyUSB0")
parser.add_argument('-b', '--baud', dest='baud', default=9600, type=int)
args = parser.parse_args()
port = args.port
baudrate = args.baud
amount = 5
reader = SerialReader(port, baudrate, amount)
fig, ax = plt.subplots()
ax.autoscale_view()
ax.fmt_xdata = DateFormatter('%H:%M:%S')
plt.xlabel("Time")
plt.ylabel("Temperature")
lines = []
lines.append(ax.plot_date([], [], '-', label = 'DHT11')[0])
lines.append(ax.plot_date([], [], '-', label = 'DHT22 #1')[0])
lines.append(ax.plot_date([], [], '-', label = 'DHT22 #1')[0])
lines.append(ax.plot_date([], [], '-', label = 'MCP9808 #1')[0])
lines.append(ax.plot_date([], [], '-', label = 'MCP9808 #2')[0])
ax.legend(lines, [l.get_label() for l in lines], loc=0)
fig.autofmt_xdate()
anim = animation.FuncAnimation(fig, reader.update, fargs=lines, blit=True, interval=4000)
fig.autofmt_xdate()
plt.show()
reader.close()