import network
from machine import Pin, ADC
from time import sleep
from blynk_simple import Blynk # use the simple library file
# ====== WiFi & Blynk Config ======
SSID = 'Wokwi-GUEST'
PASSWORD = ''
BLYNK_AUTH = "YdUCZuumhtQY60grWntlka3y3pqPQwgT"
# ====== Hardware Setup ======
pir = Pin(27, Pin.IN) # Motion sensor
mq2 = ADC(Pin(34)) # Gas sensor
mq2.atten(ADC.ATTN_11DB)
mq2.width(ADC.WIDTH_10BIT)
door = Pin(12, Pin.OUT) # Door relay
light = Pin(14, Pin.OUT) # Light controlled by Blynk switch (new)
# ====== Connect WiFi ======
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to WiFi...")
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
sleep(1)
print(".", end="")
print("\nā
WiFi connected:", wlan.ifconfig())
connect_wifi()
# ====== Initialize Blynk ======
blynk = Blynk(BLYNK_AUTH)
blynk.connect()
# ====== Main Loop ======
while True:
# --- Sensor readings ---
gas_value = mq2.read()
motion = pir.value() == 1
gas_alert = gas_value > 600
# --- Door control logic ---
if motion and gas_alert:
door.on()
blynk.virtual_write(0, "Door Open - Gas Alert!")
blynk.virtual_write(2, 1)
print(f"šØ Door Open | Gas: {gas_value}")
else:
door.off()
blynk.virtual_write(0, "Door Closed - Safe")
blynk.virtual_write(2, 0)
print(f"ā
Door Closed | Gas: {gas_value}")
# --- Send gas reading to Blynk ---
blynk.virtual_write(1, gas_value)
# --- Read Blynk Light Switch (V3) ---
light_state = blynk.virtual_read(3)
if light_state == "1":
light.on()
print("š” Light ON from Blynk")
elif light_state == "0":
light.off()
print("š” Light OFF from Blynk")
sleep(2)