import machine
import dht
import ssd1306
import time
# Initialize DHT22 sensor
dht_sensor = dht.DHT22(machine.Pin(15))
# Initialize I2C and OLED Display
i2c = machine.I2C(0, scl=machine.Pin(17), sda=machine.Pin(16), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Initialize LED
led = machine.Pin(20, machine.Pin.OUT)
while True:
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
# Display temperature and humidity on OLED
oled.fill(0) # Clear display
oled.text("Temp: {:.1f} C".format(temp), 0, 0)
oled.text("Hum: {:.1f} %".format(hum), 0, 10)
oled.show()
# Check if temperature or humidity exceeds threshold
if temp > 30 or hum > 35:
# Blink the LED
for _ in range(100): # Blink 100 times
led.on()
time.sleep(0.5) # LED on for 0.5 seconds
led.off()
time.sleep(0.5) # LED off for 0.5 seconds
else:
led.off() # Turn off LED if conditions are normal
time.sleep(2) # Delay before the next reading
except OSError as e:
oled.fill(0)
oled.text('Sensor Error', 0, 0)
oled.show()
time.sleep(2)