#define TRIG_PIN 9
#define ECHO_PIN 8
#define LED_PIN 7
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600); // Initialize serial communication at 9600 baud
lcd.init();
//lcd.begin(16,2);
lcd.backlight();
lcd.clear();
}
void loop() {
// Send a 10 microsecond pulse to the trigger pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the duration of the echo pulse
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance in centimeters
float distance = (duration / 2.0) / 29.1;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Control the LED based on the distance
if (distance <= 40) {
digitalWrite(LED_PIN, HIGH); // Turn on the LED if the object is within the threshold distance
delayMicroseconds(100);
digitalWrite(LED_PIN, LOW);
delayMicroseconds(100);
lcd.setCursor(0, 0);
lcd.print("RobotX Siemreap");
lcd.setCursor(0, 1);
lcd.print("Thank You!");
delay(100);
} else {
digitalWrite(LED_PIN, LOW); // Turn off the LED if the object is beyond the threshold distance
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Hello");
}
// Wait a bit before the next measurement
delay(500);
}