// Arduino Uno R3, ISC LCD 16x2, HC-SR04 Ultrasonic Sensor, x3 LEDs, Buzzer.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "pitches.h"
// Set the LCD address to 0x27 for a 16 chars and 2 line display
// You may need to change the address to 0x3F if 0x27 does not work
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define BUZZER_PIN 8 // The Arduino pin connected to the buzzer

// notes in the melody:
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

int trigPin = 10;    // Trigger
int echoPin = 9;    // Echo
long duration, cm, inches;
 
void setup() {
  //Serial Port begin
  Serial.begin (9600);
  //Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  lcd.init(); // Initialize the LCD, correct method is init()

  // Turn on the backlight
  lcd.backlight();
}
 
void loop() {
  // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
 
  // Read the signal from the sensor: a HIGH pulse whose
  // duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
 
  // Convert the time into a distance
  cm = (duration/2) / 29.1;     // Divide by 29.1 or multiply by 0.0343
  inches = (duration/2) / 74;   // Divide by 74 or multiply by 0.0135
  
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  

  lcd.setCursor(0,0);
  lcd.print("Distance: ");
  lcd.setCursor(11,0);
  lcd.print(cm);
  if(cm > 100){
    lcd.setCursor(14,0);
    lcd.print("cm.");
    digitalWrite(13, LOW);
    digitalWrite(12, LOW);
    digitalWrite(11, HIGH);}
  if (cm < 100) {digitalWrite(12, HIGH);
  digitalWrite(11, LOW);
  digitalWrite(13, LOW);
  for (int thisNote = 0; thisNote < 8; thisNote++) {
  // to calculate the note duration, take one second divided by the note type.
  //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
  int noteDuration = 1000 / noteDurations[thisNote];
  tone(BUZZER_PIN, melody[thisNote], noteDuration);
  lcd.setCursor(13,0);
  lcd.print("!!!!");
  if (cm < 10) {
    lcd.setCursor(12,0);
    lcd.print("!!!!!");
    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
  }
  }
  }

}