from machine import Pin, I2C
from time import sleep
import dht
from i2c_lcd import I2cLcd
# --- Sensor and LCD Setup ---
# Initialize DHT22 sensor on GPIO28
sensor = dht.DHT22(Pin(28))
# Initialize I2C for LCD (SDA = GP0, SCL = GP1)
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400000)
# LCD I2C address (use i2c.scan() to find if unknown)
I2C_ADDR = 0x27
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
# --- Program Start ---
lcd.clear()
lcd.putstr("System Initializing")
sleep(2)
while True:
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
# Print to serial
print("Temperature: {:.1f} C Humidity: {:.1f} %".format(temp, hum))
# Display on LCD
lcd.clear()
lcd.putstr("Temp: {:.1f} C".format(temp))
lcd.move_to(0, 1)
lcd.putstr("Hum : {:.1f} %".format(hum))
except Exception as e:
print("Sensor Error:", e)
lcd.clear()
lcd.putstr("Sensor Error")
lcd.move_to(0, 1)
lcd.putstr(str(e)[:16]) # Print first 16 chars of error
sleep(2)