#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);

const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 6; // Echo Pin of Ultrasonic Sensor
#define led 11

const int buzzer = 9; //buzzer to arduino pin 9

void setup() {

   lcd.init();
  lcd.clear();         
  lcd.backlight(); 

   Serial.begin(9600); // Starting Serial Terminal
   pinMode(LED_BUILTIN,OUTPUT);
   pinMode(led,OUTPUT);

   pinMode(buzzer, OUTPUT);
}

void loop() {
   long duration, inches, cm , tonee,toneee;
   pinMode(pingPin, OUTPUT);
   digitalWrite(pingPin, LOW);
   delayMicroseconds(2);
   digitalWrite(pingPin, HIGH);
   delayMicroseconds(10);
   digitalWrite(pingPin, LOW);
   pinMode(echoPin, INPUT);
   duration = pulseIn(echoPin, HIGH);
   inches = microsecondsToInches(duration);
   cm = microsecondsToCentimeters(duration);

   //lcd

   lcd.clear();
   //delay(1000);
   lcd.setCursor(0,0);
   lcd.print("Obstacle Detection ");
   lcd.setCursor(2,1);
   lcd.print(cm);
   lcd.print("cm");
   
   Serial.print(inches);
   Serial.print(" inches, ");
   Serial.print(cm);
   Serial.print("cm");
   Serial.println();
   delay(100);

   if(cm>100)
   {
      digitalWrite(LED_BUILTIN,HIGH);
      digitalWrite(led,LOW);
       tonee = toneeee1(toneee);

   } 

else if(cm<20)
{
     //digitalWrite(LED_BUILTIN,LOW); 
    // digitalWrite(12,HIGH);
     tonee = toneeee2(toneee);
   }


   else{
     digitalWrite(LED_BUILTIN,LOW); 
     digitalWrite(led,HIGH);
     tonee = toneeee(toneee);
   }
}

long microsecondsToInches(long microseconds) {
   return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
   return microseconds / 29 / 2;
}

// high alert
long toneeee(long toneee) 
{
   tone(buzzer, 1000); // Send 1KHz sound signal...
   tone(led, 1000); // Led on
  delay(100);        // ...for 1 sec
  noTone(buzzer);     // Stop sound...
  noTone(led);   // led off
  delay(100);        // ...for 1sec

}

// alert


long toneeee1(long toneee) 
{
   tone(buzzer, 1000); // Send 1KHz sound signal...
   digitalWrite(led,HIGH); // led on
  delay(1000);        // ...for 1 sec
  noTone(buzzer);     // Stop sound...
   digitalWrite(led,LOW); // led off
  delay(1000);        // ...for 1sec

}

// very high alert
long toneeee2(long toneee) 
{
   tone(buzzer, 1000); // Send 1KHz sound signal...
   digitalWrite(led,HIGH);
  delay(1000);        // ...for 1 sec
  //noTone(buzzer);     // Stop sound...
  // digitalWrite(12,LOW);
 // delay(1000);        // ...for 1sec

}