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
}
▶ RUN

Output/ Explanation:


Latest Current Affairs 2026 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Online MBA 2 years Online MCA Online BCA Best Website and Software Company in Allahabad