#include <LiquidCrystal.h>
// Define pins for the ultrasonic sensor
#define TRIG_PIN 12
#define ECHO_PIN 14
// Define pins for the LCD
#define RS 4
#define EN 5
#define D4 18
#define D5 19
#define D6 20
#define D7 21
// Define pin for the buzzer
#define BUZZER_PIN 13
LiquidCrystal lcd(RS, EN, D4, D5, D6, D7);
void setup() {
// Initialize the LCD
lcd.begin(16, 2);
// Initialize the ultrasonic sensor pins
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Initialize the buzzer pin
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, LOW);
lcd.print("Distance: ");
}
void loop() {
// Send a 10us pulse to trigger the ultrasonic sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the duration of the echo pulse
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance in cm
float distance = duration * 0.034 / 2;
// Print the distance on the LCD
lcd.setCursor(0, 1);
lcd.print(" "); // Clear previous distance
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" cm");
if (distance <12) {
tone(BUZZER_PIN, 100);
} else{
noTone(BUZZER_PIN);
}
delay(500); // Wait before taking another reading
}