from machine import Pin, I2C, UART
from machine_i2c_lcd import I2cLcd
import time
# i2c lcd 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)
# UART
uart = UART(1, baudrate=9600, tx=Pin(17), rx=Pin(16))
# last value tracking
last_temp = None
last_hum = None
last_door = None
last_gas = None
# displaying stuff
def show_reading(temp, hum, door):
lcd.clear()
if digital_gas_value == 0:
line_1 = ("GAS LEAK!")
lcd.move_to(0, 0)
lcd.putstr(line_1 + " " * (16 - len(line_1)))
line_2 = ("TAKE ACTION NOW!")
lcd.move_to(0, 1)
lcd.putstr(line_2 + " " * (16 - len(line_2)))
else:
lcd.clear()
line_1 = "T:{:.1f}C H:{:.1f}%".format(temp, hum)
lcd.move_to(0, 0)
lcd.putstr(line_1 + " " * (16 - len(line_1)))
line_2 = "DOOR: " + door
lcd.move_to(0, 1)
lcd.putstr(line_2 + " " * (16 - len(line_2)))
def show_waiting():
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("Waiting for data")
lcd.move_to(6, 1)
lcd.putstr("(^_^)")
show_waiting()
time.sleep(2)
while True:
if uart.any():
line = uart.readline()
if not line:
continue
try:
text = line.decode().strip()
print(f"Received:{text}")
t_str, h_str, n_f, d_str, g_val = text.split(",")
temp = float(t_str)
hum = float(h_str)
near_flag = bool(n_f)
door = str(d_str)
digital_gas_value = int(g_val)
if (temp != last_temp or hum != last_hum or
door != last_door or digital_gas_value != last_gas):
show_reading(temp, hum, door)
last_temp = temp
last_hum = hum
last_door = door
except Exception as e:
print(f"Parse Error: {e}, Data: {line}")
time.sleep_ms(20)