#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Define pins for ultrasonic sensor
#define trigPin 6
#define echoPin 7
// Define variables for distance and duration
long duration;
int distance;
LiquidCrystal_I2C lcd (0x27,16,2);
int red=5;
int green=4;
int yellow=3;

void setup() {

  // Initialize Serial communication

  lcd.begin(16,2);
  lcd.backlight();
  // Define pin modes
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(yellow, OUTPUT);
 
}

void loop() {
  // Send a 10µs pulse to the Trig pin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Measure the duration of the echo signal
  duration = pulseIn(echoPin, HIGH);

  // Calculate the distance to the obstacle
  distance = duration * 0.034 / 2;

  // Display the distance on the Serial monitor
  lcd.setCursor(0,0);
  lcd.print("Distance: ");
  lcd.setCursor(0,1);
  lcd.print(distance);
  lcd.println(" cm");
  // Wait for 100ms before measuring again
  delay(100);
  if(distance >=0 && distance<=150){
  lcd.setCursor(10,1);
  lcd.print(" close ");
  digitalWrite(red, HIGH);
  digitalWrite(green, LOW);
  digitalWrite(yellow, LOW);
  }
  else if(distance >=151 && distance<=300){
  lcd.setCursor(10,1);
  lcd.print("Normal");
  digitalWrite(red, LOW);
  digitalWrite(green,LOW);
  digitalWrite(yellow, HIGH);
  }
  else if(distance >=301 && distance<=400)
  {
  lcd.setCursor(10,1);
  lcd.print("   Far");
  digitalWrite(red, LOW);
  digitalWrite(green, HIGH);
  digitalWrite(yellow, LOW);
  }

}