#include <LiquidCrystal_I2C.h>
3. #define echoPin 3 // attach pin D2 Arduino to pin Echo of HC-SR04
4. #define trigPin 2 //attach pin D3 Arduino to pin Trig of HC-SR04
5. // defines variables
6. long duration; // variable for the duration of sound wave travel
7. int distance; // variable for the distance measurement
8. LiquidCrystal_I2C lcd(0x27, 16, 2);
9. void setup() {
10.pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
11.pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
12.Serial.begin(9600); // // Serial Communication is starting with 9600 of
baudrate speed
13.lcd.init();
14.lcd.backlight();7
15.lcd.clear();
16.pinMode(5, OUTPUT); //merah
17.pinMode(6, OUTPUT); //kuning
18.pinMode(7, OUTPUT); //hijau
19.}
20.void loop() {
21.// Clears the trigPin condition
22.digitalWrite(trigPin, LOW);
23.delayMicroseconds(2);
24.// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
25.digitalWrite(trigPin, HIGH);
26.delayMicroseconds(10);
27.digitalWrite(trigPin, LOW);
28.// Reads the echoPin, returns the sound wave travel time in microseconds
29.duration = pulseIn(echoPin, HIGH);
30.// Calculating the distance
31.distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go
and back)
32.// Displays the distance on the Serial Monitor
33.lcd.setCursor(0,0);
34.lcd.print("Distance: ");
35.lcd.print(distance);
36.lcd.println(" cm ");
37.lcd.print(" ");
38.Serial.print("Distance: ");
39.Serial.print(distance);
40.Serial.println(" cm");
41.delay(500);
42.if (distance >= 16) {
43.digitalWrite(7, HIGH);
44.digitalWrite(6, LOW);
45.digitalWrite(5, LOW);
46.} else if (distance >= 5) {
47.digitalWrite(6, HIGH);
48.digitalWrite(7, LOW);
49.digitalWrite(5, LOW);
50.} else if (distance <= 4) {
51.digitalWrite(5, HIGH);
52.digitalWrite(6, LOW);
53.digitalWrite(7, LOW);
54.}
55.}