from machine import Pin, SoftI2C
from time import sleep
from pico_i2c_lcd import I2cLcd
import dht
# Initialize I2C and LCD
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=100000)
I2C_ADDR = 0x27
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
dht_sensor = dht.DHT22(Pin(14))
RED_LED = Pin(18, Pin.OUT)
GREEN_LED = Pin(19, Pin.OUT)
BLUE_LED = Pin(23, Pin.OUT)
threshold = 30
def update_display():
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
lcd.clear()
lcd.putstr("Nhiet do: {}C".format(temp))
lcd.move_to(0, 1)
lcd.putstr("Do am: {}%".format(hum))
if temp < 20:
RED_LED.off()
GREEN_LED.off()
BLUE_LED.on()
elif 20 <= temp <= threshold:
RED_LED.off()
GREEN_LED.on()
BLUE_LED.off()
else:
RED_LED.on()
GREEN_LED.off()
BLUE_LED.off()
lcd.clear()
lcd.putstr("CANH BAO!")
except OSError as e:
print("Failed to read sensor.")
lcd.clear()
lcd.putstr("Error reading")
RED_LED.off()
GREEN_LED.off()
BLUE_LED.off()
while True:
update_display()
sleep(2)