#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define trig 11
#define echo 10
#define buzzer 2
#define led 8
void setup() {
lcd.begin(16, 2);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
}
float readDistanceCM() {
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
int duration = pulseIn(echo, HIGH);
return duration * 0.017102;
}
void loop() {
float distance = readDistanceCM();
Serial.print("Jarak = ");
Serial.print(readDistanceCM());
Serial.println(" cm");
delay(500);
lcd.setCursor(0,0);
lcd.print("jarak");
lcd.setCursor(0,1);
lcd.print(distance);
if (distance <50){
digitalWrite(led, HIGH);
tone(buzzer, 500);
delay(210);
noTone(buzzer);
digitalWrite(led, LOW);
delay(210);
}
}