#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
const int dhtPin = 15;
const int trigPin = 5;
const int echoPin = 18;
const int ledPin = 4;
const int buzzerPin = 2;
const int pirPin = 34;
#define DHTTYPE DHT22
LiquidCrystal_I2C lcd(0x27, 16, 2);
DHT dht(dhtPin, DHTTYPE);
unsigned long lastChange = 0;
byte screen = 0;
int getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
return duration * 0.034 / 2;
}
void showLCD(int distance, float temp, float hum, int motion) {
if (millis() - lastChange >= 2000) {
lastChange = millis();
screen++;
if (screen > 3) {
screen = 0;
}
lcd.clear();
}
if (screen == 0) {
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temp, 1);
lcd.print(" C");
} else if (screen == 1) {
lcd.setCursor(0, 0);
lcd.print("Hum : ");
lcd.print(hum, 0);
lcd.print(" %");
} else if (screen == 2) {
lcd.setCursor(0, 0);
lcd.print("Dist: ");
lcd.print(distance);
lcd.print(" cm");
} else {
lcd.setCursor(0, 0);
if (motion == HIGH)
lcd.print("Motion: YES");
else
lcd.print("Motion: NO");
}
}
void setup() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
dht.begin();
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(pirPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
digitalWrite(ledPin, LOW);
noTone(buzzerPin);
}
void loop() {
float temp = dht.readTemperature();
float hum = dht.readHumidity();
int distance = getDistance();
int motion = digitalRead(pirPin);
if (distance <= 20 || distance >= 399 || motion == HIGH) {
digitalWrite(ledPin, HIGH);
tone(buzzerPin, 1000);
} else {
digitalWrite(ledPin, LOW);
noTone(buzzerPin);
}
showLCD(distance, temp, hum, motion);
Serial.print("Temperature: ");
Serial.print(temp);
Serial.println(" C");
Serial.print("Humidity: ");
Serial.print(hum);
Serial.println(" %");
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
Serial.print("Motion: ");
if (motion == HIGH)
Serial.println("Detected");
else
Serial.println("No Motion");
Serial.println("----------------------");
delay(500);
}