// imports
#include <DHTesp.h>
#include <ESP32Servo.h>
// define pins
#define LDR_PIN 13
#define LED_PIN 23
#define DHT_PIN 26
#define SERVO_PIN 15
#define MOTION_PIN 2
#define MOTION_LED 22
#define BUZZER_PIN 21
// define base variables for modules
int mov_state = LOW;
int val = 0;
int ldr_value = 0;
int ldr_threshold = 2045;
// object for DHT22
DHTesp dhtSensor;
// object for servo
Servo servo;
// setup
void setup() {
// brightness
pinMode(LDR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
// temp sensor
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// servo
servo.attach(SERVO_PIN, 500, 2400);
// motion sensor
pinMode(MOTION_PIN, INPUT);
pinMode(MOTION_LED, OUTPUT);
// buzzer
pinMode(BUZZER_PIN, OUTPUT);
}
// main loop
void loop() {
Serial.begin(9600);
readLight();
readTemp();
motionSensor();
delay(100);
}
// reads the brightness and writes to LED
void readLight(){
ldr_value = analogRead(LDR_PIN); // read the value from the sensor
Serial.println(ldr_value);
// if light not present
if (ldr_value > ldr_threshold) {
digitalWrite(LED_PIN, HIGH);
}
// if light present
else{
digitalWrite(LED_PIN, LOW);
}
}
// reads temperature and writes to servo
void readTemp(){
TempAndHumidity data = dhtSensor.getTempAndHumidity();
float temp = data.temperature;
if (temp >= 25){
servo.write(270);
delay(15);
} else{
servo.write(90);
delay(15);
}
}
// detects motion and activates an LED and a buzzer
void motionSensor(){
val = digitalRead(MOTION_PIN);
if (val == HIGH) { // if motion is detected
digitalWrite(MOTION_LED, HIGH); // activate LED
digitalWrite(BUZZER_PIN, HIGH); // enable buzzer
if (mov_state == LOW) {
mov_state = HIGH;
}
} else {
digitalWrite(MOTION_LED, LOW);
digitalWrite(BUZZER_PIN, LOW);
if (mov_state == HIGH) {
mov_state = LOW;
}
}
}