Today's tiny project was to add a display for the temperature and humidity instead of printing it to the console. I added another toy from the recent buy - a 1.3" OLED display.

I'm using the robert-hh SH1106 driver. Too lazy to write one for now.

The display's i2c address is $3c, so it works with the LP55231 ($32) and AHT21B ($38) on the same i2c channel.

I stripped all the unnecessary junk out of the AHT21B code in this one, so the source code is pretty simple and easy to read. No frills. Does the job quite well.

Next - wireless, and put the sensor outdoors.

Very simple MicroPython demo:

# ghmicro.com
# AHT21B temperature/humidity sensor - 1.3" OLED display

import time
from machine import I2C, Pin
import sh1106

i2c = machine.I2C(1,freq=400000)
display = sh1106.SH1106_I2C(128,64,i2c)

tri = bytearray(3)
six = bytearray(6)

def write3(one,two,three):
    tri[0] = one
    tri[1] = two
    tri[2] = three
    i2c.writeto(0x38,tri)

while 1:
    write3(0xac,0x33,0x00)       #trigger measurement
    pyb.delay(80)                #wait for measurement
    #should check status here, but delay is long enough
    six = i2c.readfrom(0x38,6)   #read 6 bytes of measurement

    display.fill(0)              #clear framebuffer

    #convert temperature
    i = ((six[3] & 0x0f) << 16) | (six[4] << 8) | six[5]
    temperature_c = ((i / 1048576) * 200) - 50
    temperature_f = ((temperature_c * 9) / 5) + 32
    display.text(str(temperature_f) + "F", 0, 0, 1) #print temp to framebuffer

    #convert humidity
    i = ((six[1] << 16) | (six[2] << 8) | six[3]) >> 4
    humidity = (i / 1048576) * 100
    display.text(str(humidity) + "%",0,15,1)        #print humidity to framebuffer
    display.show()                                  #write framebuffer to screen

    pyb.delay(2000)              #wait 2 seconds and go again

Next Post Previous Post