import time
import json
import network
from machine import Pin, ADC, I2C, PWM
import ssd1306
# --------------------
# WiFi Setup
# --------------------
def connect_wifi():
print("Connecting to WiFi...")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST", "")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.5)
print("\nWiFi connected:", wlan.ifconfig())
connect_wifi()
# --------------------
# MQTT Setup
# --------------------
from umqtt.simple import MQTTClient
MQTT_BROKER = "broker.hivemq.com"
MQTT_PORT = 1883
MQTT_TOPIC = "52227124091/GasSensor"
CLIENT_ID = "clientId-533ZcZwoJp"
mqtt_client = MQTTClient(CLIENT_ID, MQTT_BROKER, port=MQTT_PORT)
mqtt_client.connect()
print("MQTT connected!")
last_mqtt = 0
MQTT_INTERVAL = 1 # seconds
def mqtt_publish(gas_value, alarm_state):
global last_mqtt
now = time.time()
if now - last_mqtt >= MQTT_INTERVAL:
payload = {
"gas_value": gas_value,
"alarm": alarm_state,
"timestamp": now
}
mqtt_client.publish(MQTT_TOPIC, json.dumps(payload))
print("MQTT Sent:", payload)
last_mqtt = now
# --------------------
# Pin Definitions
# --------------------
MQ2_PIN = 34
BUZZER_PIN = 15
BUTTON_PIN = 4
SERVO_PIN = 18 # Servo pin
SCL_PIN = 22
SDA_PIN = 21
# --------------------
# Hardware Setup
# --------------------
mq2 = ADC(Pin(MQ2_PIN))
mq2.atten(ADC.ATTN_11DB)
buzzer = Pin(BUZZER_PIN, Pin.OUT)
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP)
# --- Servo Motor Setup ---
servo = PWM(Pin(SERVO_PIN), freq=50)
def servo_angle(angle):
duty = int((angle / 180) * 102 + 26) # Convert angle to duty cycle
servo.duty(duty)
servo_angle(0) # Start closed
# OLED Setup
i2c = I2C(0, scl=Pin(SCL_PIN), sda=Pin(SDA_PIN))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
GAS_THRESHOLD = 1800
reset_flag = False
def show_oled(line1, line2=""):
oled.fill(0)
oled.text(line1, 0, 10)
oled.text(line2, 0, 30)
oled.show()
# --------------------
# Main Loop
# --------------------
while True:
gas_value = mq2.read()
alarm_state = "OFF"
# --- Button only resets buzzer ---
if button.value() == 0:
reset_flag = True
buzzer.off() # Stop buzzer only
show_oled("RESET DONE", "Buzzer Off")
time.sleep(1)
# --- Gas detection ---
if gas_value > GAS_THRESHOLD:
if not reset_flag:
alarm_state = "ON"
servo_angle(90) # Open servo
buzzer.on()
show_oled("!!! GAS ALERT !!!", f"Gas: {gas_value}")
time.sleep(0.3)
buzzer.off()
time.sleep(0.3)
else:
alarm_state = "MUTED"
servo_angle(90) # Keep OPEN
show_oled("GAS STILL HIGH", "Alarm Muted")
time.sleep(0.3)
else:
reset_flag = False
alarm_state = "SAFE"
buzzer.off()
servo_angle(0) # Close when safe
show_oled("Kitchen SAFE", f"Gas: {gas_value}")
time.sleep(0.3)
# Send MQTT
mqtt_publish(gas_value, alarm_state)