MQ2 Gas Sensor Interfacing Raspberry Pi

 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

Raspbery Pi
Raspberry Pi Pinout Diagram

Pinout Diagram of MQ-2 Sensor
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

  1. MQ2 sensor detects gas concentration
  2. Gas presence changes sensor resistance
  3. Module converts this to digital signal
  4. DO pin becomes LOW/HIGH based on threshold
  5. Raspberry Pi reads signal from GPIO17
  6. Gas detected → LED turns ON
  7. 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

  1. Import GPIO and time libraries
  2. Assign gas sensor to GPIO17
  3. Assign LED to GPIO18
  4. Set GPIO mode to BCM
  5. Set sensor as input
  6. Set LED as output
  7. Read sensor value
  8. If LOW → gas detected → LED ON
  9. Else → LED OFF
  10. 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.

തുടക്കക്കാർക്കായുള്ള ഇലക്ട്രോണിക്സ് ലളിതമായി പഠിക്കാം.

Empowering students in Kerala with hands-on technical skills.