// ---------------------------------------------------------------- //
// Arduino Ultrasoninc Sensor HC-SR04
// Re-writed by Arbi Abdul Jabbaar
// Using Arduino IDE 1.8.7
// Using HC-SR04 Module
// Tested on 17 September 2019
// ---------------------------------------------------------------- //
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16,2);
#define nada 262
#define nada2 349
#define echoPin 2 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-SR04
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
int l1=8;
int buzzer=4;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
Serial.println("with Arduino UNO R3");
pinMode(l1, OUTPUT);
lcd.init();
lcd.backlight();
}
void loop() {
// Clears the trigPin condition
lcd.setCursor(0,0);
lcd.print("jarak : ");
lcd.setCursor(0,1);
lcd.print("ket :");
lcd.setCursor(7,0);
lcd.print(distance);
lcd.setCursor(10,0);
lcd.print("cm");
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
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; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distance:");
Serial.print(distance);
Serial.println(" cm");
if (distance <100){
digitalWrite(l1, HIGH);
tone(buzzer, nada);
delay(100);
tone(buzzer, nada2);
delay(100);
lcd.setCursor(7,1);
lcd.print("Dekat");
}
else {
digitalWrite(l1, LOW);
noTone(buzzer);
lcd.setCursor(7,1);
lcd.print("Jauh ");
}
}