#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// using I2C lcd so wiring easier
LiquidCrystal_I2C lcd(0x27, 16, 2);
// pins
int buzzer = 19;
int trigPin = 33;
int echoPin = 18; // changed from 34, more stable
int led = 15;
int pirPin = 13;
int gasPin = 34; // MQ-2
long duration;
int distance;
int gasValue;
bool motionDetected;
void setup() {
Serial.begin(9600); // for monitoring values
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzer, OUTPUT);
pinMode(led, OUTPUT);
pinMode(pirPin, INPUT);
pinMode(gasPin, INPUT);
lcd.init();
lcd.backlight();
}
void loop() {
// read all sensors first
motionDetected = digitalRead(pirPin); // check movement
gasValue = analogRead(gasPin); // gas level
// ultrasonic part to get distance
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2; // convert to cm
// print everything in one line so easier to see
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm | Gas Value: ");
Serial.print(gasValue);
Serial.print(" | Motion: ");
if (motionDetected == HIGH) {
Serial.println("Detected");
} else {
Serial.println("No Motion");
}
// priority logic, gas first cause most dangerous
if (gasValue > 2000) {
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Gas Leak!");
digitalWrite(buzzer, HIGH);
digitalWrite(led, HIGH);
}
// then motion
else if (motionDetected == HIGH) {
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Motion Detected");
// buzzer + led for few seconds
for (int i = 0; i < 5; i++) {
digitalWrite(buzzer, HIGH);
digitalWrite(led, HIGH);
delay(500);
digitalWrite(led, LOW);
delay(500);
}
digitalWrite(buzzer, LOW);
}
// then obstacle
else if (distance < 200) {
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Obstacle:");
lcd.setCursor(0,1);
lcd.print(distance);
lcd.print(" cm");
digitalWrite(led, HIGH);
digitalWrite(buzzer, LOW);
}
// nothing happening
else {
lcd.clear();
lcd.setCursor(0,0);
lcd.print("System Normal");
digitalWrite(led, LOW);
digitalWrite(buzzer, LOW);
}
delay(500); // small delay so not too fast
}