Project 3.1.16: Methane Leak Detector
Advanced Embedded Systems Project Using Raspberry Pi Pico 2 W and MicroPython
Overview
The Pico reads an MQ-4 style methane sensor and raises graded local alerts when the gas level rises above calibrated thresholds.
Methane leaks around waste sites, pits, and enclosed service areas can create explosion and health risks if they are not noticed early.
A Pico 2 W prototype with a methane gas sensor, LED, buzzer, and analog threshold logic.
Sensor warm-up, methane threshold calibration, and honest discussion of non-certified gas safety measurements.
Required Components
![]() Raspberry Pi Pico 2 W |
![]() Buzzer |
![]() Breadboard |
![]() Jumper wires |
![]() LED |
![]() Resistor |
![]() Gas Sensor |
Circuit Connections
| Component terminal | Connect to | Pico physical pin | Notes |
|---|---|---|---|
| MQ-4 VCC | Module-rated supply | Often external 5V | Check the board label |
| MQ-4 GND | GND | Physical pin 38 | Common ground |
| MQ-4 AO | Voltage-divider midpoint to GPIO 26 | GPIO 26 / physical pin 31 | Do not connect a 5V analog output directly |
| LED anode | 220 ohm resistor to GPIO 15 | GPIO 15 / physical pin 20 | Warning LED |
| Buzzer positive | GPIO 16 | GPIO 16 / physical pin 21 | Critical alarm |
Wiring Diagram

MQ-4 AO -> resistor divider -> GPIO 26
GND -> MQ-4 GND, LED cathode, buzzer negative
GPIO 15 -> 220 ohm resistor -> LED anode
GPIO 16 -> buzzer positive
External supply -> MQ-4 heater power if required
Step-by-Step Assembly
- Power the MQ-4 sensor according to its board label and connect its ground to Pico GND.
- Build a resistor divider on the analog output before connecting the midpoint to GPIO 26.
- Connect the LED to GPIO 15 through a 220 ohm resistor and the LED cathode to GND.
- Connect the buzzer positive pin to GPIO 16 and its negative pin to GND.
- Place the sensor in a ventilated test area and allow warm-up before calibration.
Testing Individual Components
Before running the full project, test each subsystem separately. This makes it easier to find wiring, library, or logic problems before full integration.
- Hardware setup: Assemble the Pico, sensor, indicator, and load wiring exactly as shown in the connection table before applying power.
- Test the input sensor: Read baseline methane values for several minutes after warm-up so the thresholds come from real room conditions.
- Test the output device: Test the LED and buzzer outputs separately before linking them to gas thresholds.
- Test the decision logic: Confirm the warning stage appears before the critical stage as the reading rises.
- Run the full system: Run the full system and compare raw values with the reported state labels.
- Validate the prototype: Repeat tests in different airflow conditions to see how the baseline and stability change.
- Save the project: Save the validated program on the Pico as main.py and keep a copy on the computer for future edits.
Full Project Code
After completing and checking the circuit connections, open Thonny IDE, copy and paste this code into a new file or upload the project file to the Raspberry Pi Pico 2 W, then run it from Thonny.
from machine import ADC, Pin
import time
GAS_PIN = 26
LED_PIN = 15
BUZZER_PIN = 16
WARNING_LEVEL = 18000
CRITICAL_LEVEL = 30000
WARMUP_SECONDS = 60
gas = ADC(GAS_PIN)
led = Pin(LED_PIN, Pin.OUT)
buzzer = Pin(BUZZER_PIN, Pin.OUT)
def read_level(samples=10):
total = 0
for _ in range(samples):
total += gas.read_u16()
time.sleep_ms(20)
return total // samples
print("Warming methane sensor...")
for remaining in range(WARMUP_SECONDS, 0, -1):
print("Warm-up remaining:", remaining)
time.sleep(1)
print("Methane leak detector ready")
while True:
level = read_level()
if level >= CRITICAL_LEVEL:
status = "CRITICAL"
led.on()
buzzer.on()
elif level >= WARNING_LEVEL:
status = "WARNING"
led.on()
buzzer.off()
else:
status = "NORMAL"
led.off()
buzzer.off()
print("Methane level: {} | Status: {}".format(level, status))
time.sleep(2)
How the Code Works
| Code Section | What It Does | Why It Matters | What to Modify During Testing |
|---|---|---|---|
| Warm-up phase | Waits for the MQ-4 sensor to stabilize | Methane decisions are meaningless if the sensor heater has not settled | Increase WARMUP_SECONDS if your module needs a longer initial warm-up |
| read_level | Averages several analog samples into one gas level | Averaging reduces noise and makes threshold testing more reliable | Increase the sample count if the values still jump too much |
| Threshold logic | Separates NORMAL, WARNING, and CRITICAL methane states | Graded states are easier to validate and explain than a single alarm point | Tune WARNING_LEVEL and CRITICAL_LEVEL using real baseline data |
| Alert outputs | Uses LED for warning and both LED and buzzer for critical conditions | Students can see how one sensor can support multiple response levels | Keep the buzzer reserved for CRITICAL if classroom testing needs to stay manageable |
Expected Result
The serial monitor reports the current reading or state clearly.
The hardware output responds when the decision logic changes state.
Subsystem behavior matches the thresholds, timing, or rules described in the document.
Validation Checks
- Normal condition test: record the stable warm-room baseline with no deliberate gas source nearby
- Warning condition test: create a mild controlled change and confirm the LED turns on first
- Critical condition test: create a stronger controlled test condition and confirm the buzzer activates
- Calibration test: compare repeated baselines before locking in the final thresholds
- Limitation test: explain why the system is a prototype and not a certified methane safety instrument
Deployment and Limitations
- This prototype can be used for local warning demonstrations and early field trials
- Before deployment, it needs enclosure protection, calibration records, and a clear response procedure
- Alert systems should always be treated as decision-support tools unless they are certified for the application
Troubleshooting
| Problem | Possible Cause | Solution |
|---|---|---|
| Reading is always low or flat | The analog output or divider wiring is incorrect | Rebuild the divider and confirm the AO line reaches GPIO 26 |
| System is always in alarm | Thresholds are too low for the room baseline | Record the warm baseline and raise the thresholds accordingly |
| Values drift a lot | Sensor is not fully warmed or airflow is unstable | Extend warm-up time and test in a more stable airflow condition |
| Buzzer never sounds | Critical threshold is too high or the buzzer is miswired | Temporarily lower CRITICAL_LEVEL and verify the buzzer separately |






