from machine import Pin, I2C
from time import sleep
import dht
from i2c_lcd import I2cLcd
# Initialize DHT22 sensor on GPIO28 (change if needed)
sensor = dht.DHT22(Pin(28)) # Use dht.DHT11 if you have DHT11 sensor
# Setup I2C (SDA=GP0, SCL=GP1)
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400000)
# Scan for I2C devices and set LCD address
devices = i2c.scan()
if not devices:
print("No I2C device found! Check wiring.")
lcd = None
else:
print("I2C devices found:", [hex(dev) for dev in devices])
lcd_addr = 0x27 if 0x27 in devices else devices[0]
lcd = I2cLcd(i2c, lcd_addr, 2, 16)
sleep(2) # Sensor stabilization
while True:
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
print(f"Temperature: {temp:.1f} °C Humidity: {hum:.1f} %")
if lcd:
lcd.clear()
lcd.putstr(f"Temp: {temp:.1f} C")
lcd.move_to(0, 1)
lcd.putstr(f"Hum : {hum:.1f} %")
else:
print("LCD not initialized, skipping display.")
except OSError as e:
print("Sensor Error:", e)
if lcd:
lcd.clear()
lcd.putstr("Sensor Error")
else:
print("LCD not initialized, skipping display.")
sleep(3)S