#include <ESP32Servo.h>

#define TRIG_PIN 17
#define ECHO_PIN 18
#define SERVO_PIN 15
#define LED1_PIN 14
#define LED2_PIN 12
#define LED3_PIN 32
#define LED4_PIN 33
#define LED5_PIN 25
#define LED6_PIN 26
#define LED7_PIN 27

Servo servo;
int ledState = LOW;

void setup() {
  Serial.begin(9600);
  Serial.println("Welcome To Distance Meter");
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  servo.attach(SERVO_PIN);
  pinMode(LED1_PIN, OUTPUT);
  pinMode(LED2_PIN, OUTPUT);
  pinMode(LED3_PIN, OUTPUT);
  pinMode(LED4_PIN, OUTPUT);
  pinMode(LED5_PIN, OUTPUT);
  pinMode(LED6_PIN, OUTPUT);
  pinMode(LED7_PIN, OUTPUT);

  servo.write(0);
}

void loop() {
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  float duration_us = pulseIn(ECHO_PIN, HIGH);
  float Distance_cm = 0.017 * duration_us;

  if (Distance_cm <= 350) {
    servo.write(45);
    digitalWrite(LED1_PIN, HIGH);
  } else {
    digitalWrite(LED1_PIN, LOW);
  }

  if (Distance_cm <= 300) {
    digitalWrite(LED2_PIN, HIGH);
  } else {
    digitalWrite(LED2_PIN, LOW);
  }

  if (Distance_cm <= 250) {
    servo.write(90);
    digitalWrite(LED3_PIN, HIGH);
  } else {
    digitalWrite(LED3_PIN, LOW);
  }

  if (Distance_cm <= 200) {
    digitalWrite(LED4_PIN, HIGH);
  } else {
    digitalWrite(LED4_PIN, LOW);
  }

  if (Distance_cm <= 150) {
    servo.write(135);
    digitalWrite(LED5_PIN, HIGH);
  } else {
    digitalWrite(LED5_PIN, LOW);
  }

  if (Distance_cm <= 100) {
    digitalWrite(LED6_PIN, HIGH);
  } else {
    digitalWrite(LED6_PIN, LOW);
  }

  if (Distance_cm <= 50) {
    servo.write(180);
    digitalWrite(LED7_PIN, HIGH);
  } else {
    digitalWrite(LED7_PIN, LOW);
  }

  Serial.print("Distance = ");
  Serial.print(Distance_cm);
  Serial.println(" cm");

  delay(1000);
}