from machine import Pin, ADC, PWM
from time import sleep
# MQ2 Gas Sensor (Analog Read)
mq2_sensor = ADC(26) # MQ2 connected to GP26 (ADC0)
THRESHOLD = 20000 # Gas threshold value
# Buzzer (PWM for sound)
buzzer = PWM(Pin(15)) # Buzzer connected to GP15
buzzer.freq(2000) # Set frequency to 2kHz
# Stepper Motor (Exhaust Fan) - Bipolar 4-wire
step_pins = [Pin(16, Pin.OUT), Pin(17, Pin.OUT), Pin(18, Pin.OUT), Pin(19, Pin.OUT)]
# Stepper Motor Sequence (Half Step Mode)
step_sequence = [
[1, 0, 0, 1],
[1, 0, 0, 0],
[1, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]
]
def step_motor(direction=1, steps=100):
""" Function to move the stepper motor """
for _ in range(steps):
for step in step_sequence[::direction]:
for pin, val in zip(step_pins, step):
pin.value(val)
sleep(0.002) # Small delay for smooth movement
def stop_motor():
""" Function to stop the stepper motor """
for pin in step_pins:
pin.value(0) # Set all motor pins LOW to stop it
# Main loop
while True:
gas_level = mq2_sensor.read_u16() # Read gas level (0 - 65535)
print(f"Gas Level: {gas_level}") # Debugging
if gas_level > THRESHOLD:
print("⚠️ Gas Leak Detected! Turning ON Fan & Alarm!")
buzzer.duty_u16(30000) # Activate buzzer
step_motor(direction=1, steps=200) # Run fan in forward direction
else:
print("✅ Safe Environment! Turning OFF Fan & Alarm!")
buzzer.duty_u16(0) # Turn off buzzer
stop_motor() # STOP the motor completely
sleep(1) # Wait before next reading