Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
63 lines (53 sloc) 1.75 KB
"""
Read HDC1008 temperature and humidity.
Datasheet: http://www.ti.com/lit/ds/symlink/hdc1008.pdf
"""
from __future__ import print_function
import time
import array
import io
import fcntl
def read_temperature_humidity():
# Device filename: I2C bus 1.
DEV_FILENAME = "/dev/i2c-1"
# From <linux/i2c-dev.h>
I2C_SLAVE_DEV = 0x0703
# Default HDC1008 I2C address
I2C_ADDR = 0x40
TEMP_REG = 0x00
HUM_REG = 0x01
CFG_REG = 0x02
TEMP_CONV_SEC = 0.0065 # 6.50 ms
HUM_CONV_SEC = 0.00625 # 6.25 ms
STARTUP_CONV_SEC = 0.015 # 15 ms
DATA_LEN = 2 # 2 bytes output data
# Open device
f_dev_rb = io.open(DEV_FILENAME, "rb", buffering=0)
fcntl.ioctl(f_dev_rb, I2C_SLAVE_DEV, I2C_ADDR)
f_dev_wb = io.open(DEV_FILENAME, "wb", buffering=0)
fcntl.ioctl(f_dev_wb, I2C_SLAVE_DEV, I2C_ADDR)
# Configure for full resolution temperature and humidity.
buf = bytearray([CFG_REG, 0x02, 0x00]) # Set Bit[12] to 1.
f_dev_wb.write(buf)
time.sleep(STARTUP_CONV_SEC)
# Read temperature
buf = bytearray([TEMP_REG])
f_dev_wb.write(buf)
time.sleep(TEMP_CONV_SEC)
data = f_dev_rb.read(DATA_LEN)
buf = array.array('B', data)
raw_temperature = buf[0] * 256 + buf[1]
temperature = (raw_temperature / 65536.0) * 165.0 - 40.0
# If you prefer Fahrenheit
temperature = temperature * 9.0 / 5.0 + 32.0
# Read relative humidity
buf = bytearray([HUM_REG])
f_dev_wb.write(buf)
time.sleep(HUM_CONV_SEC)
data = f_dev_rb.read(DATA_LEN)
buf = array.array('B', data)
raw_humidity = buf[0] * 256 + buf[1]
humidity = (raw_humidity / 65536.0) * 100.0
return (temperature, humidity)
if __name__ == "__main__":
print("%.2fF\t%.2f%%" % read_temperature_humidity())