import machine
import dht
import time
led_cold = machine.Pin(15, machine.Pin.OUT)
led_normal = machine.Pin(16, machine.Pin.OUT)
led_humid = machine.Pin(17, machine.Pin.OUT)
button_toggle = machine.Pin(18, machine.Pin.IN)
dht_sensor = dht.DHT22(machine.Pin(14))
threshold_cold = 20
threshold_humid = 80
running = False # Flag to indicate if the program should run
def check_button_toggle():
return button_toggle.value()
while True:
if check_button_toggle():
time.sleep(0.1) # Debounce the button
if check_button_toggle(): # Check if the button is still pressed after debounce
running = not running # Toggle the running flag
# If running is False, turn off LEDs immediately
if not running:
led_cold.off()
led_normal.off()
led_humid.off()
# Wait for button release
while check_button_toggle():
pass
if running:
dht_sensor.measure()
time.sleep(1)
temp = dht_sensor.temperature()
humidity = dht_sensor.humidity()
if temp <= threshold_cold:
led_cold.on()
led_normal.off()
led_humid.off()
elif humidity >= threshold_humid:
led_cold.off()
led_normal.off()
led_humid.on()
else:
led_cold.off()
led_normal.on()
led_humid.off()
print("Temperature:", temp)
print("Humidity:", humidity)
time.sleep(1)
else:
time.sleep(0.1) # Add a small delay to reduce CPU usage when not running