#include <LiquidCrystal_I2C.h>
#include <Wire.h>
LiquidCrystal_I2C lcd(0x27,20,4);
#define echoPin 12 // attach pin D12 Arduino to pin Echo of HC-SR04
#define trigPin 13 //attach pin D13 Arduino to pin Trig of HC-SR04
// defines variables
long duration; // variable for the duration of sound wave travel
int distance_cm; // variable for centimeters measurement
const int buzzer = 8;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
pinMode(buzzer, OUTPUT);
lcd.backlight();
lcd.init();
}
void loop() {
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance_cm = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance_cm);
lcd.println(" cm");
tone(buzzer, 2000);
delay(100);
noTone(buzzer);
delay(distance_cm * 2);
}