#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int trigPin = 12;
const int echoPin = 11;
int cahaya = A2;
int ldr;
long duration;
int distance;
int buzzer = 4;
int led = 3;
void setup()
{
lcd.init();
lcd.backlight();
lcd.setCursor(0,0);
lcd.print(" FIQRI R.S");
lcd.setCursor(0,1);
lcd.print("NIM : D412021062");
delay (3000);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT);// Sets the echoPin as an Input
pinMode(cahaya, INPUT);
pinMode(buzzer, OUTPUT);
pinMode(led, OUTPUT);
Serial.begin(9600); // Starts the serial communication
}
void loop()
{
lcd.clear();
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
ldr = analogRead(cahaya);
// Sets the trigPin on HIGH state for 10 micro seconds
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= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
Serial.print("Cahaya: ");
Serial.println(ldr);
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
delay (500);
if (distance <= 15){
lcd.setCursor(3,1);
lcd.print("bahaya");
digitalWrite (buzzer, HIGH);
delay (1000);
}
if (15< distance < 50 ){
lcd.setCursor(4,1);
lcd.print("siaga");
delay (1000);
}
else {
lcd.setCursor(5,1);
lcd.print("aman");
digitalWrite (buzzer, LOW);
delay(1000);
}
if (ldr <= 500){
digitalWrite (led, HIGH);
delay(1000);
}
else {
digitalWrite (led, LOW);
delay(1000);
}
}