/*
HC-SR04 Ultrasonic Sensor dengan lamp.
Konfigurasi:
=Ultrasinic Sensor=
Vcc | 5V
Gnd | GND
echo | pin 2
Trig | pin 3
=LED=
pin 8 sampai 4 (besar ke kecil bisa ditambahakan sampai pin 13)
=LCD I2C=
Gnd | GND
Vcc | 5v
SDA | A4
SCL | A5
Tugas II Produktif.
©️ 2022 - Kelompok 2 XI EI 2
*/
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
int trig = 3,
echo = 2,
ledPin[] = { 8, 7, 6, 5, 4},
jarakSeb = 0,
minJarak = 200;
void setup() {
lcd.init();
lcd.backlight();
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
for(int i = 0; i < sizeof ledPin / sizeof *ledPin; i++){
pinMode(ledPin[i], OUTPUT);
}
if(minJarak > 400) minJarak = 400;
lcd.print("<SENSOR & LAMPU>");
delay(2000);
}
float jarakCM() {
digitalWrite(trig, !1);
digitalWrite(trig, !0);
digitalWrite(trig, !1);
int duration = pulseIn(echo, HIGH);
return duration / 58;
}
void loop() {
float jarak = jarakCM();
if(jarak == jarakSeb) return;
else jarakSeb = jarak;
float persenT = 100 - ((jarak / 400) * 100);
if(persenT < 0) persenT = 0;
for(int i = 0; i < sizeof ledPin / sizeof *ledPin; i++){
digitalWrite(ledPin[i], !(jarak > ((minJarak / (sizeof ledPin / sizeof *ledPin)) * (i + 1))));
}
lcd.clear();
lcd.print("JARAK:");
lcd.print(jarak);
lcd.print("CM");
lcd.setCursor(0,1);
lcd.print("%> ");
lcd.print(persenT);
// delay(500);
}