#include <ESP32Servo.h>
// Define pins
const int trigPin = 14;
const int echoPin = 12;
const int ledPin = 13;
Servo myServo;
// Variables for distance measurement
long duration;
int distance;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
// Attach the servo to pin 11
myServo.attach(15);
}
void loop() {
// Sweep the servo from 0 to 180 degrees
for (int pos = 0; pos <= 180; pos += 1) {
myServo.write(pos);
delay(15);
measureDistance();
}
// Sweep the servo from 180 to 0 degrees
for (int pos = 180; pos >= 0; pos -= 1) {
myServo.write(pos);
delay(15);
measureDistance();
}
}
void measureDistance() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin on HIGH state for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = duration * 0.034 / 2;
// Print the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// Turn on the LED if an object is within 50 cm
if (distance < 50) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}