from machine import Pin, ADC, I2C, PWM
import time
import dht
import ssd1306
# ---------------- LEDs ----------------
leds = [
Pin(2, Pin.OUT),
Pin(3, Pin.OUT),
Pin(4, Pin.OUT),
Pin(5, Pin.OUT)
]
# ---------------- Buttons -------------
buttons = [
Pin(6, Pin.IN, Pin.PULL_UP),
Pin(7, Pin.IN, Pin.PULL_UP),
Pin(8, Pin.IN, Pin.PULL_UP),
Pin(9, Pin.IN, Pin.PULL_UP)
]
# ---------------- IR ------------------
ir = Pin(10, Pin.IN)
last_ir = 1
ir_value = 0
# ---------------- Buzzer --------------
buzzer = PWM(Pin(11))
buzzer.duty_u16(0)
# ---------------- Sensors -------------
gas = ADC(26)
dht22 = dht.DHT22(Pin(12))
# ---------------- OLED ----------------
i2c = I2C(0, scl=Pin(1), sda=Pin(0))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# ---------------- Functions -----------
def buzzer_on():
buzzer.freq(1000)
buzzer.duty_u16(30000)
def buzzer_off():
buzzer.duty_u16(0)
def read_ir():
global last_ir, ir_value
val = ir.value()
if last_ir == 1 and val == 0: # falling edge
ir_value += 1
if ir_value > 4:
ir_value = 1
time.sleep_ms(300)
last_ir = val
return ir_value
# ---------------- Main Loop -----------
while True:
# ---- Read DHT22 ----
try:
dht22.measure()
temp = dht22.temperature()
hum = dht22.humidity()
except:
temp = 0
hum = 0
# ---- Read Gas ----
gas_value = gas.read_u16() // 256
if gas_value > 150:
buzzer_on()
else:
buzzer_off()
# ---- IR Control (SIMULATED) ----
ir_btn = read_ir()
if ir_btn == 1:
leds[0].on()
elif ir_btn == 2:
leds[1].on()
elif ir_btn == 3:
leds[2].on()
elif ir_btn == 4:
leds[3].on()
# ---- Button OFF ----
for i in range(4):
if buttons[i].value() == 0:
leds[i].off()
# ---- OLED ----
oled.fill(0)
oled.text("HOME AUTOMATION", 0, 0)
oled.text("IR BTN: " + str(ir_btn), 0, 12)
oled.text("Temp: {} C".format(temp), 0, 24)
oled.text("Hum : {} %".format(hum), 0, 34)
oled.text("Gas : {}".format(gas_value), 0, 44)
oled.show()
time.sleep(0.2)