1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import serial
import numpy as np
import math
SER = serial.Serial('COM14')
CHANNELS = [
'ax',
'ay',
'az',
'gx',
'gy',
'gz',
'temp',
'hum',
'pres',
'gas',
'lux',
]
CHANNEL_IDX = {name: i for (i, name) in enumerate(CHANNELS)}
SAMPLE_COUNT = 500
def main():
fig = plt.figure()
# subfigs = fig.subfigures(3, math.ceil(len(CHANNELS) / 3))
elem_data = {}
for chan in CHANNELS:
idx = CHANNEL_IDX[chan]
# subfig = subfigs[idx % 3][idx // 3]
ax = fig.add_subplot(3, math.ceil(len(CHANNELS) / 3), idx + 1)
ax.set_title(chan)
xs = np.arange(SAMPLE_COUNT),
ys = np.zeros(SAMPLE_COUNT),
line = ax.plot(xs, ys)[0]
elem_data[chan] = {
'ys': ys,
# 'fig': subfig,
'ax': ax,
'line': line
}
elem_data['temp']['ax'].set_ylim([15, 40])
elem_data['hum']['ax'].set_ylim([0, 100])
elem_data['pres']['ax'].set_ylim([0, 100000])
def animate(i):
now = datetime.now()
if not SER.in_waiting:
return []
line = SER.readline().decode('utf-8')
for elem in line.split(','):
elem = elem.strip()
if len(elem) == 0:
continue
split = elem.split(':')
if len(split) != 2:
continue
k = split[0].strip()
v = float(split[1].strip())
if k in elem_data:
dat = elem_data[k]
dat['ys'] = np.roll(dat['ys'], -1)
dat['ys'][-1] = v
dat['line'].set_ydata(dat['ys'])
yield from (item['line'] for item in elem_data.values())
ani = animation.FuncAnimation(fig, animate, interval=50, blit=True)
plt.show()
if __name__ == '__main__':
main()
|