import machine
import time
gas_sensor = machine.ADC(26)
buzzer = machine.Pin(15, machine.Pin.OUT)
stepper_1a_plus = machine.Pin(10, machine.Pin.OUT)
stepper_1a_minus = machine.Pin(11, machine.Pin.OUT)
stepper_1b_plus = machine.Pin(12, machine.Pin.OUT)
stepper_1b_minus = machine.Pin(13, machine.Pin.OUT)
led = machine.Pin(25, machine.Pin.OUT)
GAS_THRESHOLD = 20000
SENSOR_READING_INTERVAL = 0.5
STEPPER_STEP_DELAY = 0.002
bipolar_sequence = [
[1, 0, 1, 0], # Step 1
[0, 1, 1, 0], # Step 2
[0, 1, 0, 1], # Step 3
[1, 0, 0, 1] # Step 4
]
fan_running = False
buzzer_pwm = machine.PWM(buzzer)
buzzer_pwm.freq(1000)
buzzer_pwm.duty_u16(0)
def set_alarm(state):
"""Controls the buzzer."""
if state:
buzzer_pwm.duty_u16(32768)
else:
buzzer_pwm.duty_u16(0)
def control_fan(enable):
"""Starts or stops the stepper motor (fan)."""
global fan_running
if enable and not fan_running:
fan_running = True
elif not enable and fan_running:
stepper_1a_plus.value(0)
stepper_1a_minus.value(0)
stepper_1b_plus.value(0)
stepper_1b_minus.value(0)
fan_running = False
def step_motor():
"""Runs the stepper motor continuously when fan is ON."""
for _ in range(200):
for step in bipolar_sequence:
stepper_1a_plus.value(step[0])
stepper_1a_minus.value(step[1])
stepper_1b_plus.value(step[2])
stepper_1b_minus.value(step[3])
time.sleep(STEPPER_STEP_DELAY)
def read_gas_level():
"""Reads the MQ-2 gas sensor."""
return gas_sensor.read_u16()
def is_gas_level_critical(gas_level):
"""Checks if gas level exceeds the threshold."""
return gas_level > GAS_THRESHOLD
print("Gas Detection System Starting...")
print("Warming up MQ2 sensor...")
time.sleep(5)
print("System ready!")
try:
while True:
gas_level = read_gas_level()
print("Gas Level:", gas_level)
if is_gas_level_critical(gas_level):
led.value(1)
set_alarm(1)
control_fan(True)
if fan_running:
step_motor()
else:
led.value(0)
set_alarm(0)
control_fan(False)
time.sleep(SENSOR_READING_INTERVAL)
except KeyboardInterrupt:
set_alarm(0)
control_fan(False)
led.value(0)
print("System stopped.")