#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#define FRONT_TRIG 2
#define FRONT_ECHO 3
#define LEFT_TRIG 4
#define LEFT_ECHO 5
#define RIGHT_TRIG 6
#define RIGHT_ECHO 7
#define BACK_TRIG 8
#define BACK_ECHO 9

#define DISTANCE_THRESHOLD 20  // Threshold distance in cm

// Initialize LCD display (address 0x27 for a 16x2 LCD)
LiquidCrystal_I2C lcd(0x27, 16, 2);

// Function to calculate distance using ultrasonic sensor
long readUltrasonicDistance(int trigPin, int echoPin) {
  digitalWrite(trigPin, LOW);  // Clear the trigPin condition
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);  // Set the trigPin high for 10us
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);  // Read the echoPin, returns sound wave travel time in microseconds
  long distance = (duration / 2) / 29.1;  // Convert time to distance
  return distance;
}

void setup() {
  // Set up the ultrasonic sensor pins
  pinMode(FRONT_TRIG, OUTPUT);
  pinMode(FRONT_ECHO, INPUT);
  pinMode(LEFT_TRIG, OUTPUT);
  pinMode(LEFT_ECHO, INPUT);
  pinMode(RIGHT_TRIG, OUTPUT);
  pinMode(RIGHT_ECHO, INPUT);
  pinMode(BACK_TRIG, OUTPUT);
  pinMode(BACK_ECHO, INPUT);

  // Initialize the LCD
  lcd.begin(16, 2);  // Corrected the lcd.begin call
  lcd.backlight();
  lcd.clear();
  
  lcd.setCursor(0, 0);
  lcd.print("Car System Ready");
  delay(2000);  // Display welcome message for 2 seconds
  lcd.clear();
}

void loop() {
  long frontDist = readUltrasonicDistance(FRONT_TRIG, FRONT_ECHO);
  long leftDist = readUltrasonicDistance(LEFT_TRIG, LEFT_ECHO);
  long rightDist = readUltrasonicDistance(RIGHT_TRIG, RIGHT_ECHO);
  long backDist = readUltrasonicDistance(BACK_TRIG, BACK_ECHO);

  lcd.clear();  // Clear LCD to update new status

  if (frontDist < DISTANCE_THRESHOLD) {
    lcd.setCursor(0, 0);
    lcd.print("Obstacle Front!");
    lcd.setCursor(0, 1);
    lcd.print("Car Stopped");
    delay(1000);  // Simulate halt
  } else if (leftDist < DISTANCE_THRESHOLD) {
    lcd.setCursor(0, 0);
    lcd.print("Obstacle Left!");
    lcd.setCursor(0, 1);
    lcd.print("Car Stopped");
    delay(1000);
  } else if (rightDist < DISTANCE_THRESHOLD) {
    lcd.setCursor(0, 0);
    lcd.print("Obstacle Right!");
    lcd.setCursor(0, 1);
    lcd.print("Car Stopped");
    delay(1000);
  } else if (backDist < DISTANCE_THRESHOLD) {
    lcd.setCursor(0, 0);
    lcd.print("Obstacle Back!");
    lcd.setCursor(0, 1);
    lcd.print("Car Stopped");
    delay(1000);
  } else {
    lcd.setCursor(0, 0);
    lcd.print("Clear Path");
    lcd.setCursor(0, 1);
    lcd.print("Moving Forward");
  }
  
  delay(500);  // Delay before the next loop
}
$abcdeabcde151015202530fghijfghij