データの受け渡しがメインということなので、その辺のサンプルとしてみてください。グラフ描画は極めていいかげんです。
Arduino側のテストデータ発生プログラム。
シリアルに対しindex,data1,data2,data3
というデータを発行します。
Arduino
1const float TEMP_TABLE[] = {
2 30, 30, 31, 32, 32, 32, 33, 33, 34, 34,
3 35, 35, 34, 34, 34, 33, 33, 33, 33, 33,
4 32, 32, 32, 32, 32, 32, 31, 31, 32, 31,
5 28, 28, 28, 28, 27, 27, 28, 28, 28, 27,
6 26, 27, 27, 28, 29, 29, 29, 30
7};
8// 直近24時間の30分毎 東京の気温
9// from https://www.time-j.net/WorldTime/Weather/Weather36h/Asia/Tokyo
10
11const int SIZE = sizeof TEMP_TABLE/sizeof TEMP_TABLE[0];
12unsigned long idx;
13void setup() {
14 Serial.begin(115200);
15}
16
17void loop() {
18 float temp1, temp2, temp3;
19 temp1 = TEMP_TABLE[idx%SIZE];
20 temp2 = TEMP_TABLE[(idx*3/2)%SIZE]+0.5;
21 temp3 = TEMP_TABLE[(idx*2)%SIZE]+1.5;
22
23 Serial.print(idx);
24 Serial.print(',');
25 Serial.print(temp1);
26 Serial.print(',');
27 Serial.print(temp2);
28 Serial.print(',');
29 Serial.println(temp3);
30
31 idx++;
32 delay(500);
33}
Python側、一行データを受信し、,
で切り分けて、配列に繋いで、グラフ表示する例。
Python
1import serial
2import matplotlib.pyplot as plt
3
4showNum=48
5
6idx=[0]*showNum
7temp1=[0.]*showNum
8temp2=[0.]*showNum
9temp3=[0.]*showNum
10fig, ax = plt.subplots()
11ax.set_xlabel('TEMP1')
12with serial.Serial('COM3',115200, timeout=5) as ser:
13 while True:
14 line=ser.readline().decode()
15 if len(line)==0 :
16 continue
17 elements=line.split(',')
18 idx.append(int(elements[0]))
19 idx=idx[-showNum:]
20 temp1.append(float(elements[1]))
21 temp1=temp1[-showNum:]
22 temp2.append(float(elements[2]))
23 temp2=temp2[-showNum:]
24 temp3.append(float(elements[3]))
25 temp3=temp3[-showNum:]
26 #ここまでで、idx, temp1, temp2, temp3に直近のデータ配列が出来ている
27
28 #適宜グラフ描画
29 line1, =ax.plot(idx,temp1,color='red')
30 line2, =ax.plot(idx,temp2,color='green')
31 line3, =ax.plot(idx,temp3,color='blue')
32 plt.xlim(idx[0],idx[-1])
33 plt.pause(0.001)
34 line1.remove()
35 line2.remove()
36 line3.remove()