#include <LiquidCrystal.h>
#include <Adafruit_MPU6050.h>
#define BUZZER 8
#define ACCIDENT_THRESHOLD 10
// Initialize the LCD and MPU6050 objects
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
Adafruit_MPU6050 mpu;
// Define the variables for storing the accelerometer, gyroscope, and temperature data
float AccX, AccY, AccZ;
float GyroX, GyroY, GyroZ;
float Temp;
// Define the variables for storing the roll, pitch, and yaw angles
float roll, pitch, yaw;
// Define the flag for indicating an accident
bool accident = false;
void setup() {
Serial.begin(9600);
pinMode(BUZZER, OUTPUT);
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
lcd.print("Accident Detect");
lcd.setCursor(0, 1);
lcd.print("Alert System");
delay(3000);
lcd.clear();
if (!mpu.begin()) {
Serial.println("Failed to find MPU6050 chip");
while (1) {
delay(10);
}
}
Serial.println("MPU6050 Found!");
// Set the accelerometer and gyroscope range and filter bandwidth
mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
mpu.setGyroRange(MPU6050_RANGE_2000_DEG);
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
}
void loop() {
// Read the accelerometer, gyroscope, and temperature data from the sensor
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
// Store the data in the variables
AccX = a.acceleration.x;
AccY = a.acceleration.y;
AccZ = a.acceleration.z;
GyroX = g.gyro.x;
GyroY = g.gyro.y;
GyroZ = g.gyro.z;
Temp = temp.temperature;
// Calculate the roll and pitch angles from the accelerometer data
roll = atan2(AccY, AccZ) * 180 / PI;
pitch = atan2(-AccX, sqrt(AccY * AccY + AccZ * AccZ)) * 180 / PI;
// Calculate the yaw angle from the gyroscope data
yaw = yaw + GyroZ * 0.01; // Assuming a loop time of 10 ms
// Calculate the magnitude of the acceleration vector
float accMag = sqrt(AccX * AccX + AccY * AccY + AccZ * AccZ);
// Check if the acceleration magnitude exceeds the threshold
if (accMag > ACCIDENT_THRESHOLD) {
// Set the accident flag to true
accident = true;
}
if(accident){
digitalWrite(BUZZER,HIGH);
lcd.clear();
lcd.print("Accident Detected");
lcd.setCursor(0, 1);
lcd.print("Be Careful!");
delay(4000);
digitalWrite(BUZZER,LOW);
accident = false;
}
lcd.clear();
}