from machine import Pin
import dht
import time
# Thiết lập các ngưỡng nhiệt độ và độ ẩm
TEMP_HIGH_THRESHOLD = 25
TEMP_LOW_THRESHOLD = 23
HUM_HIGH_THRESHOLD = 50
# Khai báo các chân GPIO cho cảm biến DHT22 và LED
dht_pin = Pin(15, Pin.IN, Pin.PULL_UP) # Chân DHT22
led_red = Pin(16, Pin.OUT) # LED đỏ
led_yellow = Pin(17, Pin.OUT) # LED vàng
led_green = Pin(18, Pin.OUT) # LED xanh
# Khởi tạo cảm biến DHT22
sensor = dht.DHT22(dht_pin)
def flash_led(pin, times=2, delay_time=0.5):
for _ in range(times):
pin.on()
time.sleep(delay_time)
pin.off()
time.sleep(delay_time)
def get_temp_status(temp):
if temp > TEMP_HIGH_THRESHOLD:
return "hot"
elif temp < TEMP_LOW_THRESHOLD:
return "cold"
else:
return "normal"
def get_hum_status(hum):
if hum > HUM_HIGH_THRESHOLD:
return "humid"
else:
return "normal"
def update_leds(temp, hum):
temp_status = get_temp_status(temp)
hum_status = get_hum_status(hum)
if temp_status == "hot":
led_red.on()
led_yellow.off()
led_green.off()
elif temp_status == "cold":
led_red.off()
led_yellow.on()
led_green.off()
else:
led_red.off()
led_yellow.off()
led_green.on()
if hum_status == "humid":
flash_led(led_red)
else:
flash_led(led_green)
while True:
try:
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
print("Temperature: {}*C Humidity: {}%".format(temperature, humidity))
update_leds(temperature, humidity)
time.sleep(2)
except OSError as e:
print('Failed to read sensor.')