#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
const int triggerPin = 8;
const int echoPin = 9;
const int buzzerPin = 11;
const int ledPin = 10;
const int fallThreshold = 1500; // Adjust this threshold based on your requirements (empirical testing).
const int objectDetectionDistance = 20; // Adjust the distance for object detection.
void setup() {
Wire.begin();
mpu.initialize();
Serial.begin(9600);
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
int16_t ax, ay, az;
mpu.getAcceleration(ax, ay, az);
// Calculate the magnitude of acceleration
float accelerationMagnitude = sqrt(ax * ax + ay * ay + az * az);
// Read distance from the ultrasonic sensor
long duration, distance;
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1; // Convert to centimeters.
// Object detection
if (distance < objectDetectionDistance) {
digitalWrite(ledPin, HIGH); // Turn on LED
digitalWrite(buzzerPin, HIGH); // Turn on Buzzer
Serial.println("Object detected");
} else {
digitalWrite(ledPin, LOW); // Turn off LED
digitalWrite(buzzerPin, LOW); // Turn off Buzzer
}
// Fall detection
if (accelerationMagnitude > fallThreshold) {
digitalWrite(ledPin, HIGH); // Turn on LED
digitalWrite(buzzerPin, HIGH); // Turn on Buzzer
Serial.println("Fall detected");
}
delay(100); // Add a delay to avoid overwhelming the output.
}