#include <Wire.h>
#include <MPU6050.h>
const int MPU_addr = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
MPU6050 mpu;
float ax = 0, ay = 0, az = 0, gx = 0, gy = 0, gz = 0;
const int buzzerPin = 2;
const int buttonPin = 3;
int buttonState = 0;
void setup() {
Serial.begin(9600);
mpu.initialize();
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
mpu_read();
// 2050, 77, 1947 are values for calibration of accelerometer
// values may be different for you
ax = (AcX - 2050) / 16384.00;
ay = (AcY - 77) / 16384.00;
az = (AcZ - 1947) / 16384.00;
// 270, 351, 136 for gyroscope
gx = (GyX + 270) / 131.07;
gy = (GyY - 351) / 131.07;
gz = (GyZ + 136) / 131.07;
// Read acceleration data
float Raw_AM = pow(pow(ax, 2) + pow(ay, 2) + pow(az, 2), 0.5);
int AM = Raw_AM*1000;
// Check if acceleration exceeds 500 m/s²
if (AM >= 500) {
// Turn on the buzzer
digitalWrite(buzzerPin, HIGH);
Serial.println("Fall Detect - BUZZER ON");
tone(2,250,10000);
} else {
// Turn off the buzzer
digitalWrite(buzzerPin, LOW);
}
// Read the state of the push button
buttonState = digitalRead(buttonPin);
// If the button is pressed, turn off the buzzer
if (buttonState == HIGH) {
digitalWrite(buzzerPin, LOW);
Serial.println("Button Push");
}
// Print the acceleration data to the serial monitor
Serial.print("Acceleration (m/s²): ");
Serial.print(AM);
Serial.println();
delay(100);
}
void mpu_read() {
Wire.beginTransmission(MPU_addr);
Wire.write(0x3B); // Starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr, 14, true); // Request a total of 14 registers
AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
}