#include <ESP32Servo.h>
const int trigPin = 12;
const int echoPin = 13;
const int LED1 = 14;
const int LED2 = 15;
const int LED3 = 16;
const int LED4 = 17;
const int LED5 = 18;
int duration = 0;
int distance = 0;
Servo myservo; // Create a servo object
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);
pinMode(LED5, OUTPUT);
myservo.attach(18); // Attach the servo to pin 9 (or use a different PWM pin)
Serial.begin(9600);
}
void loop()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration / 58.2;
if (distance <50)
{
digitalWrite(LED1, HIGH);
}
else
{
digitalWrite(LED1, LOW);
}
if (distance < 100)
{
digitalWrite(LED2, HIGH);
}
else
{
digitalWrite(LED2, LOW);
}
if (distance <200)
{
digitalWrite(LED3, HIGH);
}
else
{
digitalWrite(LED3, LOW);
}
if (distance < 300)
{
digitalWrite(LED4, HIGH);
}
else
{
digitalWrite(LED4, LOW);
}
if (distance < 400)
{
digitalWrite(LED5, HIGH);
myservo.write(90); // Move the servo when LED5 is on
}
else
{
digitalWrite(LED5, LOW);
myservo.write(0); // Move the servo back when LED5 is off
}
delay(100);
}