#include <Wire.h> // For I2C communication
#include <LiquidCrystal_I2C.h> // Library for LCD with I2C
// Create LCD object with I2C address (usually 0x27 or 0x3F)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Ultrasonic Sensor pins
const int trigPin = 9;
const int echoPin = 10;
// LED and Buzzer pins
const int ledPin = 6;
const int buzzerPin = 7;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// Initialize LCD
lcd.init();
lcd.backlight(); // Turn on backlight
lcd.setCursor(0, 0);
lcd.print("Ultrasonic Test");
delay(2000);
}
void loop() {
// Send trigger pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read echo pulse
long duration = pulseIn(echoPin, HIGH);
// Calculate distances
float distanceCM = duration * 0.034 / 2;
float distanceInches = distanceCM / 2.54;
// Display on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("CM: ");
lcd.print(distanceCM, 1);
lcd.setCursor(0, 1);
lcd.print("In: ");
lcd.print(distanceInches, 1);
// LED and Buzzer alert
if (distanceCM <= 10) {
digitalWrite(ledPin, HIGH);
// Beep like a bomb alert
for (int i = 0; i < 3; i++) {
tone(buzzerPin, 1000);
delay(100);
noTone(buzzerPin);
delay(100);
}
} else {
digitalWrite(ledPin, LOW);
noTone(buzzerPin);
}
delay(500);
}