environmental_sensors.py 1.41 KB
Newer Older
1
from sense_hat import SenseHat
Rousseau Vincent's avatar
Rousseau Vincent committed
2
3
4
5
from datetime import datetime
import time
from pathlib import Path
import csv
6
7
8

sense = SenseHat()

Rousseau Vincent's avatar
Rousseau Vincent committed
9
10
def float_format(f):
    return '{:.2f}'.format(f)
11

Rousseau Vincent's avatar
Rousseau Vincent committed
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
def get_data():
    humidity = float_format(sense.get_humidity())
    temp_humidity = float_format(sense.get_temperature_from_humidity())
    #print("Humidity sensor : {} %rH , {} °C".format(humidity, temp_humidity))

    pressure = float_format(sense.get_pressure())
    temp_pressure = float_format(sense.get_temperature_from_pressure())
    #print("Pressure sensor : {} Millibars , {} °C".format(pressure, temp_pressure))
    
    return [datetime.now().timestamp(), humidity, temp_humidity, pressure, temp_pressure]

# Create folder to store the data
data_folder = Path('./data')
data_folder.mkdir(parents=True, exist_ok=True)
try:
    while(True):
        current_minute = datetime.now().minute
        file_date = datetime.now().strftime('%Y_%m_%d_%H_%M')
        file_name = data_folder/str('sense_hat_data_' + file_date + '.csv')
        with file_name.open('w') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(['timestamp', 'humidity', 'temp_humidity', 'pressure', 'temp_pressure'])
            
            while(True):
                writer.writerow(get_data())
                time.sleep(1)
                if(current_minute != datetime.now().minute):
                    break

except KeyboardInterrupt:
    pass