MicroPython Driver for DHT12 Sensor

DHT12 Driver Code for micro:bit

Download as zip file

'''
DHT12 (humidity and temperature sensors)
MicroPython driver for micro:bit

AUTHOR: fredscave.com
DATE  : 2025/01
VERSION : 1.00
'''

from microbit import i2c, sleep

ADDR = 0x5C
CMD_MEASURE = bytes([0x00])

def CtoF(Ctemp):
    return round((Ctemp * 9/5) +32, 1)


class DHT12():
    def __init__(self):
        self.data = [None] * 3

    def Read(self):
        attempt = 1
        while (attempt < 4):
            try:
                i2c.write(ADDR, CMD_MEASURE)
                sleep(10)
                buf = i2c.read(ADDR, 5)
            except:
                attempt += 1
                sleep(1000)
            else:
                self.data[0] = DHT12._convertRH(buf)
                self.data[1] = DHT12._convertT(buf)
                self.data[2] = DHT12._checksum(buf)
                return self.data
        self.data[0] = self.data[1] = None
        self.data[2] = False
        return self.data

    def T(self):
        self.Read()
        return self.data[1]

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

    @staticmethod
    def _convertRH(buf):
        RH = buf[0] + buf[1]/10
        return (RH)

    @staticmethod
    def _convertT(buf):
        T = (buf[2] & 0b01111111) + buf[3]/10
        if buf[3] & 0b10000000:
            T = -T
        return T

    @staticmethod
    def _checksum(buf):
        return buf[0]+buf[1]+buf[2]+buf[3] == buf[4]

          

Example

This example will use two DHT12 sensors together on the same I2C bus. Two hundred humidity and temperature readings will be taken from each sensor. There will be a three second interval between each set of readings.

Average humidity and temperature will be calculated for each sensor across the two hundred readings.

An I2C multiplexer will be used to connect the two sensors to the I2C bus since each DHT12 has a fixed address. In this case the TCA9548A multiplexer will be used.

For simplicity the two DHT12 sensors will be referred to as (#1)DHT12 and (#2)DHT12.

Driver files

The following driver module files need to be copied to the micro:bit's filesystem:

Hookup
  • Connect TCA9548A, (#1)DHT12 and (#2)DHT12 power and ground pins to the micro:bit's 3.3V and GND pins respectively.
  • TCA9548A: Connect SCL and SDA to micro:bit's pin19 and pin20 respectively.
  • (#1)DHT12: Connect SCL and SDA pins to TCA9548A's SC1 and SD1 pins respectively.
  • (#2)DHT12: Connect SCL and SDA pins to TCA9548A's SC2 and SD2 pins respectively.
Project hookup with micro:bit, TCA9548A multiplexer and two DHT12 sensors
Project hookup with micro:bit, TCA9548A multiplexer and two x DHT12 sensors.

Code:
# Two DHT12 humidity and temperature
# sensors will each be read (humidity
# and temperature) two hundred times
# with a three second wait period
# between each set of readings.

# When the all the readings have been
# taken, averages for each of the two
# sensors will be calculated and reported.

from fc_dht12 import *
from fc_tca9548a import *
from microbit import sleep

SAMPLES = 200

tca9548a = TCA9548A()
dht12_1 = DHT12()
dht12_2 = DHT12()

sum_RH1 = sum_T1 = sum_RH2 = sum_T2 = 0

for _ in range(SAMPLES):
    # Read (#1)DHT12 sensor
    tca9548a.OpenChannels(1)
    reading = dht12_1.Read()
    sum_RH1 += reading[0]
    sum_T1 += reading[1]
    tca9548a.CloseChannels(1)
    # Read (#2)DHT12 sensor
    tca9548a.OpenChannels(2)
    reading = dht12_1.Read()
    sum_RH2 += reading[0]
    sum_T2 += reading[1]
    tca9548a.CloseChannels(2)
    # Wait 3 seconds
    sleep(3000)
    
# Calculate averages
print('(#1)DHT12 average RH:', sum_RH1/SAMPLES)
print('(#1)DHT12 average T:', sum_T1/SAMPLES)
print('(#1)DHT12 average RH:', sum_RH2/SAMPLES)
print('(#1)DHT12 average T:', sum_T2/SAMPLES)
          

Output:
(#1)DHT12 average RH: 40.802
(#1)DHT12 average T: 25.72602
(#1)DHT12 average RH: 48.36905
(#1)DHT12 average T: 26.31995
          
Notes:

The temperatures between the two sensors are in reasonable agreement at 26°C.

However , in absolute terms, there is a discrepancy of more than 7 %RH between the two sensors. This is a case where an onboard heater (as more sophisticated sensors posses) could be useful. If heat was judicially applied the sensors might provide better results.

Ultimately, both of these sensors should be reconditioned. The product datasheet discusses a process for this.