from machine import ADC, Pin
import time
# --- MQ-2 Pins ---
mq2_analog = ADC(26) # GP26 = AO (analog output)
mq2_digital = Pin(15, Pin.IN) # GP15 = DO (digital output)
# --- Buzzer Pin ---
buzzer = Pin(14, Pin.OUT) # GP14 for buzzer
# Function to read analog gas level
def read_gas():
raw_value = mq2_analog.read_u16() # 0-65535
voltage = raw_value * 3.3 / 65535 # Convert to voltage
return raw_value, voltage
# Main loop
while True:
raw, volt = read_gas()
# Simple analysis thresholds (adjust as needed)
if raw < 20000:
gas_level = "Low"
buzzer.value(0) # Turn OFF buzzer
elif raw < 40000:
gas_level = "Medium"
buzzer.value(0) # Turn OFF buzzer
else:
gas_level = "High"
buzzer.value(1) # Turn ON buzzer
# Digital alert (optional display)
alert = "🚨 Gas above threshold!" if mq2_digital.value() == 1 else "Safe"
# Print status
print(f"Raw: {raw}, Voltage: {volt:.2f} V, Gas Level: {gas_level}, Alert: {alert}")
time.sleep(1)