from machine import Pin
import time
# ---------- Pin Configuration (matches diagram.json) ----------
gas_do = Pin(16, Pin.IN) # MQ2 digital output -> GP16
buzzer = Pin(15, Pin.OUT) # Buzzer -> GP15
step_pin = Pin(14, Pin.OUT) # A4988 STEP -> GP14
dir_pin = Pin(13, Pin.OUT) # A4988 DIR -> GP13
enable_pin = Pin(12, Pin.OUT) # A4988 ENABLE -> GP12 (active LOW)
# ---------- Initial state ----------
enable_pin.value(1) # 1 = disabled (A4988 ENABLE is active-LOW)
dir_pin.value(1) # fixed rotation direction
buzzer.value(0)
def motor_enable():
enable_pin.value(0) # LOW = driver enabled, coils energized
def motor_disable():
enable_pin.value(1) # HIGH = driver disabled, coils off (saves power)
def step_once(delay_us=800):
step_pin.value(1)
time.sleep_us(delay_us)
step_pin.value(0)
time.sleep_us(delay_us)
# ---------- Main Loop ----------
print("Gas Detection System Started")
while True:
gas_detected = gas_do.value() # 1 = gas above threshold, 0 = normal
# NOTE: if your buzzer/motor react backwards when you test in Wokwi,
# this polarity is inverted on some sensor builds -- just flip the
# condition below to "if gas_detected == 0:" instead.
if gas_detected == 1:
print("!! Gas level HIGH - Activating exhaust fan and alarm !!")
buzzer.value(1)
motor_enable()
for _ in range(20): # spin stepper while gas stays high
step_once()
else:
print("Gas level normal - System OFF")
buzzer.value(0)
motor_disable()
time.sleep_ms(100)