#include <Servo.h>
#include <LiquidCrystal.h>
// Pin definitions
const int trigPin = 9;
const int echoPin = 10;
const int servoPin = 11;
// LCD setup
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
// Servo setup
Servo myServo;
// Variables to store distance
long duration;
int distance;
const int threshold = 50; // Threshold in centimeters (20 inches)
void setup() {
// Start serial communication
Serial.begin(9600);
// Set up the ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize the servo
myServo.attach(11);
// Initialize the LCD
lcd.begin(16, 2);
}
void loop() {
// Clear previous readings on the LCD
lcd.clear();
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the time taken for the echo to return
duration = pulseIn(echoPin, HIGH);
// Calculate the distance (in cm)
distance = duration * 0.0344 / 2;
// Check if the distance is within the threshold (20 inches / 50 cm)
if (distance < threshold) {
// Display the welcome message
lcd.setCursor(0, 0);
lcd.print("Hi, Welcome To");
lcd.setCursor(0, 1);
lcd.print("the Weisser Residence");
// Move the servo to a predefined position (e.g., 90 degrees)
myServo.write(90);
} else {
// Display the distance on the LCD
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" cm");
// Control the servo based on distance
if (distance < 10) {
myServo.write(90);
delay(500);
myServo.write(-90);
}
}
// Delay for a short period before the next reading
delay(500);
}