-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbme280_sample.py
executable file
·92 lines (72 loc) · 2.57 KB
/
bme280_sample.py
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
import os
import sys
import time
import pytz
import datetime
import smbus2
import bme280
from dotenv import load_dotenv
# BME280 sensor address (default address)
address = 0x77
# Initialize I2C bus
bus = smbus2.SMBus(0)
# Load calibration parameters (basically specifying a sensor)
calibration_params = bme280.load_calibration_params(bus, address)
# Load timezone
halifax_tz = pytz.timezone("America/Halifax")
# Load env variables
load_dotenv()
# Load device name and calibration
device_name = os.getenv("NAME")
TEMP_CALI = float(os.getenv("TEMP_CALI"))
PRESSURE_CALI = float(os.getenv("PRESSURE_CALI"))
HUMIDITY_CALI = float(os.getenv("HUMIDITY_CALI"))
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def main(rec_sec=10):
header = [
"Time",
"Temperature (C)",
"Pressure (hPa)",
"Humidity",
]
# Init csv file header
date = datetime.datetime.now().strftime("%Y-%m-%d-%H:%M")
with open(rf"/home/UNBWeatherStation/data/{date}_{device_name}.csv", "w") as file:
header_str = ",".join(header)
file.write(header_str + "\n")
# main loop
for i in range(rec_sec):
try:
# Read sensor data
data = bme280.sample(bus, address, calibration_params)
# Extract temperature, pressure, and humidity
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
temperature_celsius = data.temperature + TEMP_CALI
pressure = data.pressure + PRESSURE_CALI
humidity = data.humidity + HUMIDITY_CALI
# Convert temperature to Fahrenheit
# temperature_fahrenheit = celsius_to_fahrenheit(temperature_celsius)
# write the measurements to the csv file
reading_str = ",".join([str(x) for x in [
timestamp,
temperature_celsius,
pressure,
humidity,
]])
file.write(reading_str)
file.write("\n")
print(reading_str)
# Wait for a few seconds before the next reading
time.sleep(1)
except KeyboardInterrupt:
print('Program stopped')
break
except Exception as e:
print('An unexpected error occurred:', str(e))
break
if (__name__ == "__main__"):
time.sleep(30) # wait for RTC to be set as system clock
args = sys.argv
if (len(args) > 1): main(int(args[1]))
else: main()