#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <MPU6050_tockn.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // Address 0x27, 16 columns, 2 rows
MPU6050 mpu6050(Wire);
const int trigPin = 7;
const int echoPin = 6;
const int buzzerPin = 2;
int maxSpeed = 60; // Set your maximum allowed speed in km/h
int safeDistance = 20; // Set your safe following distance in centimeters
void setup() {
lcd.init();
lcd.backlight();
Wire.begin();
mpu6050.begin();
mpu6050.calcGyroOffsets(true);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
float accX = mpu6050.getAccX() / 16384.0;
float speed = accX * 100; // Assuming you've calibrated it properly
float distance = getDistance();
lcd.setCursor(0, 0);
lcd.print("Speed: " + String(speed) + " km/h");
lcd.setCursor(0, 1);
lcd.print("Distance: " + String(distance) + " cm");
if (speed > maxSpeed) {
// Display overspeed warning on the LCD
lcd.setCursor(0, 1);
lcd.print("Overspeed!");
// Activate the buzzer to indicate overspeed
tone(buzzerPin, 1000); // You can change the tone and duration
// Implement accident-avoidance logic here
if (distance < safeDistance) {
// Implement automatic braking or avoidance maneuver here
// For simulation purposes, you can print a message or take a specific action
Serial.println("Collision imminent! Applying brakes.");
}
} else {
noTone(buzzerPin);
}
delay(1000); // Update every second
}
float getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
float cm = duration * 0.034 / 2;
return cm;
}