Devesh36/usb-c-aqi-meter

A PETG-enclosed air-quality monitor assembly combining an AQI circuit board, Sensirion SPS30 particulate sensor, OLED display with bezel and glass, power slider, branding, and internal wiring harness.

Version
1.2.0
License
unset
Stars
0

Use with the tscircuit CLI

tsci is the tscircuit CLI. Install it with npm install -g tscircuit.

tsci clone Devesh36/usb-c-aqi-meter  # download the package files into ./usb-c-aqi-meter
tsci add Devesh36/usb-c-aqi-meter    # add it to your project as @tsci/Devesh36.usb-c-aqi-meter

In a cloned or new (tsci init) project: tsci dev starts a local preview, tsci build outputs Circuit JSON, and tsci push publishes to tscircuit.com.

firmware/main.py

"""BREATHE Pico reference firmware. Hardware testing is still required.

Copy main.py and protocol.py onto a Pico running MicroPython. Configure the
Waveshare SSD1309 module for I2C address 0x3C before connecting the harness.
"""
from machine import Pin, I2C, UART
import framebuf
import time
from protocol import crc8, shdlc_request, shdlc_response, particle_values, indicative_aqi


class Oled:
    """Waveshare 2.42-inch SSD1309 128x64, page addressing."""
    def __init__(self, i2c):
        self.i2c = i2c
        self.buffer = bytearray(1024)
        self.fb = framebuf.FrameBuffer(self.buffer, 128, 64, framebuf.MONO_VLSB)
        reset = Pin(9, Pin.OUT, value=1)
        time.sleep_ms(10)
        reset.value(0)
        time.sleep_ms(10)
        reset.value(1)
        time.sleep_ms(100)
        # SSD1309 uses the module's external OLED supply, not SSD1306 charge-pump commands.
        commands = (0xAE, 0x20, 0x02, 0x40, 0xA1, 0xC8, 0xA6,
                    0xA8, 0x3F, 0xD3, 0x00, 0xD5, 0x80,
                    0xD9, 0x22, 0xDA, 0x12, 0xDB, 0x40, 0x81, 0x7F,
                    0xA4, 0xAF)
        self.command(commands)

    def command(self, values):
        self.i2c.writeto(0x3C, b"\x00" + bytes(values))

    def show(self, lines):
        self.fb.fill(0)
        cursor = 0
        for line in lines[:6]:
            text = str(line)
            if text.startswith("AQI "):
                # Two-times text size makes the current estimate readable at a glance.
                small = framebuf.FrameBuffer(bytearray(64), 64, 8, framebuf.MONO_VLSB)
                small.text(text[:8], 0, 0, 1)
                for y in range(8):
                    for x in range(64):
                        if small.pixel(x, y):
                            self.fb.fill_rect(x * 2, cursor + y * 2, 2, 2, 1)
                cursor += 18
            else:
                self.fb.text(text[:16], 0, cursor, 1)
                cursor += 9
        for page in range(8):
            self.command((0xB0 + page, 0x00, 0x10))
            self.i2c.writeto(0x3C, b"\x40" + self.buffer[page * 128:(page + 1) * 128])


class Sps30:
    def __init__(self):
        # SEL must float for UART. Never configure GP8 as an output/pull-down.
        Pin(8, Pin.IN, pull=None)
        self.uart = UART(0, baudrate=115200, bits=8, parity=None, stop=1,
                         tx=Pin(0), rx=Pin(1), timeout=50, rxbuf=256)

    def command(self, command, data=b""):
        self.uart.read()  # Discard stale complete frames before a request.
        self.uart.write(shdlc_request(command, data))
        deadline = time.ticks_add(time.ticks_ms(), 500)
        frame = bytearray()
        while time.ticks_diff(deadline, time.ticks_ms()) > 0:
            value = self.uart.read(1)
            if not value:
                continue
            if value[0] == 0x7E:
                if len(frame) > 1:
                    frame.append(0x7E)
                    return shdlc_response(frame, command)
                frame = bytearray((0x7E,))
            elif frame:
                frame.extend(value)
                if len(frame) > 256:
                    raise ValueError("SPS30 overlong frame")
        raise OSError("SPS30 timeout")

    def start(self):
        # Software reset also recovers an already-running sensor after Pico reset.
        self.command(0xD3)
        time.sleep_ms(500)
        self.command(0x00, b"\x01\x03")

    def read(self):
        return particle_values(self.command(0x03))


def environment(i2c):
    i2c.writeto(0x44, b"\xFD")
    time.sleep_ms(10)
    data = i2c.readfrom(0x44, 6)
    if crc8(data[:2]) != data[2] or crc8(data[3:5]) != data[5]:
        raise ValueError("SHT40 checksum error")
    temperature = -45 + 175 * ((data[0] << 8) | data[1]) / 65535
    humidity = max(0, min(100, -6 + 125 * ((data[3] << 8) | data[4]) / 65535))
    return temperature, humidity


def main():
    i2c = I2C(1, sda=Pin(2), scl=Pin(3), freq=100000)
    screen = Oled(i2c)
    screen.show(("tscircuit", "AQI --", "STARTING"))
    sensor = Sps30()
    pending_start = True
    samples = []
    last_sample = None
    # SW_PWR physically disconnects USB-C power. No mode/reset controls are fitted.
    while True:
        loop_started = time.ticks_ms()
        try:
            if pending_start:
                sensor.start()
                warm_until = time.ticks_add(time.ticks_ms(), 30000)
                pending_start = False
                samples = []
            values = sensor.read()
            now = time.ticks_ms()
            if values is None:
                if last_sample is not None and time.ticks_diff(now, last_sample) > 5000:
                    raise OSError("No fresh PM data")
                screen.show(("tscircuit", "AQI --", "WAITING FOR PM"))
            elif time.ticks_diff(warm_until, now) > 0:
                screen.show(("tscircuit", "AQI --", "WARMING SENSOR"))
                last_sample = now
            else:
                last_sample = now
                samples.append((now, values[1]))
                samples = [(t, v) for t, v in samples if time.ticks_diff(now, t) < 60000]
                ready = len(samples) >= 55 and time.ticks_diff(now, samples[0][0]) >= 59000
                pm25 = sum(v for _, v in samples) / len(samples)
                aqi = indicative_aqi(pm25) if ready else None
                try:
                    temperature, humidity = environment(i2c)
                    ambient = "%.1fC  %.0f%%RH" % (temperature, humidity)
                except (OSError, ValueError):
                    ambient = "SHT40 ERROR"
                number = ">500" if aqi == 501 else str(aqi) if ready else "--"
                screen.show(["tscircuit / EST", "AQI " + number,
                             "PM2.5 %.1f" % pm25, "ug/m3 / 60s avg", ambient,
                             "US PM2.5 INDEX" if ready else "COLLECTING 60s"])
        except (OSError, ValueError) as error:
            print("tscircuit AQI:", error)
            samples = []
            last_sample = None
            pending_start = True
            screen.show(("SENSOR ERROR", "AQI --", "CHECK SPS30", "USB / CABLE"))
        remaining = 1000 - time.ticks_diff(time.ticks_ms(), loop_started)
        if remaining > 0:
            time.sleep_ms(remaining)


if __name__ == "__main__":
    main()