1. Introduction
The MQ2 gas sensor is used to detect gases like LPG, smoke, methane, and hydrogen. It provides both analog and digital outputs. This sensor is widely used in gas leakage detection and safety systems.
2. Components
- Raspberry Pi
- MQ2 Gas Sensor Module
- LED
- 220Ω Resistor
- Breadboard
- Jumper Wires
3. Circuit and connections
| Raspberry Pi Pinout Diagram |
| Pinout Diagram of MQ-2 Sensor |
Connections:
- VCC → 5V (Pin 2)
- GND → GND (Pin 6)
- DO → GPIO17 (Pin 11)
- LED + → GPIO18 (Pin 12)
- LED – → GND (via 220Ω resistor)
4. Detailed Step By Step Circuit working
- MQ2 sensor detects gas concentration
- Gas presence changes sensor resistance
- Module converts this to digital signal
- DO pin becomes LOW/HIGH based on threshold
- Raspberry Pi reads signal from GPIO17
- Gas detected → LED turns ON
- No gas → LED OFF
5. Libraries to be included
import RPi.GPIO as GPIO
import time
6. Code
import RPi.GPIO as GPIO
import time
gas = 17
led = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(gas, GPIO.IN)
GPIO.setup(led, GPIO.OUT)
while True:
if GPIO.input(gas) == 0: # Gas detected
GPIO.output(led, True)
print("Gas Detected!")
else:
GPIO.output(led, False)
time.sleep(0.1)
7. Detailed Step By Step Code working
- Import GPIO and time libraries
- Assign gas sensor to GPIO17
- Assign LED to GPIO18
- Set GPIO mode to BCM
- Set sensor as input
- Set LED as output
- Read sensor value
- If LOW → gas detected → LED ON
- Else → LED OFF
- Add delay for stability
8. Tips
- Allow sensor to warm up for 20–30 seconds
- Adjust sensitivity using onboard potentiometer
- Avoid placing near strong airflow
- Use proper ventilation while testing
9. Uses
- Gas leakage detection
- Fire safety systems
- Industrial safety monitoring
- Smart home alerts
10. Conclusion
The MQ2 gas sensor is an essential component for safety applications. It helps detect harmful gases and prevent accidents using Raspberry Pi.