#include <LCD-I2C.h> // Include LCD I2C library
LCD_I2C lcd(0x27, 16, 2); // Set up LCD (address, columns, rows)
#define pinTrig 2 // Ultrasonic sensor trigger pin
#define pinEcho 4 // Ultrasonic sensor echo pin
#define pinLed 5 // LED pin
// Function to measure distance from ultrasonic sensor
float getDistance(int trig, int echo) {
pinMode(trig, OUTPUT);
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
pinMode(echo, INPUT);
float distance = pulseIn(echo, HIGH) / 58.0; // Convert pulse time to cm
// Handle possible error with pulseIn returning 0
if (distance == 0) {
return -1; // Return -1 to indicate error
} else {
return distance;
}
}
void setup() {
Serial.begin(115200); // Activate serial monitor
// Initialize LCD display
lcd.init();
lcd.display();
lcd.backlight();
// Initialize sensor and LED pins
pinMode(pinTrig, OUTPUT);
pinMode(pinEcho, INPUT);
pinMode(pinLed, OUTPUT);
}
void loop() {
lcd.clear(); // Clear the screen
lcd.setCursor(5, 0); // Set position column 5, row 0
lcd.print("Akhdan"); // Print on LCD
lcd.setCursor(7, 1); // Set position column 7, row 1
lcd.print("8K"); // Print on LCD
delay(1000);
lcd.clear(); // Clear the screen
lcd.setCursor(1, 0); // Set position column 1, row 0
lcd.print("Aku Belajar"); // Print on LCD
lcd.setCursor(8, 1); // Set position column 8, row 1
lcd.print("Robotika"); // Print on LCD
delay(1000);
// Read distance from the ultrasonic sensor
float jarak = getDistance(pinTrig, pinEcho);
// Check if the distance reading is valid
if (jarak != -1) {
// Display the distance on the LCD
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("Jarak (cm) = ");
lcd.setCursor(1, 1);
lcd.print(jarak);
// Check if the object is within 200 cm
if (jarak <= 200) {
digitalWrite(pinLed, HIGH); // Turn on the LED
lcd.clear();
lcd.print("Object Detected!");
} else {
digitalWrite(pinLed, LOW); // Turn off the LED
lcd.clear();
lcd.print("No Object");
}
} else {
lcd.clear();
lcd.print("Sensor Error");
}
delay(1000); // Small delay for readability
}