#include <Wire.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <LiquidCrystal_I2C.h>
Adafruit_MPU6050 mpu;
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD address to 0x27 for a 16 chars and 2 line display
const int buzzerPin = 9; // Pin for the buzzer
unsigned long fallTriggerTime = 5000; // Time after which the fall is simulated (5 seconds)
unsigned long previousMillis = 0;
bool fallSimulated = false; // A flag to track if the fall has been simulated
void setup() {
Serial.begin(115200);
// Initialize the LCD
lcd.begin(16, 2);
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("MPU6050 Init");
// Initialize the MPU6050 sensor
if (!mpu.begin()) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("MPU6050 Error");
Serial.println("Failed to find MPU6050 chip");
while (1) {
delay(10);
}
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("MPU6050 Ready");
// Set accelerometer and gyro ranges
mpu.setAccelerometerRange(MPU6050_RANGE_2_G);
mpu.setGyroRange(MPU6050_RANGE_250_DEG);
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
// Initialize the buzzer
pinMode(buzzerPin, OUTPUT);
digitalWrite(buzzerPin, LOW); // Buzzer off initially
}
void loop() {
sensors_event_t a, g, temp;
unsigned long currentMillis = millis();
// Check if it's time to simulate a fall
if (currentMillis - previousMillis >= fallTriggerTime && !fallSimulated) {
// Simulate a fall by creating artificial accelerometer values
a.acceleration.x = 4.5; // Large acceleration in X (simulating a sudden movement)
a.acceleration.y = 4.2; // Large acceleration in Y (simulating a sudden movement)
a.acceleration.z = 0.3; // Low Z value (simulating a free fall)
fallSimulated = true; // Mark the fall as simulated
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Fall Simulated!");
Serial.println("Fall Simulated!");
} else if (!fallSimulated) {
// Read actual sensor data before fall is simulated
mpu.getEvent(&a, &g, &temp);
}
// Display accelerometer values on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("X:");
lcd.print(a.acceleration.x, 1);
lcd.setCursor(8, 0);
lcd.print("Y:");
lcd.print(a.acceleration.y, 1);
lcd.setCursor(0, 1);
lcd.print("Z:");
lcd.print(a.acceleration.z, 1);
// Fall detection logic: if acceleration exceeds a threshold
if (abs(a.acceleration.x) > 3 || abs(a.acceleration.y) > 3 || abs(a.acceleration.z) < 0.5) {
lcd.setCursor(8, 1);
lcd.print("Fall!!");
Serial.println("Fall detected!");
// Activate buzzer
digitalWrite(buzzerPin, HIGH);
tone(buzzerPin,1000);
} else {
// Turn off the buzzer if no fall is detected
digitalWrite(buzzerPin, LOW);
}
delay(500); // Slow down the loop to make the output readable
}