#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
// Pin definitions for HC-SR04 Ultrasonic Sensor
const int trigPin = 7;
const int echoPin = 6;
// Pin definition for Servo
const int servoPin = 9;
// Create Servo object
Servo myServo;
// Create LCD object with I2C address (0x27 is common for most 16x2 I2C LCDs)
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize the HC-SR04 sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize the servo motor
myServo.attach(servoPin);
// Initialize the LCD
lcd.begin(16, 2);
lcd.print("System Ready Sir");
delay(2000); // Display message for 2 seconds
lcd.clear();
}
void loop() {
// Trigger the ultrasonic sensor to send a pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the pulse from the echo pin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters (speed of sound is ~343 m/s)
long distance = duration * 0.0344 / 2;
// Print the distance to the Serial Monitor (optional)
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is within a specific range (e.g., object detected within 30 cm)
if (distance < 30) { // Object detected within 30 cm
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("What are u doin?");
myServo.write(90); // Rotate servo to 90 degrees
delay(10000); // Hold the servo position for 1 second
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Waiting...");
myServo.write(0); // Return the servo to 0 degrees
delay(2000); // Wait for 2 seconds before checking again
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("All Clear Roger");
}
delay(200); // Short delay to avoid continuous sensor reading
}