#include <LiquidCrystal.h>
#include <DHT.h>
// Pin assignments
const int ledPin = 5; // digital pin 5 for LED
const int ldrPin = A0; // analog pin 0 for LDR
const int buzzerPin = 6; // digital pin 6 for Buzzer
const int pirPin = 7; // digital pin 7 for PIR sensor
const int relayPin = 8; // digital pin 8 for Relay
const int dhtPin = 9; // digital pin 9 for DHT sensor
const int rs = 10, en = 11, d4 = 12, d5 = 13, d6 = 14, d7 = 15; // LCD pins
// Initialize the DHT sensor
#define DHTTYPE DHT11 // Define the type of DHT sensor used (DHT11 or DHT22)
DHT dht(dhtPin, DHTTYPE);
// Initialize the LCD library with the LCD pin numbers
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize pin modes
pinMode(ledPin, OUTPUT); // LED as output
pinMode(ldrPin, INPUT); // LDR as input
pinMode(buzzerPin, OUTPUT); // Buzzer as output
pinMode(pirPin, INPUT); // PIR sensor as input
pinMode(relayPin, OUTPUT); // Relay as output
// Initialize the LCD
lcd.begin(16, 2); // Set up the LCD's number of columns and rows
lcd.print("System Ready");
// Initialize the DHT sensor
dht.begin();
}
void loop() {
// Read the LDR sensor value
int ldrStatus = analogRead(ldrPin);
// Read the DHT sensor values
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Display temperature and humidity on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print(" C");
lcd.setCursor(0, 1);
lcd.print("Humidity: ");
lcd.print(humidity);
lcd.print(" %");
// Check if it's dark (LDR value <= 200)
if (ldrStatus <= 200) {
digitalWrite(ledPin, HIGH); // Turn on the LED
Serial.print("Darkness detected, turn on the LED: ");
Serial.println(ldrStatus);
// Read the PIR sensor value
int pirStatus = digitalRead(pirPin);
// Check if motion is detected
if (pirStatus == HIGH) {
tone(buzzerPin, 1000); // Emit a tone of 1000 Hz on the Buzzer
digitalWrite(relayPin, HIGH); // Activate the Relay
Serial.println("Motion detected, activating buzzer and relay");
} else {
noTone(buzzerPin); // Stop the tone on the Buzzer
digitalWrite(relayPin, LOW); // Deactivate the Relay
Serial.println("No motion detected, buzzer and relay off");
}
} else {
digitalWrite(ledPin, LOW); // Turn off the LED
Serial.print("Sufficient light detected, turn off the LED: ");
Serial.println(ldrStatus);
// Ensure the buzzer and relay are off
noTone(buzzerPin); // Stop the tone on the Buzzer
digitalWrite(relayPin, LOW);
}
delay(2000); // Wait a few seconds between measurements
}