from machine import Pin, UART, I2C
import ssd1306
import time
# -------------------------------
# OLED Setup (I2C)
# -------------------------------
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
devices = i2c.scan()
if not devices:
raise RuntimeError("No I2C devices found")
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# -------------------------------
# UART Setup
# -------------------------------
uart = UART(1, baudrate=9600, tx=Pin(17), rx=Pin(16))
def show_waiting():
oled.fill(0)
oled.text("Waiting data...", 9, 15)
oled.text("(^_^)", 40, 40)
oled.show()
show_waiting()
while True:
if uart.any():
try:
line = uart.readline() # Read until newline '\n'
if not line:
continue
# Decode binary string to normal text string and clean it up
data_str = line.decode('utf-8').strip()
# Split values by comma: temp, hum, dist, gas_val, gas_bool, door_status
parts = data_str.split(',')
if len(parts) == 6:
temp = parts[0]
hum = parts[1]
dist = parts[2]
gas_val = parts[3] # This is the gas value we want to show
gas_alert = int(parts[4]) # 1 if True, 0 if False
door_status = parts[5]
# Clear screen for fresh data
oled.fill(0)
if gas_alert == 1:
# ==================================================
# EMERGENCY DISPLAY WITH CRITICAL STATE & GAS VALUE
# ==================================================
oled.text("CRITICAL STATE", 8, 2) # Top warning header
oled.text("----------------", 0, 12) # Visual separator line
oled.text("GAS DETECTED!", 12, 24) # Main alert text
oled.text("Gas: {}".format(gas_val), 0, 38) # Current gas concentration
oled.text("Door: FORCED OPEN", 0, 52) # System status
else:
# NORMAL DATA MONITOR MODE (Removed Header to show Door Status)
oled.text("Temp: {} C".format(temp), 0, 2)
oled.text("Hum: {} %".format(hum), 0, 14)
oled.text("Dist: {} cm".format(dist), 0, 26)
oled.text("Gas: {}".format(gas_val), 0, 38)
oled.text("Door: {}".format(door_status), 0, 50)
# Push graphics buffer to hardware screen
oled.show()
except Exception as e:
print("UART Parsing Error:", e)
time.sleep_ms(250)