import network
from machine import Pin, ADC
from time import sleep
from dht import DHT11
import BlynkLib
# ==============================
# š¹ WiFi + Blynk Setup
# ==============================
SSID = "Wokwi-GUEST"
PASSWORD = ""
BLYNK_AUTH = "EsnQrr405mSSeflKTfa13MGF4qlQK-4K" # Your token
print("Connecting to WiFi...")
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(SSID, PASSWORD)
while not wifi.isconnected():
print(".", end="")
sleep(1)
print("\nā
WiFi Connected! IP:", wifi.ifconfig()[0])
blynk = BlynkLib.Blynk(BLYNK_AUTH)
# ==============================
# š¹ Sensor + Pin Setup
# ==============================
mq2 = ADC(Pin(34)) # Gas sensor
mq2.atten(ADC.ATTN_11DB)
mq2.width(ADC.WIDTH_10BIT)
pir = Pin(27, Pin.IN) # Motion sensor
dht_sensor = DHT11(Pin(25)) # DHT11 temperature & humidity
door_led = Pin(12, Pin.OUT) # Red LED for alert
light_led = Pin(14, Pin.OUT) # Light control from Blynk
buzzer = Pin(26, Pin.OUT) # Buzzer alert
# Default gas threshold
gas_threshold = 400
# ==============================
# š¹ Virtual Pin Handlers
# ==============================
@blynk.on("V5") # Light ON/OFF control from Blynk
def light_control(value):
if value[0] == '1':
light_led.on()
print("š” Light ON (from Blynk)")
else:
light_led.off()
print("š” Light OFF (from Blynk)")
@blynk.on("V6") # Gas threshold control from Blynk
def update_threshold(value):
global gas_threshold
gas_threshold = int(value[0])
print("š Gas threshold set to:", gas_threshold)
# ==============================
# š¹ Main Monitoring Loop
# ==============================
print("\nšØ Hazardous Zone Monitoring Started š\n")
while True:
blynk.run()
try:
# Read all sensors
gas_value = mq2.read()
motion = pir.value()
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
except Exception as e:
print("ā ļø Sensor read error:", e)
gas_value, motion, temperature, humidity = 0, 0, 0, 0
# --- Safety Condition Logic ---
alert = False
status = "ā
Safe"
if gas_value > gas_threshold:
alert = True
status = "ā ļø ALERT: Gas Level High!"
if motion:
alert = True
status = "ā ļø ALERT: Motion Detected!"
if motion and gas_value > gas_threshold:
status = "šØ CRITICAL: Gas Leak + Motion!"
# --- LED, Buzzer, and Blynk Alerts ---
if alert:
door_led.on() # Red LED ON
buzzer.on()
blynk.virtual_write(3, 255) # Motion LED ON
blynk.virtual_write(4, status)
else:
door_led.off()
buzzer.off()
blynk.virtual_write(3, 0) # Motion LED OFF
blynk.virtual_write(4, "šŖ Door Open - SAFE")
# --- Send Data to Blynk ---
blynk.virtual_write(0, gas_value) # Gas gauge
blynk.virtual_write(1, temperature) # Temperature gauge
blynk.virtual_write(2, humidity) # Humidity gauge
# --- Debug Info ---
print(f"Gas: {gas_value}, Temp: {temperature}°C, Humidity: {humidity}%, Motion: {motion}, Threshold: {gas_threshold}")
print("Status:", status)
print("===================================")
sleep(2)