#include <ESP32Servo.h>

const int TRIGGER_PIN = 4;    // Ultrasonic sensor trigger pin
const int ECHO_PIN = 5;       // Ultrasonic sensor echo pin
const int SERVO_PIN = 13;     // Servo motor pin
const int SERVO_ANGLE = 90;   // Servo angle to rotate

Servo myservo;

void setup() {
  Serial.begin(9600);
  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  myservo.attach(SERVO_PIN); // Attach servo to pin
}

void loop() {
  long duration, distance;
  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);
  duration = pulseIn(ECHO_PIN, HIGH);
  distance = duration * 0.034 / 2;

  if (distance <= 50) {
    myservo.write(SERVO_ANGLE); // Rotate servo to 90 degrees
    delay(500); // Wait for 5 seconds
  } else {
    myservo.write(0); // Return servo to original state
  }
}
Loading
esp32-devkit-c-v4