#include <LiquidCrystal.h>
// LCD pins
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
// IR sensor pins
const int IR1 = 8;
const int IR2 = 9;
// Variables for time and velocity calculation
unsigned long t1 = 0;
unsigned long t2 = 0;
float velocity = 0.0;
void setup() {
// Initialize LCD
lcd.begin(16, 2); // Initialize LCD: 16 columns, 2 rows
lcd.clear(); // Clear LCD screen
lcd.setCursor(0, 0); // Set cursor to first column of first row
lcd.print("Vehicle Speed"); // Print initial message on LCD
// Initialize IR sensor pins
pinMode(IR1, INPUT);
pinMode(IR2, INPUT);
// Initialize Serial communication for debugging
Serial.begin(9600);
}
void loop() {
// Check if IR1 is triggered
if (digitalRead(IR1) == HIGH && t1 == 0) {
t1 = millis(); // Record time when IR1 is triggered for the first time
}
// Check if IR2 is triggered after IR1
if (digitalRead(IR2) == HIGH && t1 != 0 && t2 == 0) {
t2 = millis(); // Record time when IR2 is triggered after IR1
}
// Calculate velocity if both t1 and t2 are recorded
if (t1 != 0 && t2 != 0) {
unsigned long timeDifference = t2 - t1;
float timeSeconds = timeDifference / 1000.0; // Convert milliseconds to seconds
// Calculate velocity in km/hr
velocity = (0.2 / timeSeconds) * 3.6;
// Display velocity on LCD
lcd.clear(); // Clear LCD screen
lcd.setCursor(0, 0); // Set cursor to first column of first row
lcd.print("Vehicle Speed"); // Print initial message on LCD
lcd.setCursor(0, 1); // Set cursor to first column of second row
lcd.print(velocity); // Print velocity
lcd.print(" Km/hr"); // Print unit
// Print velocity to Serial Monitor for debugging
Serial.print("Velocity: ");
Serial.print(velocity);
Serial.println(" Km/hr");
// Reset values for next calculation
t1 = 0;
t2 = 0;
delay(500); // Delay for readability
}
}