#include <Wire.h>
#include <Adafruit_LiquidCrystal.h> // For Adafruit I2C LCD
#include <NewPing.h> // For Ultrasonic distance measurement
#define TRIGGER_PIN 12 // Pin connected to the HC-SR04 Trigger
#define ECHO_PIN 13 // Pin connected to the HC-SR04 Echo
#define MAX_DISTANCE 200 // Maximum distance to measure (in cm)
#define BUZZER_PIN 26 // Pin connected to the Buzzer
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // Initialize ultrasonic sensor
Adafruit_LiquidCrystal lcd(0); // Initialize the I2C LCD
void setup() {
// Start serial communication for debugging
Serial.begin(9600);
// Initialize the LCD screen
lcd.begin(16, 2);
lcd.setBacklight(LOW); // Turn off the backlight initially
// Initialize buzzer pin as output
pinMode(BUZZER_PIN, OUTPUT);
// Set initial LCD message
lcd.setCursor(0, 0);
lcd.print("Distance Sensor");
}
void loop() {
// Get the distance from the ultrasonic sensor
int distance = sonar.ping_cm();
// Clear the previous message on the LCD
lcd.clear();
// Display the distance on the LCD
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
// If an object is closer than 30 cm, trigger the buzzer
if (distance > 0 && distance < 30) {
tone(BUZZER_PIN, 1000); // Buzz at 1000 Hz frequency
lcd.setCursor(0, 1);
lcd.print("Object detected!");
} else {
noTone(BUZZER_PIN); // Turn off buzzer if distance is safe
}
delay(500); // Delay to allow sensor to stabilize and reduce flicker on LCD
}