MicroPython Driver for AHT10 / AHT15

AHT10, AHT15 Driver Code for micro:bit

Download as zip file

'''
AHT10, AHT15 (humidity and temperature sensors)
MicroPython driver for micro:bit

AUTHOR: fredscave.com
DATE  : 2024/11
VERSION : 1.00
'''

from microbit import i2c, sleep
from micropython import const

ADDR = const(0x38)
CMD_INIT = [0xE1, 0x08, 0x00]
CMD_MEASURE = [0xAC, 0x33, 0x00]
CMD_RESET = const(0xBA)

class AHT1X():
    def __init__(self, addr=ADDR):
        self.addr = addr
        self.Initialise()

    def Initialise(self):
        i2c.write(self.addr, bytearray(CMD_INIT))        

    def Read(self):
        i2c.write(self.addr, bytearray(CMD_MEASURE))
        #sleep(50)
        busy = True
        while busy:
            buf = i2c.read(self.addr, 6)
            sleep(10)
            busy = buf[0] & 0b10000000
        measurements = AHT1X.convert(buf)
        return measurements

    def T(self):
        measurements = self.Read()
        return round(measurements[1], 1)

    def RH(self):
        measurements = self.Read()
        return int(measurements[0] + 0.5)

    def Reset(self):
        i2c.write(self.addr, bytes([CMD_RESET]))
        sleep(20)

    @staticmethod
    def convert(buf):
        RawRH = ((buf[1] << 16) |( buf[2] << 8) | buf[3]) >> 4
        RH = RawRH * 100 / 0x100000
        RawT = ((buf[3] & 0x0F) << 16) | (buf[4] << 8) | buf[5]
        T = ((RawT * 200) / 0x100000) - 50
        return (RH, T)