#include <ESP32Servo.h>
Servo myservo; // create servo object to control a servo
const int trigPin = 16;
const int echoPin = 17;
long duration;
int distance;
void setup() {
myservo.attach(12); // attaches the servo on pin 8 to the servo object
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
if (distance < 10) {
// Rotate servo to 180 degrees in anti-clockwise direction
myservo.write(180);
} else if (distance > 10) {
// Rotate servo to 0 degrees for clockwise direction
myservo.write(0);
}
delay(1000); // Delay a little bit to improve simulation performance
}