#include <ServoESP32.h>
#define TRIGGER_PIN 0 // Replace with your actual trigger pin number
#define ECHO_PIN 21 // Replace with your actual echo pin number
#define LED_PIN 27 // Replace with your LED pin number
#define SERVO_PIN 4 // Replace with your servo pin number
ServoESP32 myservo;
long duration, distance;
void setup() {
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(SERVO_PIN, OUTPUT);
myservo.attach(SERVO_PIN);
myservo.write(90); // Initialize servo to the middle position
}
void loop() {
// Ultrasonic sensor
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; // Calculate distance in centimeters
// LED control
if (distance < 10) {
digitalWrite(LED_PIN, HIGH); // Turn on LED when an object is close
} else {
digitalWrite(LED_PIN, LOW); // Turn off LED when no object is close
}
// Servo motor control
int servoAngle = map(distance, 2, 200, 0, 180); // Map distance to servo angle
myservo.write(servoAngle);
delay(100); // Adjust this delay based on your project requirements
}