#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int trigPin = 8;
const int echoPin = 7;
const int vehicleThreshold = 50; // Adjust this threshold according to your setup
const int vehicleDuration = 20000; // 5 minutes in milliseconds
const int debounceTime = 5000; // 5 seconds debounce time
const int numReadings = 10; // Number of readings to average
long duration;
int distance;
unsigned long startTime = 0;
bool vehicleDetected = false;
int vehicleCounter = 0;
unsigned long lastChangeTime = 0;
int readings[numReadings]; // the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int averageDistance = 0; // the average
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
lcd.begin(16, 2);
lcd.clear();
// Initialize the readings array
for (int i = 0; i < numReadings; i++) {
readings[i] = 0;
}
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Smooth out the distance readings with a moving average filter
total = total - readings[readIndex];
readings[readIndex] = distance;
total = total + readings[readIndex];
readIndex = (readIndex + 1) % numReadings;
averageDistance = total / numReadings;
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(averageDistance);
lcd.setCursor(0, 1);
lcd.print("Count: ");
lcd.print(vehicleCounter);
if (averageDistance < vehicleThreshold) {
if (!vehicleDetected) {
// Vehicle has just arrived
vehicleDetected = true;
startTime = millis();
} else {
// Vehicle has been there for some time
if (millis() - startTime >= vehicleDuration && millis() - lastChangeTime >= debounceTime) {
// Vehicle presence confirmed for 5 minutes and debounce time passed
lcd.clear();
lcd.print("Vehicle Detected");
vehicleCounter++;
lcd.setCursor(0, 1);
lcd.print("Count: ");
lcd.print(vehicleCounter);
delay(5000); // Display message for 5 seconds
lcd.clear();
vehicleDetected = false;
lastChangeTime = millis();
}
}
} else {
// No vehicle detected
vehicleDetected = false;
}
delay(500); // Adjust delay as needed for your application
}