Programming Examples

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


O level January 2025 practical Exam question

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
}
Output


Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2026 Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Best Website and Software Company in Allahabad