from machine import Pin, I2C, UART
import time
from i2c_lcd import I2cLcd
########### LCD CODE : ##################
# I²C on default ESP32 pins (change if needed)
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
# Find LCD address
devices = i2c.scan()
if not devices:
raise RuntimeError("No I2C devices found. Check wiring.")
# 16x2 LCD at first found address
lcd = I2cLcd(i2c, devices[0], 2, 16)
# UART1: TX=17, RX=16
uart = UART(1, baudrate=9600, tx=Pin(17), rx=Pin(16))
lcd.clear()
lcd.putstr("Waiting for data")
def show_reading(t, h,g,d):
while True :
lcd.clear()
# Line 1: Temp (fits 16 chars)
lcd.move_to(0, 0)
lcd.putstr("Temp: {:>5.1f}C".format(t))
# Line 2: Humidity
lcd.move_to(0, 1)
lcd.putstr("Hum : {:>5.1f}%".format(h))
time.sleep(5)
lcd.clear()
# Line 1: Temp (fits 16 chars)
if g==0:
lcd.putstr("Gas leak ⚠")
# Line 2: Humidity
lcd.move_to(0, 1)
if d==1:
lcd.putstr("Door : Open")
elif d==0:
lcd.putstr("Door : Closed")
time.sleep(5)
#MAIN LOOP
while True:
if uart.any():
line = uart.readline()
print(line)
if not line:
continue
try:
text = line.decode().strip()
parts = text.split(",")
t = float(parts[0])
h = float(parts[1])
g = int(float(parts[2]))
d = int(float(parts[3]))
show_reading(t, h, g, d)
print("Recv:", text)
except Exception as e:
print(e)
time.sleep_ms(20)