// Define Pin Allocations
const int gasSensorPin = A0; // MQ2 Analog pin
const int greenLedPin = 2; // Safe Status LED
const int redLedPin = 3; // Alarm Status LED
const int buzzerPin = 4; // Piezo Alarm
// Set the gas threshold limit
// In Wokwi, default clean air sits around 300.
const int gasThreshold = 400;
void setup() {
// Initialize digital pins as outputs
pinMode(greenLedPin, OUTPUT);
pinMode(redLedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// Set the gas pin as input
pinMode(gasSensorPin, INPUT);
// Initialize the Serial Monitor
Serial.begin(9600);
Serial.println("--- MQ2 Gas Detection System Active ---");
}
void loop() {
// Read the analog value from the MQ2 sensor
int gasValue = analogRead(gasSensorPin);
// Print value to screen so you can find your ideal threshold
Serial.print("Current Gas Level: ");
Serial.println(gasValue);
// Check if gas levels cross the danger zone
if (gasValue > gasThreshold) {
// DANGER: Gas Detected!
digitalWrite(greenLedPin, LOW); // Turn off green
digitalWrite(redLedPin, HIGH); // Turn on red
// Play a distinct 1000Hz frequency alarm sound
tone(buzzerPin, 1000);
Serial.println("[ALERT] Gas Leak Detected! Alarm sounding!");
}
else {
// SAFE: Normal Environment
digitalWrite(greenLedPin, HIGH); // Green stays on
digitalWrite(redLedPin, LOW); // Red stays off
// Silence the alarm
noTone(buzzerPin);
}
// Wait 300ms before reading again
delay(300);
}