from machine import Pin, I2C
from time import sleep
import dht
from i2c_lcd import I2cLcd
# Initialize DHT22 sensor on GPIO28
sensor = dht.DHT22(Pin(28)) # Change to DHT11 if needed
# Setup I2C (SDA=GP0, SCL=GP1)
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400000)
# Scan for I2C devices
devices = i2c.scan()
if not devices:
print("No I2C device found! Check wiring.")
lcd = None
lcd_available = False
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)
lcd.putstr("Initializing...")
sleep(1)
lcd.clear()
lcd_available = True
sleep(2) # Allow sensor to stabilize
while True:
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
print(f"Temperature: {temp:.1f} °C Humidity: {hum:.1f} %")
if lcd_available:
lcd.clear()
lcd.putstr(f"Temp: {temp:.1f}{chr(223)}C")
lcd.move_to(0, 1)
lcd.putstr(f"Hum : {hum:.1f} %")
else:
print("LCD not available.")
except OSError as e:
print("Sensor Error:", e)
if lcd_available:
lcd.clear()
lcd.putstr("Sensor Error")
else:
print("LCD not available to display error.")
sleep(3)