from machine import Pin, ADC, PWM
import time
# Configure the MQ2 gas sensor
mq2_sensor = ADC(26) # Connect MQ2 analog output to GPIO 26 (ADC0)
# Configure the buzzer
buzzer = PWM(Pin(15)) # Connect buzzer to GPIO 15
buzzer.freq(440) # Set frequency to 440 Hz (A4 note)
buzzer.duty_u16(0) # Initially off
# Configure stepper motor pins (for a standard 4-pin bipolar stepper)
in1 = Pin(16, Pin.OUT)
in2 = Pin(17, Pin.OUT)
in3 = Pin(18, Pin.OUT)
in4 = Pin(19, Pin.OUT)
# Stepper motor sequence (full step sequence)
step_sequence = [
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
]
# Define LED pin for status indication
status_led = Pin(25, Pin.OUT) # Built-in LED on Pi Pico
# Set the gas threshold level (adjust this value based on your sensor calibration)
# MQ2 sensor returns values from 0-65535 (16-bit ADC)
GAS_THRESHOLD = 27000 # This is an example threshold, needs calibration
# Variables to track system state
fan_running = False
def set_stepper_step(step):
"""Set the stepper motor pins according to the sequence step"""
in1.value(step_sequence[step][0])
in2.value(step_sequence[step][1])
in3.value(step_sequence[step][2])
in4.value(step_sequence[step][3])
def stepper_stop():
"""Turn off all stepper motor pins to stop it and save power"""
in1.value(0)
in2.value(0)
in3.value(0)
in4.value(0)
def start_fan():
"""Start the stepper motor as an exhaust fan"""
global fan_running
fan_running = True
print("Starting exhaust fan")
def stop_fan():
"""Stop the stepper motor"""
global fan_running
fan_running = False
stepper_stop()
print("Stopping exhaust fan")
def start_alarm():
"""Turn on the buzzer alarm"""
buzzer.duty_u16(32768) # 50% duty cycle
print("Alarm ON")
def stop_alarm():
"""Turn off the buzzer alarm"""
buzzer.duty_u16(0) # 0% duty cycle
print("Alarm OFF")
def read_gas_level():
"""Read the gas level from MQ2 sensor"""
# Read raw analog value (0-65535)
raw_value = mq2_sensor.read_u16()
print(f"Gas level: {raw_value}")
return raw_value
print("Gas Detection System Starting...")
print(f"Gas threshold set to: {GAS_THRESHOLD}")
try:
step_count = 0
while True:
# Read the current gas level
gas_level = read_gas_level()
# Check if gas level is above threshold
if gas_level > GAS_THRESHOLD:
# Gas level is high, activate alarm and fan
status_led.value(1) # Turn on status LED
if not fan_running:
start_fan()
start_alarm()
# Only run the stepper if fan should be running
if fan_running:
# Move stepper motor one step
set_stepper_step(step_count % 4)
step_count += 1
else:
# Gas level is normal, deactivate alarm and fan
status_led.value(0) # Turn off status LED
if fan_running:
stop_fan()
stop_alarm()
# Short delay
time.sleep(1)
except KeyboardInterrupt:
# Clean shutdown
stepper_stop()
stop_alarm()
print("System stopped")