-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_dht.py
executable file
·56 lines (47 loc) · 1.34 KB
/
test_dht.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import adafruit_dht
import board
import json
import signal
import sys
import time
from config import gpio
# always cleanup GPIO on strg-c or kill
def signalHandler(signal, frame):
dhtDevice.exit()
sys.exit(0)
config = json.load(open('config.json', 'r'))
sensor = config['dht']['type']
interval = 4.0
if sensor == 'DHT11':
dhtDevice = adafruit_dht.DHT11(gpio)
elif sensor == 'DHT22':
dhtDevice = adafruit_dht.DHT22(gpio)
else:
print('Error: Invalid DHT sensor type: %s' % sensor)
sys.exit(1)
signal.signal(signal.SIGINT, signalHandler)
print('Note: Errors are expected when reading from DHT sensor, don\'t worry about them.')
lastSuccessRead = 0
while True:
try:
temp = dhtDevice.temperature
hum = dhtDevice.humidity
except RuntimeError as e:
# errors are expected when reading from DHT
print(e)
time.sleep(0.2)
continue
except Exception as error:
dhtDevice.exit()
raise error
if temp is None or hum is None:
print('Read incomplete data, trying again')
time.sleep(0.2)
continue
lastSuccessRead = time.time()
print('Temperature: %.1f C, Humidity: %s%%' % (temp, hum))
sleepSecs = interval - (time.time() - lastSuccessRead)
if sleepSecs > 0:
time.sleep(sleepSecs)