from machine import Pin, ADC, I2C
import dht
import time
import ssd1306
# Pin Configuration
# DHT22 (GP28)
dht_sensor = dht.DHT22(Pin(28))
# LDR (GP26)
ldr = ADC(26)
# RGB LED
red_led = Pin(13, Pin.OUT)
green_led = Pin(12, Pin.OUT)
blue_led = Pin(11, Pin.OUT)
# Buzzer (GP14)
buzzer = Pin(14, Pin.OUT)
# OLED (GP16 = SDA, GP17 = SCL)
i2c = I2C(0, sda=Pin(16), scl=Pin(17), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Thresholds
TEMP_WARNING = 30
TEMP_CRITICAL = 35
LIGHT_THRESHOLD = 30000
# Functions
def read_sensors():
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
light = ldr.read_u16()
return temperature, humidity, light
def get_status(temp, light):
if temp > TEMP_CRITICAL or light < LIGHT_THRESHOLD:
return "CRITICAL"
elif temp >= TEMP_WARNING:
return "WARNING"
else:
return "NORMAL"
def update_led(status):
red_led.off()
green_led.off()
blue_led.off()
if status == "NORMAL":
green_led.on()
elif status == "WARNING":
red_led.on()
green_led.on() # Yellow
elif status == "CRITICAL":
red_led.on()
def update_buzzer(status):
if status == "CRITICAL":
buzzer.on()
else:
buzzer.off()
def update_display(temp, hum, light, status):
oled.fill(0)
oled.text("Env Monitor", 10, 0)
oled.text("Temp : {:.1f} C".format(temp), 0, 18)
oled.text("Hum : {:.1f} %".format(hum), 0, 32)
oled.text("Light: {}".format(light), 0, 46)
oled.text(status, 30, 56)
oled.show()
# Main Loop
while True:
try:
# Read sensors
temperature, humidity, light = read_sensors()
# Get system status
status = get_status(temperature, light)
# Update outputs
update_led(status)
update_buzzer(status)
update_display(temperature, humidity, light, status)
# Terminal Output
print("[{:^10}] Temp: {:.1f}°C | Light: {}".format(
status,
temperature,
light
))
except Exception as e:
print("Error:", e)
oled.fill(0)
oled.text("Sensor Error", 0, 25)
oled.show()
red_led.off()
green_led.off()
blue_led.off()
buzzer.off()
time.sleep(2)