#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define DHTPIN 2
#define DHTTYPE DHT22
#define trigPin 9
#define echoPin 8
#define pirPin 7
#define buzzer 6
#define ledPin 5
#define buttonPin 4
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2);
bool sensorActive = false;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(pirPin, INPUT);
pinMode(buzzer, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
lcd.init();
lcd.backlight();
dht.begin();
lcd.setCursor(0, 0);
lcd.print("Press button to");
lcd.setCursor(0, 1);
lcd.print("activate sensors");
}
void loop() {
// Check if button is pressed to toggle sensors on/off
if (digitalRead(buttonPin) == LOW) {
delay(300); // Debounce delay
sensorActive = !sensorActive;
lcd.clear();
if (sensorActive) {
lcd.setCursor(0, 0);
lcd.print("Sensors activated");
} else {
lcd.setCursor(0, 0);
lcd.print("Sensors deactivated");
noTone(buzzer); // Stop buzzer if active
digitalWrite(ledPin, LOW); // Turn off LED
}
}
if (sensorActive) {
// DHT22 Sensor: Temperature and Humidity
float temp = dht.readTemperature();
float hum = dht.readHumidity();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temp);
lcd.print(" C");
lcd.setCursor(0, 1);
lcd.print("Hum: ");
lcd.print(hum);
lcd.print(" %");
// Ultrasonic Sensor: Distance Measurement
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
if (distance < 50) {
digitalWrite(ledPin, HIGH); // Turn on LED if distance < 50 cm
} else {
digitalWrite(ledPin, LOW);
}
// PIR Sensor: Motion Detection
if (digitalRead(pirPin) == HIGH) {
tone(buzzer, 1000); // Sound buzzer if motion detected
} else {
noTone(buzzer); // Stop buzzer if no motion
}
delay(1000); // Delay for sensor readings
}
}