#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
const int trigPin = 9;
const int echoPin = 10;
const int buzzerPin = 8;
Servo servoMotor;
// Set the LCD address and dimensions (16x2)
const int lcdColumns = 16;
const int lcdRows = 2;
LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows); // Change the address if needed
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
servoMotor.attach(7); // Attaching the servo motor to pin 7
Serial.begin(9600);
// Initialize the LCD
lcd.init();
lcd.backlight();
lcd.clear();
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
if (distance <= 20) {
lcd.setCursor(0, 0);
lcd.print("Warning "); // Clear the line and print warning
servoMotor.write(0); // Move the servo motor to 0 degrees
delay(1000);
if (distance <= 10) {
tone(buzzerPin, 1000);
lcd.setCursor(0, 1);
lcd.print("Danger! "); // Clear the line and print danger
} else {
lcd.setCursor(0, 1);
lcd.print(" ");
noTone(buzzerPin);
}
} else {
lcd.setCursor(0, 0);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print(" "); // Clear the line
servoMotor.write(90); // Move the servo motor to 90 degrees
}
// Print the distance to serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(100); // Delay to control the rate of measurements
}