#define ECHO_PIN 2
#define TRIG_PIN 3
// Jangan lupa tambahkan library lcd i2c
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
#include <Servo.h>
Servo servo1;
void setup() {
lcd.init();
lcd.backlight();
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(8, OUTPUT);
servo1.attach(5);
servo1.write(0);
}
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void loop() {
float distance = readDistanceCM();
Serial.print("Jarak: ");
Serial.println(readDistanceCM());
delay(100);
// if (distance > 150) {
// digitalWrite(8, HIGH);
// } else {
// digitalWrite(8, LOW);
// }
if (distance <= 10) {
digitalWrite(8, HIGH);
} else {
digitalWrite(8, LOW);
}
// lcd.clear();
// lcd.setCursor(0, 0);
// lcd.print("Jarak: ");
// lcd.print(distance);
// lcd.print(" cm");
if (distance <= 10) {
delay(200);
servo1.write(180);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("TERBUKA");
} else {
delay(200);
servo1.write(0);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("TERTUTUP");
}
}