ArduinoArduino UnoExact chip

Gas alarm (MQ-2)

The MQ-2’s level on A0, its alarm on pin 7; a buzzer sounds. Raise the gas.

Gas alarm (MQ-2) in Argynix Lab

The code

sketch.inoC++
// An MQ-2 gas sensor: AOUT on A0 for the level, DOUT on pin 7 for the alarm (LOW above
// its threshold). The buzzer on pin 8 sounds while it is. Raise the gas in the inspector.
const int ALARM = 7;
const int BUZZER = 8;

void setup() {
  pinMode(ALARM, INPUT);
  Serial.begin(9600);
}

void loop() {
  int level = analogRead(A0);
  bool gas = digitalRead(ALARM) == LOW;
  if (gas) tone(BUZZER, 2000);
  else noTone(BUZZER);
  Serial.print("gas:");
  Serial.println(level);
  delay(200);
}