#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <Servo.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
const int PIR_PIN = 1;
const int LDR_PIN = A0;
const int LED_PIN = 3;
const int SERVO_PIN = 5; // Define the servo pin
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo myservo; // create servo object to control a servo
void setup() {
Serial.begin(9600);
dht.begin();
pinMode(PIR_PIN, INPUT);
pinMode(LDR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
lcd.init();
lcd.backlight();
lcd.clear();
myservo.attach(SERVO_PIN); // attaches the servo on SERVO_PIN to the servo object
}
void loop() {
// Read PIR sensor
int pirValue = digitalRead(PIR_PIN);
// Read LDR sensor
int ldrValue = analogRead(LDR_PIN);
// Read DHT sensor
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Display PIR and LDR values on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("PIR: ");
lcd.print(pirValue);
lcd.setCursor(0, 1);
lcd.print("LDR: ");
lcd.print(ldrValue);
// Control LED based on LDR value
if (ldrValue > 500) {
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
// Check if the temperature is above the threshold
if (temperature >= 30.0) {
// Rotate servo in one direction
for (int pos = 0; pos <= 180; pos += 1) {
myservo.write(pos);
delay(15);
}
// Rotate servo in the opposite direction
for (int pos = 180; pos >= 0; pos -= 1) {
myservo.write(pos);
delay(15);
}
} else {
// If the temperature is below 30 degrees, stop the servo
myservo.write(90); // Stop the servo by setting it to its neutral position
}
// Display humidity and temperature on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Humidity: ");
lcd.print(humidity);
lcd.print(" %");
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print(" C");
delay(2000);
}