Created
July 24, 2024 20:58
-
-
Save destroy-data/2f1b570662c4584f379fcc1afc99a12b to your computer and use it in GitHub Desktop.
HDC1080.py – Small micropython library for esp8266 (should work on ESP32 as well) to work with HDC1080 humidity and temperature sensor.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Small micropython library for esp8266 (should work on ESP32 as well) to work with HDC1080 humidity and temperature sensor. | |
# | |
#It consists of one class with three methods. | |
#Constructor: | |
#HDC1080.__init__(self, i2c, address=0x40, heater=False) | |
#You have to pass I2C object and sensor address (if not default). Heater option enables internal heater which is usefull in high humidity environment to prevent condensation on sensor. Heater only works during measurements so you have to take them frequently to have desired effect. If device with given address is not found exception is raised and all found device adresses are printed. | |
# | |
#To measure temperature (Celsius degrees) and relative humidity you have to use object.read_temperature() and object.read_humidity() respectively. Those are synchronous calls and both take slightly more than 7ms. | |
#It's possible to retrieve last measured parameters with object.temperature and object.humidity. | |
from time import sleep_ms | |
class HDC1080: | |
def __init__(self, i2c, address=0x40, heater=False): | |
devices = i2c.scan() | |
assert address in devices, "Didn't find sensor with %d address. Found %s instead." % (address, devices) | |
self.i2c = i2c | |
self.address = address | |
sleep_ms(15) | |
#Setting measurements to be separate, turning on heater | |
buff = bytearray(2) | |
if heater: | |
buff[0] = 1 << 6 | |
i2c.writeto_mem(address, 0x02, buff) | |
def read_temperature(self): | |
self.i2c.writeto(self.address, bytearray(2)) | |
sleep_ms(7) | |
self.temperature = self.i2c.readfrom(self.address, 2) | |
self.temperature = int.from_bytes(self.temperature, "big") / 2**16 * 165 - 40 | |
return self.temperature | |
def read_humidity(self): | |
self.i2c.writeto_mem(self.address, 0x01, bytearray(1)) | |
sleep_ms(7) | |
self.humidity = self.i2c.readfrom(self.address, 2) | |
self.humidity = int.from_bytes(self.humidity, "big") / 2**16 * 100 | |
return self.humidity |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment