-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadSerial.py
More file actions
41 lines (35 loc) · 1.46 KB
/
ReadSerial.py
File metadata and controls
41 lines (35 loc) · 1.46 KB
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
import serial
import csv
from datetime import datetime
SERIAL_PORT = 'COM5'
BAUD_RATE = 9600
date_str = datetime.now().strftime("%Y%m%d_%H%M%S")
CSV_FILE = f"data/data_log_{date_str}.csv"
header = ['Timestamp', 'Humidity', 'Pressure', 'Temperature1H', 'Temperature2B', 'Difference', 'Average']
arduino = serial.Serial(SERIAL_PORT, BAUD_RATE)
with open(CSV_FILE, mode='a', newline='') as file:
writer = csv.writer(file)
# Write header if file is empty
if file.tell() == 0:
writer.writerow(header)
print(f"Listening on {SERIAL_PORT}... Press Ctrl+C to stop.")
try:
while True:
line = arduino.readline().decode('utf-8').strip()
if line:
parts = line.split(',') # Split CSV line into columns
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
temp1H = float(parts[2])
temp2B = float(parts[3])
diff = round(temp1H - temp2B, 2)
avg = round((temp1H + temp2B) / 2, 2)
parts.append(diff)
parts.append(avg)
writer.writerow([timestamp] + parts)
file.flush()
print(f"{timestamp} | Humidity: {parts[0]}%, Pressure: {parts[1]}kPa, Temp1H: {parts[2]}°C, Temp2B: {parts[3]}°C, Diff: {parts[4]}, Avg: {parts[5]}")
except KeyboardInterrupt:
print("\nStopped by user.")
finally:
arduino.close()
print("Serial connection closed.")