#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define trigPin 9
#define echoPin 8
#define buzzerPin 10
#define ledAlertPin 11
#define ledClearPin 12
// Initialize the LCD
LiquidCrystal_I2C lcd(0x27, 16, 2); // Address 0x27, 16 chars, 2 rows
long duration;
int distance;
// Number of readings to average
const int numReadings = 5;
// Timer variables
unsigned long detectionStartTime = 0; // Time when vehicle is detected
bool vehicleDetected = false; // Flag to check vehicle detection
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(ledAlertPin, OUTPUT);
pinMode(ledClearPin, OUTPUT);
Serial.begin(9600);
// Initialize the LCD
lcd.init();
lcd.backlight(); // Turn on the backlight
lcd.setCursor(0, 0);
lcd.print("Parking System");
delay(2000); // Display the message for 2 seconds
lcd.clear();
}
int getAverageDistance() {
long totalDistance = 0;
for (int i = 0; i < numReadings; i++) {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin high for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin and calculate the distance
duration = pulseIn(echoPin, HIGH);
int currentDistance = duration * 0.034 / 2;
totalDistance += currentDistance;
delay(50); // Delay between readings
}
return totalDistance / numReadings; // Return the average distance
}
void loop() {
// Get the average distance
distance = getAverageDistance();
// Display the distance on the LCD
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm "); // Clear remaining characters
// Check if a vehicle is detected
if (distance < 100 && distance > 0) { // Vehicle detected
if (!vehicleDetected) {
vehicleDetected = true;
detectionStartTime = millis(); // Record the time of detection
}
// Check if 30 seconds have passed since vehicle detection
if (millis() - detectionStartTime >= 30000) { // 30 seconds
tone(buzzerPin, 1000); // Produce continuous beep at 1000 Hz
digitalWrite(ledAlertPin, HIGH);
digitalWrite(ledClearPin, LOW);
// Display alert message on the LCD
lcd.setCursor(0, 1); // Move to second row
lcd.print("Vehicle Detected");
}
} else {
// If no vehicle is detected
vehicleDetected = false; // Reset the vehicle detection flag
noTone(buzzerPin); // Stop the beep
digitalWrite(ledAlertPin, LOW);
digitalWrite(ledClearPin, HIGH);
// Display clear road message on the LCD
lcd.setCursor(0, 1);
lcd.print("Road is Clear "); // Clear remaining characters
}
delay(500); // Delay for half a second
}