Try Embedded

Pico in MicroPython: an I2C climate display that copes with a missing sensor

MicroPython on a Raspberry Pi Pico reads an AHT20 over machine.I2C, checks its CRC, draws the reading on an SSD1306 OLED with framebuf, and says so when the…

Sensors · Intermediate

In a real product: Greenhouse climate display (Agriculture): A display on a greenhouse bench shows the air's temperature and humidity and lights the vent lamp when it is too hot.

An AHT20 temperature and humidity sensor and an SSD1306 OLED share one I2C bus: GP4 is SDA (data) and GP5 is SCL (clock). Every second the Pico asks the sensor for a reading, checks it, and draws it on the screen. An LED on GP15 is the vent lamp: it lights above 30 °C. If the sensor does not answer, the program says so on the screen and in the Serial Monitor, and tries again, instead of stopping with an error.

What you'll learn

  • machine.I2C(0, sda=Pin(4), scl=Pin(5)), and scan() to see which addresses answer
  • writeto() and readfrom(): sending a command to a device and reading its bytes back
  • Catching OSError so a missing or unplugged device does not stop the program
  • Drawing text with MicroPython's built-in framebuf and copying it to an SSD1306 in one write

How it works

On I2C every device has a 7-bit address. The AHT20 is at 0x38 and the OLED at 0x3C. i2c.scan() calls each address and returns a list of those that answered, so the program knows at the start what is on the bus. When it prints the list, it prints the numbers in decimal: 56 is 0x38 and 60 is 0x3C.

To measure, the program writes three bytes, 0xAC 0x33 0x00, to the AHT20. The sensor needs 80 ms, so the program waits, then reads seven bytes: a status byte (bit 7 means "still busy"), 20 bits of humidity, 20 bits of temperature, and a CRC. The CRC is a check number the sensor works out from the other six bytes. The program works it out again; if the two differ, a bit was damaged on the wire and the reading is thrown away. The datasheet then turns the raw numbers into units: humidity is raw / 2^20 * 100 %, temperature is raw / 2^20 * 200 - 50 °C.

If a device does not acknowledge its address, writeto() and readfrom() raise OSError. The program catches it in read_climate() and returns None, and the main loop shows "no sensor" and lights the vent lamp, so a broken sensor is never mistaken for a cool greenhouse.

The OLED's driver is only a few lines. framebuf.FrameBuffer draws text into a 1024-byte bytearray (128 × 64 pixels, one bit each). show() sets the OLED's column and page range and sends the whole buffer after a 0x40 byte, which tells the OLED "the rest is pixels". A 0x00 byte in front means "the rest are commands".

The diagram's sensor reads 27.5 °C and 62 %. The Serial Monitor shows:

I2C devices: [56, 60]
27.5 C  62 %  vent off

Try this

  • Click the sensor and raise the temperature above 30 °C: the screen says "VENT ON" and the LED lights.
  • Delete the sensor's SDA wire while it runs: the next reading prints "sensor not answering" and the screen shows it. Draw the wire again and the readings come back.
  • Change crc8() to start from 0x00 instead of 0xFF: every reading now fails its check. This is what a CRC is for: you see a bad reading instead of using it.

main.py

# A greenhouse climate display: an AHT20 sensor and an SSD1306 OLED on I2C0, SDA on GP4 and SCL on GP5.
# The vent lamp on GP15 lights above 30 C, or when the sensor does not answer.
from machine import I2C, Pin
import framebuf
import time

SENSOR = 0x38        # the AHT20's I2C address
SCREEN = 0x3C        # the SSD1306's I2C address
HOT_C = 30.0         # above this, the vent should open

i2c = I2C(0, sda=Pin(4), scl=Pin(5), freq=400_000)
vent = Pin(15, Pin.OUT)


class Oled:
    # The smallest SSD1306 driver: a frame buffer in RAM, copied to the screen by show().
    def __init__(self, i2c, address):
        self.i2c = i2c
        self.address = address
        self.buffer = bytearray(128 * 64 // 8)
        self.fb = framebuf.FrameBuffer(self.buffer, 128, 64, framebuf.MONO_VLSB)
        # Display off, horizontal addressing, mirror to suit the module, charge pump on, display on.
        self.commands(0xAE, 0x20, 0x00, 0xA1, 0xC8, 0x8D, 0x14, 0xAF)

    def commands(self, *codes):
        self.i2c.writeto(self.address, bytes((0x00,) + codes))   # 0x00: commands follow

    def show(self):
        self.commands(0x21, 0, 127, 0x22, 0, 7)                  # columns 0-127, pages 0-7
        self.i2c.writeto(self.address, b"\x40" + self.buffer)    # 0x40: pixels follow


def crc8(data):
    # The AHT20's CRC-8: polynomial 0x31, starting from 0xFF.
    crc = 0xFF
    for byte in data:
        crc ^= byte
        for _ in range(8):
            crc = ((crc << 1) ^ 0x31) & 0xFF if crc & 0x80 else (crc << 1) & 0xFF
    return crc


def read_climate():
    # (temperature in C, humidity in %), or None when the sensor does not answer or the CRC is wrong.
    try:
        i2c.writeto(SENSOR, b"\xAC\x33\x00")      # start a measurement
        time.sleep_ms(80)                         # it takes 80 ms
        data = i2c.readfrom(SENSOR, 7)
        while data[0] & 0x80:                     # bit 7: still busy
            time.sleep_ms(5)
            data = i2c.readfrom(SENSOR, 7)
    except OSError:
        print("sensor not answering")
        return None
    if crc8(data[:6]) != data[6]:
        print("CRC wrong, reading dropped")
        return None
    raw_h = (data[1] << 12) | (data[2] << 4) | (data[3] >> 4)
    raw_t = ((data[3] & 0x0F) << 16) | (data[4] << 8) | data[5]
    return raw_t / 1048576 * 200 - 50, raw_h / 1048576 * 100


found = i2c.scan()
print("I2C devices:", found)
screen = Oled(i2c, SCREEN) if SCREEN in found else None
if SENSOR in found and not i2c.readfrom(SENSOR, 1)[0] & 0x08:
    i2c.writeto(SENSOR, b"\xBE\x08\x00")          # not calibrated yet: initialise it
    time.sleep_ms(10)

while True:
    reading = read_climate()
    if reading is None:
        vent.value(1)                             # fail safe: a missing sensor opens the vent
        lines = ["Greenhouse", "", "no sensor", "check wiring"]
    else:
        t, h = reading
        hot = t > HOT_C
        vent.value(hot)
        print("{:.1f} C  {:.0f} %  vent {}".format(t, h, "ON" if hot else "off"))
        lines = ["Greenhouse", "", "{:.1f} C".format(t), "{:.0f} % RH".format(h), "", "VENT ON" if hot else ""]
    if screen:
        screen.fb.fill(0)
        for row, text in enumerate(lines):
            screen.fb.text(text, 0, row * 10)
        screen.show()
    time.sleep_ms(1000)

Lessons behind it