from machine import Pin, I2C
from i2c_lcd import I2cLcd
import time
from machine import UART
#uart#
uart = UART(1, baudrate=9600 , tx = Pin(17) , rx = Pin(16))
print("uart started")
# --------- Hardware Setup ---------
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
devices = i2c.scan()
if not devices:
raise RuntimeError("No LCD Found!")
lcd = I2cLcd(i2c, devices[0], 2, 16)
# --------- Display Handling Function ---------
def show_reading(temp, hum, door):
"""
Receives raw variables directly, formats the layout strings,
and applies safe 16-character row padding.
"""
# Format and pad Line 1 to exactly 16 characters
line1 = "T:{:.1f}C H:{:.1f}%".format(temp, hum)
lcd.move_to(0, 0)
lcd.putstr(line1 + " " * (16 - len(line1)))
# Format and pad Line 2 to exactly 16 characters
lcd.move_to(0,1)
if door == "OPEN_GAS":
line2 = "Gas Leak!"
elif door == "OPEN-PERSON":
line2 = "O:Person Near"
else:
line2 = "Door closed"
lcd.putstr(line2 + " " * (16 - len(line2)))
# Startup Splash
def show_waiting():
lcd.clear()
lcd.move_to(2, 0)
lcd.putstr("Waiting data")
lcd.move_to(6, 1)
lcd.putstr("(^_^)")
show_waiting()
time.sleep(2)
#main loop#
buffer = ""
while True:
if uart.any():
raw_data = uart.read()
if raw_data:
buffer += raw_data.decode('utf-8', 'ignore')
while "\n" in buffer:
Line , buffer = buffer.split("\n",1)
Line = Line.strip()
print("Recieved:", Line)
parts = Line.split(",")
if len(parts) != 3:
continue
try:
temp = float(parts[0])
hum = float(parts[1])
door_state = parts[2]
except:
continue
print(temp , hum , door_state)
show_reading(
temp=temp,
hum=hum,
door=door_state
)
time.sleep(0.1)