from machine import Pin, ADC, PWM
import time
# MQ2 Gas Sensor
gas_sensor = ADC(26) # MQ2 sensor connected to GP26 (ADC0)
ppm_threshold = 80 # Gas detection threshold in PPM
# Buzzer (Using PWM for continuous beep)
buzzer = PWM(Pin(15))
buzzer.freq(1000) # Set frequency to 1kHz (adjustable)
# Servo Motor (Fan)
servo = PWM(Pin(14)) # Servo on GP14
servo.freq(50) # 50Hz PWM frequency
def set_servo_angle(angle):
duty = int((angle / 180) * 6000 + 2000)
print(f"Setting servo to {angle}° (Duty: {duty})")
servo.duty_u16(duty)
time.sleep(0.5)
def convert_gas_value_to_ppm(analog_value):
return (analog_value / 65535) * 100 # Adjust scaling if needed
while True:
analog_value = gas_sensor.read_u16()
ppm_value = convert_gas_value_to_ppm(analog_value)
print(f"Raw ADC Value: {analog_value}, Gas Level: {ppm_value:.2f} PPM")
if ppm_value > ppm_threshold:
print("Gas detected! Turning ON fan and buzzer.")
buzzer.duty_u16(30000) # 50% duty cycle (ON)
set_servo_angle(90) # Move fan to 90 degrees
else:
print("Gas level normal. Turning OFF fan and buzzer.")
buzzer.duty_u16(0) # Stop buzzer (OFF)
set_servo_angle(0) # Reset fan position
time.sleep(1)