from machine import Pin, I2C
from dht import DHT22
from utime import sleep_ms
# Set up I2C
i2c = I2C(scl=Pin(22), sda=Pin(21))
# Set up DHT22 sensor
dht_sensor = DHT22(Pin(21))
# Set up LEDs on Pin 14 and Pin 15
led_temp_pin = Pin(14, Pin.OUT)
led_humidity_pin = Pin(15, Pin.OUT)
# Set up buttons on Pin 26 and Pin 27
button_temp_pin = Pin(26, Pin.IN, Pin.PULL_UP)
button_humidity_pin = Pin(27, Pin.IN, Pin.PULL_UP)
while True:
try:
# Read data from DHT22
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
# Print the data
print("Temperature: {:.2f} °C".format(temperature))
print("Humidity: {:.2f} %".format(humidity))
# Check buttons and turn off LEDs if pressed
if not button_temp_pin.value():
# Button on Pin 26 pressed, turn off LEDs
led_temp_pin.off()
else:
if temperature > 45:
# Turn on the LED on Pin 14
led_temp_pin.on()
else:
# Turn off the LED on Pin 14
led_temp_pin.off()
if not button_humidity_pin.value():
# Button on Pin 27 pressed, turn off LEDs
led_humidity_pin.off()
else:
if humidity < 25 or humidity > 60:
# Turn on the LED on Pin 15
led_humidity_pin.on()
else:
# Turn off the LED on Pin 15
led_humidity_pin.off()
except Exception as e:
print("Error reading DHT22:", e)
# Delay before the next reading
sleep_ms(100)