/*********
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-hc-sr04-ultrasonic-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*********/
#include <ESP32Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
Servo myservo;
const int servoPin = 15;
const int trigPin = 5;
const int echoPin = 18;
// Define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;
// Initialize the LCD with the address 0x27
LiquidCrystal_I2C lcd(0x27, 16, 2); // Adjust the parameters (address, columns, rows) according to your LCD
void setup() {
Serial.begin(115200); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
myservo.attach(servoPin);
// Initialize the LCD
lcd.init();
lcd.backlight(); // Turn on the backlight
lcd.setCursor(0, 0);
lcd.print("Distance (cm): ");
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state 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);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
//Jika jarak kurang dari 200 cm, gerakkan servo 90 derajat
if (distanceCm < 200) {
myservo.write(90);
delay(500); // Tunggu sebentar untuk memberikan waktu servo bergerak
} else {
myservo.write(0); // Kembalikan servo ke posisi awal jika tidak ada objek dalam jarak
}
// Prints the distance on the LCD
lcd.setCursor(0, 1);
lcd.print(" "); // Clear the previous distance
lcd.setCursor(0, 1);
lcd.print(distanceCm);
lcd.print(" cm");
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
Serial.print("Distance (inch): ");
Serial.println(distanceInch);
delay(1000);
}