#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
long duration;
int distance;
const int trigPin = 9;
const int echoPin = 10;
const int buz = 8;
void Get_Dis()
{
//Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println("cm");
return (distance);
}
void setup()
{
lcd.init();
lcd.backlight();
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buz, OUTPUT);
Serial.begin(9600);
}
void loop()
{
lcd.clear();
Get_Dis();
lcd.setCursor(0, 0);
lcd.print("Welcome");
lcd.setCursor(0, 1);
lcd.print("-------");
if (distance<10 && distance>4)
{
lcd.clear();
lcd.setCursor(0, 2);
lcd.println("ALARM ON! ");
for (int i = 440; i<1000; i++)
{
tone(buz, i, 10);
delay(5);
}
for ( int i = 1000; i>440; i--)
{
tone(buz, i, 10);
delay(5);
}
}
else
{
lcd.setCursor(0, 2);
lcd.println("Distance: ");
lcd.print(distance);
lcd.println("cm");
lcd.setCursor(0, 3);
lcd.println("ALARM IS OFF! ");
delay(300);
}
}