Programming Examples
Write a program to interface a gas sensor (MQ-2) and a buzzer.

Write a program to interface a gas sensor (MQ-2) and a buzzer. The buzzer should sound an alarm if the gas concentration exceeds a threshold value. Display the gas concentration on the serial monitor.
Solution#define MQ2_PIN A5 // MQ-2 analog output pin
#define BUZZER_PIN 10 // Buzzer connected to digital pin 8
int threshold = 300; // Gas threshold value (adjust as needed)
void setup() {
pinMode(BUZZER_PIN, OUTPUT);
Serial.begin(9600); // Start serial communication
}
void loop() {
int gasValue = analogRead(MQ2_PIN); // Read gas sensor value
Serial.print("Gas Concentration: ");
Serial.println(gasValue); // Display gas level
if (gasValue > threshold) {
digitalWrite(BUZZER_PIN, HIGH); // Turn ON buzzer
Serial.println(" Gas level HIGH! Alarm activated!");
} else {
digitalWrite(BUZZER_PIN, LOW); // Turn OFF buzzer
}
delay(1000); // Wait 1 second before next reading
}
▶ RUN Output/ Explanation: 