#include <ESP32Servo.h>
#define TRIGGER_PIN 12
#define ECHO_PIN 13
#define SERVO_PIN 4
#define BUTTON_PIN 14
#define PIR_PIN 14
#define LED_PIN_1 16
#define LED_PIN_2 5
Servo servo;
unsigned long servoStopTime = 0;
bool servoMoving = false;
bool led1On = false;
void setup() {
Serial.begin(9600);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(PIR_PIN, INPUT);
pinMode(LED_PIN_1, OUTPUT);
pinMode(LED_PIN_2, OUTPUT);
servo.attach(SERVO_PIN);
}
void loop() {
long duration, distance;
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGEER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration *0.034 / 2;
if (distance == 50 && !Servomoving){
servoMoving = true; // Set servo moving flag
for (int angle = 90; angle >= 0; angle--) {
servo.write(angle);
delay(15);
}
// Set the stop time for 5 seconds
servoStopTime = millis() + 5000;
}
// Check if the current time is less than servoStopTime
// If true, keep the servo at 0 degrees
if (servoMoving && millis() < servoStopTime) {
servo.write(0);
} else if (servoMoving) {
// After 5 seconds, return the servo to 90 degrees
servoMoving = false; // Reset servo moving flag
for (int angle = 0; angle <= 90; angle++) {
servo.write(angle);
delay(15);
}
}
// Check if the button is pressed
if (digitalRead(BUTTON_PIN) == LOW) {
// Turn on LED for 2 seconds
digitalWrite(LED_PIN_1, HIGH);
delay(2000);
digitalWrite(LED_PIN_1, LOW);
}
if (digitalRead(PIR_PIN)==HIGH) {
for (int i = 0 ; i < 4; i++) {
digitalWrite(LED_PIN_2, HIGH);
delay(500);
digitalWrite(LED_PIN_2, LOW);
delay(500);
}
}
}