Course Content
IoT Engineering Course using ESP32 with 12 Real-World Projects

📘 Lesson 10.2 – Gas Detection Code (Serial Monitor Version)

🎯 Objective of This Lesson

Students will learn:

  • How to read analog value from MQ3

  • How to display gas level on Serial Monitor

  • How to set a gas detection threshold

  • How to detect Gas Leak or Safe Condition


🔌 Hardware Reminder

MQ3 Pin ESP32 Pin
VCC 5V
GND GND
AO GPIO 34

🧾 Complete ESP32 Code (Copy–Paste Ready)

#define MQ3_PIN 34 // Analog pin connected to MQ3 AO

int gasValue = 0;
int threshold = 1200; // Adjust based on calibration

void setup() {
Serial.begin(115200);
pinMode(MQ3_PIN, INPUT);

Serial.println("Gas Leakage Detection System Started...");
Serial.println("Warming up sensor...");
delay(30000); // 30 seconds warm-up
Serial.println("Sensor Ready!");
}

void loop() {

gasValue = analogRead(MQ3_PIN);

Serial.print("Gas Sensor Value: ");
Serial.println(gasValue);

if (gasValue > threshold) {
Serial.println("⚠ GAS LEAK DETECTED!");
} else {
Serial.println("✅ Environment Safe");
}

Serial.println("----------------------------");
delay(1000);
}


🧠 Code Explanation (Step-by-Step)


1️⃣ Define Sensor Pin

 
#define MQ3_PIN 34
 

We connect MQ3 Analog Output (AO) to GPIO 34.

GPIO 34 supports ADC reading.


2️⃣ Threshold Value

 
int threshold = 1200;
 

This is the gas detection limit.

If sensor value becomes higher than this:

Gas leak is detected.

⚠ This value must be calibrated.


3️⃣ Serial Communication

 
Serial.begin(115200);
 

Starts communication between ESP32 and computer.

Used to display readings.


4️⃣ Warm-Up Time

 
delay(30000);
 

MQ3 needs heating time.

Without warm-up:

  • Readings will be unstable.


5️⃣ Reading Analog Value

 
gasValue = analogRead(MQ3_PIN);
 

ESP32 ADC range:

0 – 4095

Higher gas concentration → Higher value.


6️⃣ Gas Detection Logic

 
if (gasValue > threshold)
 

If value crosses threshold:

Print:

⚠ GAS LEAK DETECTED!

Otherwise:

Environment Safe.


📊 Example Serial Monitor Output

Clean air:

Gas Sensor Value: 350
Environment Safe

Mild alcohol vapor:

Gas Sensor Value: 1400
GAS LEAK DETECTED!


🔧 How to Calibrate Threshold Properly

Tell students to:

1️⃣ Upload code
2️⃣ Observe values in clean air
3️⃣ Note average value
4️⃣ Blow small alcohol vapor near sensor
5️⃣ Note new value
6️⃣ Set threshold between both values

Example:

Clean air → 400
Gas present → 1600

Set threshold = 1000


🎓 Learning Outcomes

After this lesson, students understand:

  • Analog sensor reading

  • Threshold logic

  • Serial debugging

  • Sensor calibration

  • Basic safety system programming



Scroll to Top