forked from Honey-Pi/rpi-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
read_sht31.py
67 lines (52 loc) · 2.2 KB
/
read_sht31.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
# Distributed with a free-will license.
# Use it any way you want, profit or free, provided it fits in the licenses of its associated works.
# SHT31
# This code is designed to work with the SHT31_I2CS I2C Mini Module available from ControlEverything.com.
# https://www.controleverything.com/content/Humidity?sku=SHT31_I2CS#tabs-0-product_tabset-2
import smbus
import time
from utilities import error_log
from sensors.sensor_utilities import get_smbus
# SHT31 address, 0x44(68)
DEVICE=0x44
def read_sht31(addr=DEVICE):
# Get I2C bus
bus = smbus.SMBus(get_smbus())
# Send measurement command, 0x2C(44)
# 0x06(06) High repeatability measurement
bus.write_i2c_block_data(addr, 0x2C, [0x06])
time.sleep(0.5)
# Read data back from 0x00(00), 6 bytes
# Temp MSB, Temp LSB, Temp CRC, Humididty MSB, Humidity LSB, Humidity CRC
data = bus.read_i2c_block_data(addr, 0x00, 6)
# Convert the data
temp = data[0] * 256 + data[1]
cTemp = -45 + (175 * temp / 65535.0)
fTemp = -49 + (315 * temp / 65535.0)
humidity = 100 * (data[3] * 256 + data[4]) / 65535.0
return (cTemp, humidity)
def measure_sht31(ts_sensor):
try:
fields = {}
temperature,humidity = read_sht31(DEVICE)
# ThingSpeak fields
# Create returned dict if ts_field is defined
if 'ts_field_temperature' in ts_sensor and isinstance(temperature, (int, float)):
if 'offset' in ts_sensor and ts_sensor["offset"] is not None:
temperature = temperature-ts_sensor["offset"]
fields[ts_sensor["ts_field_temperature"]] = round(temperature, 2)
if 'ts_field_humidity' in ts_sensor and isinstance(humidity, (int, float)):
fields[ts_sensor["ts_field_humidity"]] = round(humidity, 2)
return fields
except Exception as e:
error_log(e, 'Error: Error while reading SHT3x Sensor. Is it connected?')
return None
if __name__ == '__main__':
try:
cTemp,humidity = read_sht31(DEVICE)
print("Temperature:", cTemp, "C")
print("Humidity:", humidity, "%RH")
except (KeyboardInterrupt, SystemExit):
pass
except Exception as e:
error_log(e, "Unhandled Exception in SHT31 Measurement")