import machine
import dht
import time
from machine import Pin, ADC, I2C
import ssd1306
# --- Configuration ---
# I2C for OLED (128x64)
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
oled.invert(1)
# Sensors
dht_sensor = dht.DHT22(Pin(15))
gas_sensor = ADC(Pin(35))
pot = ADC(Pin(34))
# Outputs
relay = Pin(18, Pin.OUT)
buzzer = Pin(19, Pin.OUT)
led = Pin(5, Pin.OUT)
# ADC Setup (Read 0-3.3V)
gas_sensor.atten(ADC.ATTN_11DB)
pot.atten(ADC.ATTN_11DB)
def update_display(temp, hum, gas, pot):
oled.fill(0)
oled.text("Env Monitor", 0, 0)
oled.text("Temp : {} C".format(temp), 0, 16)
oled.text("Hum : {} %".format(hum), 0, 24)
oled.text("Gas : {}".format(gas), 0, 32)
oled.text("Pot : {}".format(pot), 0, 40)
oled.show()
while True:
try:
try:
# Read DHT22
dht_sensor.measure()
t = dht_sensor.temperature()
h = dht_sensor.humidity()
# Read Analog sensors
gas_val = gas_sensor.read()
pot_val = pot.read()
# Logic: If gas is high or temp > 30C, trigger alarm
if gas_val > 2000 or t > 30:
relay.value(1)
buzzer.value(1)
led.value(1)
else:
relay.value(0)
buzzer.value(0)
led.value(0)
update_display(t, h, gas_val, pot_val)
except OSError as e:
print("Failed to read sensor.")
time.sleep(2)
except KeyboardInterrupt as e:
print("Klavye kesmesiyle çıkış yapıldı.")