#include <ESP32Servo.h>
#include "DHT.h"
Servo myservo;
int pos = 0;
int servoPin = 13;
int Dht_Pin = 22;
int pirPin = 12; // PIR motion sensor pin
int pirState = LOW; // Current state of PIR (LOW = no motion, HIGH = motion detected)
#define Dht_Type DHT22
DHT dht(Dht_Pin, Dht_Type);
// Function to calculate the servo angle based on temperature
int calculateFanSpeed(float temp) {
if (temp < 25.0) {
return 0; // Fan off (0° servo angle)
} else if (temp >= 25.0 && temp < 30.0) {
return 90; // Medium speed (180° servo angle)
} else {
return 180; // High speed (180° servo angle)
}
}
// Function to move the servo gradually to a target position
void moveServoSmoothly(int startPos, int targetPos, int speedDelay) {
if (startPos < targetPos) {
for (int pos = startPos; pos <= targetPos; pos++) {
myservo.write(pos);
delay(speedDelay);
}
} else {
for (int pos = startPos; pos >= targetPos; pos--) {
myservo.write(pos);
delay(speedDelay);
}
}
}
// Add this function to stop the servo when no motion is detected
void stopServo() {
myservo.write(0); // Move servo to "off" position
pos = 0; // Update position variable to reflect servo state
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
ESP32PWM:: allocateTimer (0);
ESP32PWM:: allocateTimer (1);
ESP32PWM:: allocateTimer (2);
ESP32PWM:: allocateTimer (3);
myservo.setPeriodHertz (50);
myservo.attach(servoPin, 500, 2400);
myservo.write(0);
dht.begin();
pinMode(12, INPUT); // Set PIR pin as input
}
void loop() {
//PIR motion detected logic
int motionDetected = digitalRead(pirPin);
if (motionDetected == HIGH) {
if (pirState == LOW) {
Serial.println("Motion detected! Overriding servo control.");
pirState = HIGH;
}
// Read temperature from the DHT sensor
float temp = dht.readTemperature();
// Check if the temperature reading is valid
if (isnan(temp)) {
Serial.println("Failed to read from DHT sensor!");
delay(1000); // Wait before retrying
return;
}
// Log the temperature value
Serial.print("Temperature Value = ");
Serial.println(temp);
// Calculate the servo target angle based on the temperature
int targetAngle = calculateFanSpeed(temp);
// Determine speed delay based on temperature
int speedDelay;
if (temp < 25.0) {
speedDelay = 50; // Slow transition (Fan off)
} else if (temp >= 25.0 && temp < 30.0) {
speedDelay = 30; // Medium speed transition
} else {
speedDelay = 5; // Fast transition (Fan high speed)
}
// Smoothly move the servo to the target angle
moveServoSmoothly(pos, targetAngle, speedDelay);
// Update current position
pos = targetAngle;
// Log the servo position
Serial.print("Servo Angle Set To = ");
Serial.println(targetAngle);
} else {
if (pirState == HIGH) {
Serial.println("No motion detected. Turning off servo.");
pirState = LOW;
stopServo(); // Turn off servo when motion stops
}
}
// Delay before the next loop iteration
delay(1000);
}