#include<Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <Servo.h>
#define trig_pin 3
#define echo_pin 4
int led = 11;
int buzer = 10;
#define dht_pin 9
#define dht_type DHT22
DHT dht(dht_pin, dht_type);
Servo myServo;
#define PIR_pin 2
#define smoke_pin A0 // If this is analog input
LiquidCrystal_I2C lcd(0x27, 16, 2);
long distance;
int duration;
// Threshold for smoke/gas detection (adjust based on your sensor)
#define SMOKE_THRESHOLD 300
void setup() {
myServo.attach(5);
pinMode(led, OUTPUT);
pinMode(buzer, OUTPUT);
pinMode(PIR_pin, INPUT);
// Note: smoke_pin is analog, so no pinMode needed for analog input
pinMode(trig_pin, OUTPUT);
pinMode(echo_pin, INPUT);
Serial.begin(9600);
dht.begin();
// Initialize LCD properly
lcd.init();
lcd.backlight();
// Welcome message
lcd.setCursor(0, 0);
lcd.print("System Starting");
delay(1000);
lcd.clear();
}
void loop() {
// Clear LCD at beginning of each loop
lcd.clear();
// Read DHT sensor
float temp = dht.readTemperature();
float humidity = dht.readHumidity();
// Check if DHT readings are valid
if (isnan(temp) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
lcd.setCursor(0, 0);
lcd.print("DHT Error!");
} else {
Serial.print("Temperature: ");
Serial.print(temp);
Serial.print("°C Humidity: ");
Serial.print(humidity);
Serial.println("%");
// Display on LCD (first line)
lcd.setCursor(0, 0);
lcd.print("T:");
lcd.print(temp, 1); // Display with 1 decimal
lcd.print("C H:");
lcd.print(humidity, 0); // Display without decimals
lcd.print("%");
}
delay(500);
// Ultrasonic sensor reading
digitalWrite(trig_pin, LOW);
delayMicroseconds(2);
digitalWrite(trig_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trig_pin, LOW);
duration = pulseIn(echo_pin, HIGH);
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Display distance on LCD (second line)
lcd.setCursor(0, 1);
lcd.print("Dist:");
lcd.print(distance);
lcd.print("cm ");
// PIR motion sensor
int motion = digitalRead(PIR_pin);
if (motion == HIGH) {
Serial.println("Motion Detected!");
}
// Gas/smoke sensor - FIXED THIS PART
// Since smoke_pin is defined as A0 (analog pin), use analogRead
int gasValue = analogRead(smoke_pin);
Serial.print("Gas Level: ");
Serial.println(gasValue);
// Check if gas level exceeds threshold
if (gasValue > SMOKE_THRESHOLD) {
Serial.println("Gas Detected!");
tone(buzer, 1000);
// Display gas warning on LCD
lcd.setCursor(10, 1); // Position on second line
lcd.print("GAS!");
} else {
noTone(buzer);
}
// Distance-based control
if (distance < 10) {
digitalWrite(led, HIGH);
myServo.write(90);
Serial.println("Object detected - LED ON, Servo at 90°");
} else {
digitalWrite(led, LOW);
myServo.write(0);
}
delay(1000);
}