#include <DHTesp.h>
#include <ESP32Servo.h>
// Constants for DHT sensor
const int DHT_PIN = 15;
// Constants for photoresistor calibration
const float GAMMA = 0.7;
const float RL10 = 50;
// Constants for PIR sensor
const int LED_PIN = 5;
const int PIR_INPUT_PIN = 19;
int pirState = LOW; // Variable to store the current state of PIR sensor
// Define the pin connected to the photoresistor
const int PHOTO_RESISTOR_PIN = 2; // Adjust according to your setup
// Define servo related constants
#define ServoPin (33)
#define vrPin (34)
unsigned int ADCmin = 0;
unsigned int ADCmax = 4095;
unsigned int POSmin = 0;
unsigned int POSmax = 180;
#define ADC analogRead(vrPin)
// Creating an instance of the DHTesp class
DHTesp dhtSensor;
Servo myServo;
void setup() {
// Initializing serial communication
Serial.begin(115200);
// Configuring the DHT sensor
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// Set pinMode for LED, PIR sensor, and photoresistor pin
pinMode(LED_PIN, OUTPUT);
pinMode(PIR_INPUT_PIN, INPUT);
// Attaching the servo to its pin
myServo.attach(ServoPin);
}
void loop() {
// Reading temperature and humidity from DHT sensor
TempAndHumidity data = dhtSensor.getTempAndHumidity();
// Printing temperature and humidity
Serial.print("Temperature: ");
Serial.print(data.temperature, 2); // Two decimal places for temperature
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(data.humidity, 1); // One decimal place for humidity
Serial.println("%");
// Reading analog value from photoresistor pin
int analogValue = analogRead(PHOTO_RESISTOR_PIN);
// Convert analog value to voltage (assuming 12-bit ADC and 3.3V reference)
float voltage = analogValue / 4095.0 * 3.3;
// Calculate resistance of the photoresistor using voltage divider formula
float resistance = 2000 * voltage / (3.3 - voltage);
// Calculate lux using the resistance and predefined calibration values
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
// Print the lux value
Serial.print("Lux: ");
Serial.println(lux / 10);
// Reading state of PIR sensor
const int PIR_STATE = digitalRead(PIR_INPUT_PIN);
if (PIR_STATE == HIGH) {
digitalWrite(LED_PIN, HIGH);
if (pirState == LOW) {
Serial.println("Motion detected!");
pirState = HIGH;
}
delay(1000);
} else {
digitalWrite(LED_PIN, LOW);
if (pirState == HIGH) {
Serial.println("Motion ended!");
pirState = LOW;
}
delay(1000);
}
// Servo control based on potentiometer input
int pos = map(ADC ,ADCmin ,ADCmax ,POSmin ,POSmax);
myServo.write(pos);
}