from machine import Pin, I2C
import dht
import time
from i2c_lcd import I2cLcd
# Initialize I2C for the LCD
i2c = I2C(1, scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16) # Change 0x27 to your LCD’s I2C address if needed
# Initialize DHT22 sensor
sensor = dht.DHT22(Pin(4))
while True:
try:
# Read temperature and humidity from DHT22
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
# Display temperature and humidity on the LCD
lcd.clear()
lcd.putstr("Temp: {:.1f}C".format(temperature))
lcd.move_to(0, 1) # Move cursor to the second line
lcd.putstr("Humidity: {:.1f}%".format(humidity))
except OSError as e:
# Display error message if reading fails
lcd.clear()
lcd.putstr("Sensor error")
# Wait before taking the next reading
time.sleep(2)