from machine import Pin, PWM, ADC
import utime
mq2 = ADC(Pin(26))
buzzer = PWM(Pin(14))
buzzer.freq(1000)
stepper_pins = [Pin(16, Pin.OUT), Pin(17, Pin.OUT), Pin(18, Pin.OUT), Pin(19, Pin.OUT)]
# Step sequence for Bipolar Stepper Motor
stepper_seq = [
[1, 0, 1, 0],
[0, 1, 1, 0],
[0, 1, 0, 1],
[1, 0, 0, 1],
]
# Gas Threshold
THRESHOLD = 20000
def stepper_rotate(steps=256, delay=2):
""" Rotates stepper motor in forward direction """
for _ in range(steps):
for step in stepper_seq:
for pin, val in zip(stepper_pins, step):
pin.value(val)
utime.sleep_ms(delay)
def stepper_stop():
""" Stops the stepper motor """
for pin in stepper_pins:
pin.value(0)
def buzzer_beep(duration=1000):
""" Beeps buzzer for a given duration (supports active & passive buzzers) """
buzzer.duty_u16(30000) # ON
utime.sleep_ms(duration)
buzzer.duty_u16(0) # OFF
while True:
gas_level = mq2.read_u16()
print(f"Gas Level: {gas_level}")
if gas_level > THRESHOLD:
print("Gas detected! Activating alarm and exhaust fan.")
buzzer_beep(1000)
stepper_rotate(256, 2)
else:
print("Gas level normal.")
buzzer.duty_u16(0)
stepper_stop()
utime.sleep(1)