#include <ESP32Servo.h>
#define TRIG_PIN 32 // ESP32 pin GPIO 23 connected to Ultrasonic Sensor's TRIG pin
#define ECHO_PIN 35 // ESP32 pin GPIO 22 connected to Ultrasonic Sensor's ECHO pin
#define SERVO_PIN 13 // ESP32 pin GPIO 26 connected to Servo Motor's pin
#define DISTANCE_THRESHOLD 50 // centimeters
#define LED_PIN 12
Servo servo; // Create a servo object to control a servo
int ledState = LOW;
void setup() {
Serial.begin(9600); // Initialize the serial port
Serial.println("Welcome To Distance Meter");
pinMode(TRIG_PIN, OUTPUT); // Set TRIG_PIN as an output
pinMode(ECHO_PIN, INPUT); // Set ECHO_PIN as an input
servo.attach(SERVO_PIN); // Attach the servo to SERVO_PIN
pinMode(LED_PIN, OUTPUT); // Set LED_PIN as an output
servo.write(0); // Initialize the servo position
}
void loop() {
// Generate a 10-microsecond pulse on TRIG_PIN
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the duration of the pulse on ECHO_PIN
float duration_us = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance in centimeters
float Distance_cm = 0.017 * duration_us;
if (Distance_cm < DISTANCE_THRESHOLD) {
servo.write(360); // Rotate the servo to 360 degrees
digitalWrite(LED_PIN, HIGH); // Turn on the LED
} else {
servo.write(0); // Rotate the servo to 0 degrees
digitalWrite(LED_PIN, LOW); // Turn off the LED
}
// Print the distance value to the Serial Monitor
Serial.print("Distance = ");
Serial.print(Distance_cm);
Serial.println(" cm");
delay(500); // Add a delay to control the loop frequency
}