#include <Wire.h>
#include <MPU6050.h>
#include <Buzzer.h>
const int MPU_addr = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
float ax = 0, ay = 0, az = 0, gx = 0, gy = 0, gz = 0;
const int buzzerPin = 2; // Pin for the buzzer
const int buttonPin = 3; // Pin for the push button
boolean fall = false; // Stores if a fall has occurred
int angleChange = 0;
void setup() {
Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // Set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
Serial.begin(9600);
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Assuming a pull-up resistor is used with the button
digitalWrite(buzzerPin, HIGH);
}
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;
// Calculating Amplitude vector for 3 axis
float Raw_AM = pow(pow(ax, 2) + pow(ay, 2) + pow(az, 2), 0.5);
int AM = Raw_AM*1000; // as values are within 0 to 1, I multiplied
// it by for using if else conditions
Serial.println(AM);
// Check if the push button is pressed to turn off the buzzer
if (digitalRead(buttonPin) == LOW) {
digitalWrite(buzzerPin, HIGH);
}
// Check for the acceleration threshold of 500 m/s² (approximately 50g)
if (AM >= 500) { // AM is in 0.1g, so 5000 equals 500 m/s²
digitalWrite(buzzerPin, HIGH); // Activate the buzzer
tone(2, 262, 250);
Serial.println("FALL DETECTED - BUZZER ON");
}
// It appears that delay is needed in order not to clog the port
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)
}