#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
// Define the I2C pins for ESP32
#define SDA_PIN 21
#define SCL_PIN 22
// Variables to store accelerometer values
int16_t ax, ay, az;
float gForceX, gForceY, gForceZ;
// Threshold for fall detection (adjust as needed)
const float FALL_THRESHOLD = 2.5; // Adjust this threshold value based on your testing
void setup() {
Serial.begin(9600);
Serial.println("Initializing I2C communication...");
// Initialize I2C communication with specified pins
Wire.begin(SDA_PIN, SCL_PIN);
Serial.println("Initializing MPU6050...");
mpu.initialize();
// Check if MPU6050 is connected
if (!mpu.testConnection()) {
Serial.println("MPU6050 connection failed");
while (1);
}
Serial.println("MPU6050 connection successful");
}
void loop() {
// Read accelerometer values
mpu.getAcceleration(&ax, &ay, &az);
// Convert to G forces
gForceX = (float)ax / 16384.0;
gForceY = (float)ay / 16384.0;
gForceZ = (float)az / 16384.0;
// Calculate the magnitude of the vector
float magnitude = sqrt(gForceX * gForceX + gForceY * gForceY + gForceZ * gForceZ);
// Print values for debugging
Serial.print("X: "); Serial.print(gForceX);
Serial.print(" Y: "); Serial.print(gForceY);
Serial.print(" Z: "); Serial.print(gForceZ);
Serial.print(" Magnitude: "); Serial.println(magnitude);
// Check if the magnitude exceeds the fall threshold
if (magnitude > FALL_THRESHOLD) {
Serial.println("Fall detected!");
// You can add more actions here, like sending a notification or triggering an alarm
}
delay(1000);// Adjust delay as needed
}