0% found this document useful (0 votes)
49 views

Arduino Fall Alarm Code

arduino mpu 6050 code

Uploaded by

uditmishra2911
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Arduino Fall Alarm Code

arduino mpu 6050 code

Uploaded by

uditmishra2911
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Arduino Fall Alarm Code

write an arduino uno code to make fall alarm using


mpu6050

To create a fall detection alarm using an MPU6050 (accelerometer and gyroscope) with an
Arduino Uno, you can detect a sudden change in acceleration or orientation that could
indicate a fall. Here’s a basic code that sets up the MPU6050 and triggers an alarm when a
fall is detected.

You'll need:

An Arduino Uno

An MPU6050 sensor

A buzzer or LED for the alarm

Wiring:
1. Connect the MPU6050 to the Arduino using I2C:

VCC → 5V

GND → GND

SDA → A4

SCL → A5

2. Connect the buzzer or LED:

Positive lead of the buzzer/LED → Pin 9

Negative lead → GND

Arduino Code:

cpp

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;
int buzzerPin = 9; // Pin for the buzzer/LED

void setup() {

1/34
Wire.begin();
Serial.begin(115200);

// Initialize the MPU6050


Serial.println("Initializing MPU6050...");
mpu.initialize();

// Check if MPU6050 is connected properly


if (mpu.testConnection()) {
Serial.println("MPU6050 connection successful");
} else {
Serial.println("MPU6050 connection failed");
while (1);
}

// Setup buzzer/LED pin


pinMode(buzzerPin, OUTPUT);
}

void loop() {
int16_t ax, ay, az; // Acceleration values
int16_t gx, gy, gz; // Gyroscope values

// Get acceleration and gyroscope readings


mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

// Convert acceleration from raw values to G-forces


float accelX = ax / 16384.0;
float accelY = ay / 16384.0;
float accelZ = az / 16384.0;

// Calculate total acceleration


float totalAccel = sqrt(sq(accelX) + sq(accelY) + sq(accelZ));

// Fall detection threshold (example: if the total acceleration falls below 0.5G)
if (totalAccel < 0.5) {
// Trigger alarm (turn on the buzzer or LED)
digitalWrite(buzzerPin, HIGH);
Serial.println("Fall detected!");
} else {
// Turn off the alarm
digitalWrite(buzzerPin, LOW);

2/34
}

// Optional: Print acceleration values for debugging


Serial.print("AccelX: "); Serial.print(accelX);
Serial.print(" AccelY: "); Serial.print(accelY);
Serial.print(" AccelZ: "); Serial.println(accelZ);

delay(200); // Wait for 200ms before next reading


}

Explanation:
1. MPU6050 Initialization: The MPU6050 sensor is initialized using I2C communication.

2. Acceleration Reading: The code reads acceleration in the X, Y, and Z axes. The values are
converted into G-forces (1G ≈ 9.8 m/s²).

3. Fall Detection: A fall is detected when the total acceleration is below a certain threshold,
indicating a free fall or impact. In this case, a threshold of 0.5G is used, but you can
adjust this depending on your application.

4. Alarm: If a fall is detected, the buzzer or LED is activated.

Let me know if you'd like to adjust the fall sensitivity or add additional features!

explain each line using comments

Here's the code with detailed comments explaining each line:

cpp

#include <Wire.h> // Include the Wire library for I2C communication


#include <MPU6050.h> // Include the MPU6050 library to interface with the
sensor

MPU6050 mpu; // Create an MPU6050 object called "mpu"


int buzzerPin = 9; // Define pin 9 for the buzzer or LED

void setup() {
Wire.begin(); // Initialize the I2C communication
Serial.begin(115200); // Start the serial communication at 115200 baud rate for
debugging

// Initialize the MPU6050 sensor

3/34
Serial.println("Initializing MPU6050...");
mpu.initialize(); // Call the function to initialize the MPU6050 sensor

// Check if the MPU6050 is successfully connected to the Arduino


if (mpu.testConnection()) {
Serial.println("MPU6050 connection successful"); // Print message if the
connection is successful
} else {
Serial.println("MPU6050 connection failed"); // Print message if the
connection fails
while (1); // Stay in an infinite loop (program halts) if the connection
fails
}

pinMode(buzzerPin, OUTPUT); // Set the buzzer/LED pin as an output pin


}

void loop() {
int16_t ax, ay, az; // Declare variables for the raw acceleration values (X, Y,
Z)
int16_t gx, gy, gz; // Declare variables for the raw gyroscope values (X, Y, Z)

// Get acceleration and gyroscope data from the MPU6050


mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

// Convert raw acceleration values (ax, ay, az) to G-forces


// Divide by 16384 because the MPU6050 outputs values with a sensitivity of 16384
LSB/g in +/-2g mode
float accelX = ax / 16384.0; // Convert raw X-axis acceleration to G-force
float accelY = ay / 16384.0; // Convert raw Y-axis acceleration to G-force
float accelZ = az / 16384.0; // Convert raw Z-axis acceleration to G-force

// Calculate total acceleration using the 3D vector magnitude formula


// sqrt(x^2 + y^2 + z^2)
float totalAccel = sqrt(sq(accelX) + sq(accelY) + sq(accelZ));

// Check if total acceleration falls below the threshold of 0.5G (indicating a


possible fall)
if (totalAccel < 0.5) {
// If a fall is detected, turn on the buzzer or LED
digitalWrite(buzzerPin, HIGH); // Activate buzzer or LED
Serial.println("Fall detected!"); // Print a message for debugging

4/34
} else {
// If no fall is detected, turn off the buzzer or LED
digitalWrite(buzzerPin, LOW); // Deactivate buzzer or LED
}

// Print acceleration values for debugging purposes (optional)


Serial.print("AccelX: "); Serial.print(accelX);
Serial.print(" AccelY: "); Serial.print(accelY);
Serial.print(" AccelZ: "); Serial.println(accelZ);

delay(200); // Wait for 200 milliseconds before taking the next reading
}

Breakdown of Key Parts:


1. Include Libraries:

Wire.h : Handles I2C communication.

MPU6050.h : Provides functions to interact with the MPU6050 sensor.

2. Setup:

Initializes communication with the MPU6050 and checks if it's connected.

Sets up the pin for the buzzer/LED.

3. Loop:

Continuously reads acceleration data.

Converts raw data to G-force units.

Calculates the total acceleration to detect a fall.

Triggers an alarm (buzzer or LED) if a fall is detected.

Would you like to modify the code further or adjust specific values?

the device should also show live acceleration and angular


axis too in ide output

To display both the live acceleration (in G-force) and angular velocity (in degrees per second)
values in the Serial Monitor of the Arduino IDE, you need to extract the gyroscope data along
with the accelerometer data and print them out. Here's how to modify the code to achieve
this:

5/34
Modified Arduino Code:

cpp

#include <Wire.h> // Include the Wire library for I2C communication


#include <MPU6050.h> // Include the MPU6050 library to interface with the
sensor

MPU6050 mpu; // Create an MPU6050 object called "mpu"


int buzzerPin = 9; // Define pin 9 for the buzzer or LED

void setup() {
Wire.begin(); // Initialize the I2C communication
Serial.begin(115200); // Start the serial communication at 115200 baud rate for
debugging

// Initialize the MPU6050 sensor


Serial.println("Initializing MPU6050...");
mpu.initialize(); // Call the function to initialize the MPU6050 sensor

// Check if the MPU6050 is successfully connected to the Arduino


if (mpu.testConnection()) {
Serial.println("MPU6050 connection successful"); // Print message if the
connection is successful
} else {
Serial.println("MPU6050 connection failed"); // Print message if the
connection fails
while (1); // Stay in an infinite loop (program halts) if the connection
fails
}

pinMode(buzzerPin, OUTPUT); // Set the buzzer/LED pin as an output pin


}

void loop() {
int16_t ax, ay, az; // Declare variables for the raw acceleration values (X, Y,
Z)
int16_t gx, gy, gz; // Declare variables for the raw gyroscope values (X, Y, Z)

// Get acceleration and gyroscope data from the MPU6050


mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

6/34
// Convert raw acceleration values (ax, ay, az) to G-forces
float accelX = ax / 16384.0; // Convert raw X-axis acceleration to G-force
float accelY = ay / 16384.0; // Convert raw Y-axis acceleration to G-force
float accelZ = az / 16384.0; // Convert raw Z-axis acceleration to G-force

// Convert raw gyroscope values (gx, gy, gz) to degrees per second
float gyroX = gx / 131.0; // Convert raw X-axis gyroscope data to degrees/sec
float gyroY = gy / 131.0; // Convert raw Y-axis gyroscope data to degrees/sec
float gyroZ = gz / 131.0; // Convert raw Z-axis gyroscope data to degrees/sec

// Calculate total acceleration using the 3D vector magnitude formula


float totalAccel = sqrt(sq(accelX) + sq(accelY) + sq(accelZ));

// Check if total acceleration falls below the threshold of 0.5G (indicating a


possible fall)
if (totalAccel < 0.5) {
// If a fall is detected, turn on the buzzer or LED
digitalWrite(buzzerPin, HIGH); // Activate buzzer or LED
Serial.println("Fall detected!"); // Print a message for debugging
} else {
// If no fall is detected, turn off the buzzer or LED
digitalWrite(buzzerPin, LOW); // Deactivate buzzer or LED
}

// Print acceleration and gyroscope values for live monitoring


Serial.print("Accel (G) -> X: "); Serial.print(accelX);
Serial.print(" Y: "); Serial.print(accelY);
Serial.print(" Z: "); Serial.println(accelZ);

Serial.print("Gyro (deg/sec) -> X: "); Serial.print(gyroX);


Serial.print(" Y: "); Serial.print(gyroY);
Serial.print(" Z: "); Serial.println(gyroZ);

// Print a separator for better readability


Serial.println("---------------------------");

delay(200); // Wait for 200 milliseconds before taking the next reading
}

Key Changes:
1. Gyroscope Data:

7/34
Raw gyroscope data ( gx , gy , gz ) is retrieved from the MPU6050.

The raw values are converted into degrees per second by dividing by 131 (the
sensitivity scale factor in +/-250 degrees/sec mode).

2. Serial Output:

Added Serial.print statements to display the acceleration values (in G-force) and
gyroscope values (in degrees per second) for the X, Y, and Z axes.

Separated acceleration and gyroscope readings with labels and a separator line for
readability in the Serial Monitor.

Live Output in Arduino IDE:


When you open the Serial Monitor (set to 115200 baud), you’ll see live data similar to this:

markdown

Accel (G) -> X: 0.02 Y: 0.98 Z: 1.01


Gyro (deg/sec) -> X: 0.12 Y: -0.02 Z: 0.05
---------------------------
Accel (G) -> X: 0.01 Y: 0.97 Z: 1.02
Gyro (deg/sec) -> X: 0.10 Y: -0.03 Z: 0.04
---------------------------
...

This shows real-time acceleration in G-force and angular velocity in degrees per second for
all three axes.

Let me know if you'd like to adjust anything further!

does sensor need any calibration

Yes, the MPU6050 sensor typically benefits from calibration to improve the accuracy of the
accelerometer and gyroscope readings. Calibration compensates for sensor biases such as
offsets, which can cause the sensor to return non-zero values even when the device is
stationary.

Why Calibration is Important:


Accelerometer: When the sensor is perfectly stationary and flat, it should read 0 G for
the X and Y axes, and 1 G for the Z-axis (due to gravity). However, it might return

8/34
slightly different values because of small manufacturing imperfections or environmental
conditions.

Gyroscope: When the sensor is stationary, the gyroscope should ideally read 0°/s on all
three axes (X, Y, Z). Any non-zero readings are considered bias or drift.

How to Calibrate the MPU6050:


1. Accelerometer Calibration: This involves calculating offsets for the X, Y, and Z axes so
that when the sensor is stationary, the output becomes close to the expected values (0 G
for X and Y, 1 G for Z).

2. Gyroscope Calibration: When the sensor is stationary, the gyroscope output should be
zero on all axes. The offsets for the gyroscope are subtracted from the raw values to
ensure accurate angular velocity measurements.

You can either hard-code the offsets in your Arduino program, or dynamically calculate them
during setup. Below is an example of how to perform a basic calibration and apply offsets in
your code.

Code with Calibration:

cpp

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;
int buzzerPin = 9; // Pin for the buzzer or LED

// Variables to store offsets


float accelX_offset = 0, accelY_offset = 0, accelZ_offset = 0;
float gyroX_offset = 0, gyroY_offset = 0, gyroZ_offset = 0;

void setup() {
Wire.begin();
Serial.begin(115200);

// Initialize the MPU6050


Serial.println("Initializing MPU6050...");
mpu.initialize();

// Check if MPU6050 is connected properly

9/34
if (mpu.testConnection()) {
Serial.println("MPU6050 connection successful");
} else {
Serial.println("MPU6050 connection failed");
while (1);
}

pinMode(buzzerPin, OUTPUT);

// Perform calibration
calibrateSensor();
}

void loop() {
int16_t ax, ay, az; // Raw acceleration values
int16_t gx, gy, gz; // Raw gyroscope values

// Get raw acceleration and gyroscope data


mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

// Apply calibration offsets to acceleration


float accelX = (ax / 16384.0) - accelX_offset;
float accelY = (ay / 16384.0) - accelY_offset;
float accelZ = (az / 16384.0) - accelZ_offset;

// Apply calibration offsets to gyroscope


float gyroX = (gx / 131.0) - gyroX_offset;
float gyroY = (gy / 131.0) - gyroY_offset;
float gyroZ = (gz / 131.0) - gyroZ_offset;

// Calculate total acceleration


float totalAccel = sqrt(sq(accelX) + sq(accelY) + sq(accelZ));

// Fall detection logic


if (totalAccel < 0.5) {
digitalWrite(buzzerPin, HIGH);
Serial.println("Fall detected!");
} else {
digitalWrite(buzzerPin, LOW);
}

// Print live acceleration and gyroscope data

10/34
Serial.print("Accel (G) -> X: "); Serial.print(accelX);
Serial.print(" Y: "); Serial.print(accelY);
Serial.print(" Z: "); Serial.println(accelZ);

Serial.print("Gyro (deg/sec) -> X: "); Serial.print(gyroX);


Serial.print(" Y: "); Serial.print(gyroY);
Serial.print(" Z: "); Serial.println(gyroZ);

Serial.println("---------------------------");

delay(200); // Wait before the next reading


}

// Function to perform sensor calibration


void calibrateSensor() {
int numReadings = 1000;
long axSum = 0, aySum = 0, azSum = 0;
long gxSum = 0, gySum = 0, gzSum = 0;

// Take multiple readings to average out the sensor bias


for (int i = 0; i < numReadings; i++) {
int16_t ax, ay, az, gx, gy, gz;
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

axSum += ax;
aySum += ay;
azSum += az;
gxSum += gx;
gySum += gy;
gzSum += gz;

delay(2); // Small delay between readings


}

// Calculate average offsets for acceleration


accelX_offset = (axSum / numReadings) / 16384.0;
accelY_offset = (aySum / numReadings) / 16384.0;
// For accelZ, gravity (1G) is present, so we subtract 1 to normalize the Z-axis
accelZ_offset = ((azSum / numReadings) / 16384.0) - 1.0;

// Calculate average offsets for gyroscope


gyroX_offset = (gxSum / numReadings) / 131.0;

11/34
gyroY_offset = (gySum / numReadings) / 131.0;
gyroZ_offset = (gzSum / numReadings) / 131.0;

Serial.println("Calibration complete");
}

What the Code Does:


1. Calibration Process:

The calibrateSensor() function takes multiple readings (1000 in this case) to


calculate the average raw sensor values when the MPU6050 is stationary.

It calculates offsets for the accelerometer and gyroscope, which are subtracted from
the raw sensor data during the main loop to correct for biases.

For the Z-axis of the accelerometer, the offset accounts for the presence of 1G due to
gravity.

2. Application of Offsets:

The offsets are subtracted from the raw accelerometer and gyroscope readings in
the main loop before converting them to G-forces and degrees per second, ensuring
that the readings are more accurate.

How to Use:
1. Ensure that the MPU6050 is stationary (e.g., place it flat on a table) when performing
calibration.

2. The program will print "Calibration complete" once it finishes.

3. After calibration, the sensor should output more accurate acceleration and angular
velocity values.

Let me know if you need any further adjustments!

write only for calliberation

Here's a standalone code for calibrating the MPU6050 sensor. This code will calculate and
print the calibration offsets for both the accelerometer and gyroscope, which you can use
later in your project.

Calibration Code for MPU6050:

12/34
cpp

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

void setup() {
Wire.begin();
Serial.begin(115200);

// Initialize the MPU6050


Serial.println("Initializing MPU6050...");
mpu.initialize();

// Check if MPU6050 is connected properly


if (mpu.testConnection()) {
Serial.println("MPU6050 connection successful");
} else {
Serial.println("MPU6050 connection failed");
while (1);
}

// Perform calibration
calibrateSensor();
}

void loop() {
// Calibration runs once in setup, no need to repeat in loop
}

void calibrateSensor() {
int numReadings = 1000; // Number of readings for calibration
long axSum = 0, aySum = 0, azSum = 0;
long gxSum = 0, gySum = 0, gzSum = 0;

// Take multiple readings to average out the sensor bias


for (int i = 0; i < numReadings; i++) {
int16_t ax, ay, az, gx, gy, gz;
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

axSum += ax;
aySum += ay;

13/34
azSum += az;
gxSum += gx;
gySum += gy;
gzSum += gz;

delay(2); // Small delay between readings


}

// Calculate average offsets for accelerometer


float accelX_offset = (axSum / numReadings) / 16384.0;
float accelY_offset = (aySum / numReadings) / 16384.0;
// For accelZ, gravity (1G) is present, so we subtract 1 to normalize the Z-axis
float accelZ_offset = ((azSum / numReadings) / 16384.0) - 1.0;

// Calculate average offsets for gyroscope


float gyroX_offset = (gxSum / numReadings) / 131.0;
float gyroY_offset = (gySum / numReadings) / 131.0;
float gyroZ_offset = (gzSum / numReadings) / 131.0;

// Print calibration offsets


Serial.println("Calibration Complete:");
Serial.print("Accelerometer Offsets -> X: "); Serial.print(accelX_offset);
Serial.print(" Y: "); Serial.print(accelY_offset);
Serial.print(" Z: "); Serial.println(accelZ_offset);

Serial.print("Gyroscope Offsets -> X: "); Serial.print(gyroX_offset);


Serial.print(" Y: "); Serial.print(gyroY_offset);
Serial.print(" Z: "); Serial.println(gyroZ_offset);
}

What the Code Does:


1. Sensor Initialization: Initializes the MPU6050 and checks the connection.

2. Calibration:

It reads the sensor 1000 times to compute an average for each axis (X, Y, Z) for both
the accelerometer and gyroscope.

The average values are used to compute the calibration offsets.

3. Calibration Results: Prints out the accelerometer and gyroscope offsets. These values
can be used in your main code to adjust the raw sensor readings.

14/34
How to Use:
1. Upload this code to your Arduino while keeping the MPU6050 stationary (on a flat
surface).

2. Open the Serial Monitor (set to 115200 baud rate).

3. After calibration is complete, the offsets will be printed. These offsets should be
subtracted from your sensor readings in future programs for better accuracy.

Let me know if you need any adjustments!

i dont have serial monitor

If you don't have access to the Serial Monitor to view the calibration values, you can modify
the code to use LEDs or a buzzer to signal the completion of calibration. While you won't be
able to see the exact calibration values directly, you can at least know when the calibration is
finished, and then use pre-calculated or hardcoded calibration offsets in your main code.

Steps for Using Hardcoded Calibration Offsets:


1. Run the code on a device that has access to the Serial Monitor to obtain the offsets once.

2. Hardcode the offsets into your final project code, so calibration doesn't need to be
repeated every time.

Since you mentioned not having a Serial Monitor, here's how to modify the calibration code
to signal calibration completion with a buzzer or LED:

Modified Code Using a Buzzer/LED for Completion:

cpp

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;
int buzzerPin = 9; // Pin for the buzzer or LED

// Hardcoded calibration offsets (pre-calculated from another run with a Serial


Monitor)
float accelX_offset = 0.0, accelY_offset = 0.0, accelZ_offset = 0.0;
float gyroX_offset = 0.0, gyroY_offset = 0.0, gyroZ_offset = 0.0;

15/34
void setup() {
Wire.begin();

pinMode(buzzerPin, OUTPUT); // Set the buzzer/LED pin as an output

// Initialize the MPU6050


mpu.initialize();

// Check if MPU6050 is connected properly


if (mpu.testConnection()) {
// Optional: Flash LED or buzz briefly to indicate connection success
tone(buzzerPin, 1000, 500); // Play tone (1kHz) for 500ms
delay(500); // Wait to ensure tone is complete
} else {
while (1); // Stop execution if the sensor is not connected
}

// Perform calibration
calibrateSensor();
}

void loop() {
// Nothing needed here, as we only calibrate once during setup
}

// Function to calibrate sensor and signal completion


void calibrateSensor() {
int numReadings = 1000; // Number of readings for calibration
long axSum = 0, aySum = 0, azSum = 0;
long gxSum = 0, gySum = 0, gzSum = 0;

// Take multiple readings to average out sensor bias


for (int i = 0; i < numReadings; i++) {
int16_t ax, ay, az, gx, gy, gz;
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

axSum += ax;
aySum += ay;
azSum += az;
gxSum += gx;
gySum += gy;
gzSum += gz;

16/34
delay(2); // Small delay between readings
}

// Calculate average offsets for accelerometer


accelX_offset = (axSum / numReadings) / 16384.0;
accelY_offset = (aySum / numReadings) / 16384.0;
// For accelZ, gravity (1G) is present, so we subtract 1 to normalize Z-axis
accelZ_offset = ((azSum / numReadings) / 16384.0) - 1.0;

// Calculate average offsets for gyroscope


gyroX_offset = (gxSum / numReadings) / 131.0;
gyroY_offset = (gySum / numReadings) / 131.0;
gyroZ_offset = (gzSum / numReadings) / 131.0;

// Signal calibration completion by turning on the buzzer or LED


tone(buzzerPin, 1000, 1000); // Play tone (1kHz) for 1 second
delay(1000); // Wait for tone to finish
noTone(buzzerPin); // Ensure the buzzer turns off
}

Key Changes:
1. No Serial Monitor: The Serial Monitor code is removed, and a buzzer or LED signals
when the MPU6050 is connected and when calibration is complete.

2. Buzzer Indications:

A short tone (1 kHz for 500ms) plays if the MPU6050 is successfully connected.

After the calibration is complete, a longer tone (1 kHz for 1 second) plays to signal
that the process has finished.

3. Hardcoded Calibration Offsets:

You can replace the placeholder values ( accelX_offset , gyroX_offset , etc.) with
actual offsets that you obtain from another run where you have access to the Serial
Monitor.

How to Use:
1. Run Once with Serial Monitor: Obtain the calibration offsets by running the code on a
device that supports the Serial Monitor.

17/34
2. Hardcode Offsets: Replace the calibration offsets in the code with the values you obtain.

3. Final Setup: Upload the modified code to your device, and the buzzer will notify you
when calibration is complete. You won't need the Serial Monitor anymore.

Let me know if you need further clarification or adjustments!

#include <Wire.h> // Include the Wire library for I2C


communication
#include <MPU6050.h> // Include the MPU6050 library to
interface with the sensor

MPU6050 mpu; // Create an MPU6050 object called


"mpu"
int buzzerPin = 9; // Define pin 9 for the buzzer or LED

void setup() {
Wire.begin(); // Initialize the I2C communication
Serial.begin(115200); // Start the serial communication at
115200 baud rate for debugging

// Initialize the MPU6050 sensor


Serial.println("Initializing MPU6050...");
mpu.initialize(); // Call the function to initialize the
MPU6050 sensor

// Check if the MPU6050 is successfully connected to the


Arduino
if (mpu.testConnection()) {
Serial.println("MPU6050 connection successful"); // Print
message if the connection is successful
} else {
Serial.println("MPU6050 connection failed"); // Print
message if the connection fails
while (1); // Stay in an infinite loop (program halts) if
the connection fails
}

pinMode(buzzerPin, OUTPUT); // Set the buzzer/LED pin


as an output pin
}

18/34
void loop() {
int16_t ax, ay, az; // Declare variables for the raw
acceleration values (X, Y, Z)
int16_t gx, gy, gz; // Declare variables for the raw
gyroscope values (X, Y, Z)

// Get acceleration and gyroscope data from the MPU6050


mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

// Convert raw acceleration values (ax, ay, az) to G-forces


// Divide by 16384 because the MPU6050 outputs values
with a sensitivity of 16384 LSB/g in +/-2g mode
float accelX = ax / 16384.0; // Convert raw X-axis
acceleration to G-force
float accelY = ay / 16384.0; // Convert raw Y-axis
acceleration to G-force
float accelZ = az / 16384.0; // Convert raw Z-axis
acceleration to G-force

// Calculate total acceleration using the 3D vector


magnitude formula
// sqrt(x^2 + y^2 + z^2)
float totalAccel = sqrt(sq(accelX) + sq(accelY) + sq(accelZ));

// Check if total acceleration falls below the threshold of


0.5G (indicating a possible fall)
if (totalAccel < 0.5) {
// If a fall is detected, turn on the buzzer or LED
digitalWrite(buzzerPin, HIGH); // Activate buzzer or LED
Serial.println("Fall detected!"); // Print a message for
debugging
} else {
// If no fall is detected, turn off the buzzer or LED
digitalWrite(buzzerPin, LOW); // Deactivate buzzer or
LED
}

// Print acceleration values for debugging purposes


(optional)
Serial.print("AccelX: "); Serial.print(accelX);
Serial.print(" AccelY: "); Serial.print(accelY);
Serial.print(" AccelZ: "); Serial.println(accelZ);

19/34
delay(200); // Wait for 200 milliseconds before taking the
next reading
} also include a switch to restart detecting

You can add a push-button switch to reset or restart the fall detection process. When the
button is pressed, it can either reset the fall alarm (by turning off the buzzer) or restart the
detection logic.

Here's how to modify your code to include a switch:

Code with a Reset Switch:


cpp

#include <Wire.h> // Include the Wire library for I2C communication


#include <MPU6050.h> // Include the MPU6050 library to interface with the
sensor

MPU6050 mpu; // Create an MPU6050 object called "mpu"


int buzzerPin = 9; // Define pin 9 for the buzzer or LED
int switchPin = 8; // Define pin 8 for the reset button
bool fallDetected = false; // A flag to track if a fall has been detected

void setup() {
Wire.begin(); // Initialize the I2C communication
Serial.begin(115200); // Start the serial communication at 115200 baud rate for
debugging

// Initialize the MPU6050 sensor


Serial.println("Initializing MPU6050...");
mpu.initialize(); // Call the function to initialize the MPU6050 sensor

// Check if the MPU6050 is successfully connected to the Arduino


if (mpu.testConnection()) {
Serial.println("MPU6050 connection successful"); // Print message if the
connection is successful
} else {
Serial.println("MPU6050 connection failed"); // Print message if the
connection fails
while (1); // Stay in an infinite loop (program halts) if the connection
fails
}

20/34
pinMode(buzzerPin, OUTPUT); // Set the buzzer/LED pin as an output pin
pinMode(switchPin, INPUT_PULLUP); // Set the switch pin as input with an internal
pull-up resistor
}

void loop() {
// Check if the reset button is pressed
if (digitalRead(switchPin) == LOW) {
// If the button is pressed, reset the fall detection alarm
fallDetected = false; // Reset the fall detection flag
digitalWrite(buzzerPin, LOW); // Turn off the buzzer
Serial.println("Fall alarm reset.");
delay(500); // Debounce the button press
}

// Continue fall detection only if no fall has been detected yet


if (!fallDetected) {
int16_t ax, ay, az; // Declare variables for the raw acceleration values (X, Y,
Z)
int16_t gx, gy, gz; // Declare variables for the raw gyroscope values (X, Y, Z)

// Get acceleration and gyroscope data from the MPU6050


mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

// Convert raw acceleration values (ax, ay, az) to G-forces


float accelX = ax / 16384.0; // Convert raw X-axis acceleration to G-force
float accelY = ay / 16384.0; // Convert raw Y-axis acceleration to G-force
float accelZ = az / 16384.0; // Convert raw Z-axis acceleration to G-force

// Calculate total acceleration using the 3D vector magnitude formula


float totalAccel = sqrt(sq(accelX) + sq(accelY) + sq(accelZ));

// Check if total acceleration falls below the threshold of 0.5G (indicating a


possible fall)
if (totalAccel < 0.5) {
// If a fall is detected, turn on the buzzer or LED and set the fallDetected
flag
digitalWrite(buzzerPin, HIGH); // Activate buzzer or LED
Serial.println("Fall detected!"); // Print a message for debugging
fallDetected = true; // Set the fall detection flag
}

21/34
// Print acceleration values for debugging purposes (optional)
Serial.print("AccelX: "); Serial.print(accelX);
Serial.print(" AccelY: "); Serial.print(accelY);
Serial.print(" AccelZ: "); Serial.println(accelZ);

delay(200); // Wait for 200 milliseconds before taking the next reading
}
}

Key Changes:
1. Switch Pin Setup: The switch is connected to pin 8 and uses the internal pull-up resistor
( INPUT_PULLUP ). When the button is pressed, it grounds the pin and registers a LOW
signal.

2. Fall Detection Flag ( fallDetected ):

A flag fallDetected is used to keep track of whether a fall has already been
detected.

Once a fall is detected, the buzzer stays on, and the program will stop checking for
new falls until the button is pressed.

3. Button to Reset the Alarm:

When the button connected to switchPin is pressed, the fallDetected flag is


reset, and the buzzer or LED is turned off.

The program then continues monitoring for new falls.

4. Debouncing: A delay(500) after detecting a button press is added to debounce the


button, ensuring it doesn't register multiple presses from a single button press.

Hardware Connections:
1. Buzzer or LED: Connect the buzzer or LED to pin 9 and ground.

2. Button: Connect one side of the button to pin 8 and the other side to ground (since
we're using INPUT_PULLUP mode).

Let me know if you'd like further adjustments!

#include<Wire.h>
#include<MPU6050.h>

22/34
MPU6050 mpu;

void setup() {
Serial.begin(115200);

Serial.println("Initialize MPU6050");

while(!mpu.begin(MPU6050_SCALE_2000DPS,
MPU6050_RANGE_2G)){
Serial.println("Could not find a valid MPU6050 sensor,
check wiring!");
delay(500);
}

// If you want, you can set accelerometer offsets


// mpu.setAccelOffsetX();
// mpu.setAccelOffsetY();
// mpu.setAccelOffsetZ();

checkSettings();
}

void checkSettings()
{
Serial.println();

Serial.print(" * Sleep Mode: ");


Serial.println(mpu.getSleepEnabled() ? "Enabled" :
"Disabled");

Serial.print(" * Clock Source: ");


switch(mpu.getClockSource())
{
case MPU6050_CLOCK_KEEP_RESET:
Serial.println("Stops the clock and keeps the timing
generator in reset"); break;
case MPU6050_CLOCK_EXTERNAL_19MHZ:
Serial.println("PLL with external 19.2MHz reference"); break;
case MPU6050_CLOCK_EXTERNAL_32KHZ:
Serial.println("PLL with external 32.768kHz reference");
break;

23/34
case MPU6050_CLOCK_PLL_ZGYRO: Serial.println("PLL
with Z axis gyroscope reference"); break;
case MPU6050_CLOCK_PLL_YGYRO: Serial.println("PLL
with Y axis gyroscope reference"); break;
case MPU6050_CLOCK_PLL_XGYRO: Serial.println("PLL
with X axis gyroscope reference"); break;
case MPU6050_CLOCK_INTERNAL_8MHZ:
Serial.println("Internal 8MHz oscillator"); break;
}

Serial.print(" * Accelerometer: ");


switch(mpu.getRange()){
case MPU6050_RANGE_16G: Serial.println("+/- 16
g"); break;
case MPU6050_RANGE_8G: Serial.println("+/- 8 g");
break;
case MPU6050_RANGE_4G: Serial.println("+/- 4 g");
break;
case MPU6050_RANGE_2G: Serial.println("+/- 2 g");
break;
}

Serial.print(" * Accelerometer offsets: ");


Serial.print(mpu.getAccelOffsetX());
Serial.print(" / ");
Serial.print(mpu.getAccelOffsetY());
Serial.print(" / ");
Serial.println(mpu.getAccelOffsetZ());

Serial.println();
}

void loop() {
Vector rawAccel = mpu.readRawAccel();
Vector normAccel = mpu.readNormalizeAccel();

Serial.print(" Xraw = ");


Serial.print(rawAccel.XAxis);
Serial.print(" Yraw = ");
Serial.print(rawAccel.YAxis);
Serial.print(" Zraw = ");

24/34
Serial.println(rawAccel.ZAxis);
Serial.print(" Xnorm = ");
Serial.print(normAccel.XAxis);
Serial.print(" Ynorm = ");
Serial.print(normAccel.YAxis);
Serial.print(" Znorm = ");
Serial.println(normAccel.ZAxis);

delay(10);
} code is showing errors

The code you provided seems to use functions and methods that are likely part of a different
MPU6050 library. The library you're using in your code appears to be different from the
common MPU6050 library typically used in Arduino projects.

To fix the issues, we need to ensure you're using the correct library and its functions. Based
on your code, it looks like you're mixing function calls from different libraries (e.g.,
mpu.begin is from a different library than mpu.getClockSource() ).

Let’s break this down step by step:

1. Check the Library: Make sure you are using the correct library for the MPU6050. There
are a couple of different ones, and the function calls differ between them. You might be
mixing them up.

The code you're using seems to refer to the MPU6050_light or Adafruit_MPU6050


library, but some of the functions are specific to the MPU6050 library by Jeff
Rowberg.

2. Correct the Code: Here’s a working version of the code that uses the correct MPU6050
library (you can install it through the Library Manager in the Arduino IDE by searching
for "MPU6050" by Jeff Rowberg).

Working MPU6050 Code:

cpp

#include <Wire.h>
#include <MPU6050.h> // Make sure to install this library by Jeff Rowberg

MPU6050 mpu;

void setup() {
Serial.begin(115200);

25/34
Wire.begin(); // Start I2C communication

Serial.println("Initializing MPU6050...");

// Initialize the MPU6050


if (!mpu.testConnection()) {
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
while (1); // Stay in loop if the sensor is not found
}

// Initialize the MPU6050 and set it to the default settings


mpu.initialize();

// Optional: set accelerometer offsets


// mpu.setXAccelOffset();
// mpu.setYAccelOffset();
// mpu.setZAccelOffset();

// Check settings and configuration


checkSettings();
}

void checkSettings() {
Serial.println();

// Check if sleep mode is enabled


Serial.print(" * Sleep Mode: ");
Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");

// Check the clock source


Serial.print(" * Clock Source: ");
switch (mpu.getClockSource()) {
case MPU6050_CLOCK_KEEP_RESET: Serial.println("Stops the clock and keeps the
timing generator in reset"); break;
case MPU6050_CLOCK_EXTERNAL_19MHZ: Serial.println("PLL with external 19.2MHz
reference"); break;
case MPU6050_CLOCK_EXTERNAL_32KHZ: Serial.println("PLL with external 32.768kHz
reference"); break;
case MPU6050_CLOCK_PLL_ZGYRO: Serial.println("PLL with Z axis gyroscope
reference"); break;
case MPU6050_CLOCK_PLL_YGYRO: Serial.println("PLL with Y axis gyroscope
reference"); break;

26/34
case MPU6050_CLOCK_PLL_XGYRO: Serial.println("PLL with X axis gyroscope
reference"); break;
case MPU6050_CLOCK_INTERNAL_8MHZ: Serial.println("Internal 8MHz oscillator");
break;
}

// Check accelerometer range


Serial.print(" * Accelerometer: ");
switch (mpu.getFullScaleAccelRange()) {
case MPU6050_ACCEL_FS_2: Serial.println("+/- 2 g"); break;
case MPU6050_ACCEL_FS_4: Serial.println("+/- 4 g"); break;
case MPU6050_ACCEL_FS_8: Serial.println("+/- 8 g"); break;
case MPU6050_ACCEL_FS_16: Serial.println("+/- 16 g"); break;
}

// Check accelerometer offsets


Serial.print(" * Accelerometer offsets: ");
Serial.print(mpu.getXAccelOffset());
Serial.print(" / ");
Serial.print(mpu.getYAccelOffset());
Serial.print(" / ");
Serial.println(mpu.getZAccelOffset());

Serial.println();
}

void loop() {
// Variables for raw accelerometer data
int16_t ax, ay, az;

// Get the raw acceleration values


mpu.getAcceleration(&ax, &ay, &az);

// Convert raw accelerometer values to G-forces


float accelX = ax / 16384.0;
float accelY = ay / 16384.0;
float accelZ = az / 16384.0;

// Print raw and normalized acceleration values


Serial.print("Xraw = "); Serial.print(ax); Serial.print(" Yraw = ");
Serial.print(ay); Serial.print(" Zraw = "); Serial.println(az);
Serial.print("Xnorm = "); Serial.print(accelX); Serial.print(" Ynorm = ");

27/34
Serial.print(accelY); Serial.print(" Znorm = "); Serial.println(accelZ);

delay(100);
}

Key Changes:
1. Library and Functions:

This code assumes you’re using the MPU6050 library by Jeff Rowberg, which can be
installed through the Arduino Library Manager.

The correct function to get acceleration values is mpu.getAcceleration(&ax, &ay,


&az) instead of readRawAccel() or readNormalizeAccel() .

2. Serial Output:

The code will now output the raw acceleration data as well as the normalized G-
forces for each axis.

How to Install the Correct Library:


1. In the Arduino IDE, go to Sketch -> Include Library -> Manage Libraries.

2. Search for MPU6050 by Jeff Rowberg.

3. Install the library.

This should resolve the issues you're facing with the code. Let me know if you encounter any
further problems!

C:\Users\uditm_27jdw1v\AppData\Local\Temp\.arduinoIDE-
unsaved2024822-1096-
b9e7m8.w059q\sketch_sep22a\sketch_sep22a.ino: In
function 'void checkSettings()':
C:\Users\uditm_27jdw1v\AppData\Local\Temp\.arduinoIDE-
unsaved2024822-1096-
b9e7m8.w059q\sketch_sep22a\sketch_sep22a.ino:41:10:
error: 'MPU6050_CLOCK_EXTERNAL_19MHZ' was not
declared in this scope
case MPU6050_CLOCK_EXTERNAL_19MHZ:
Serial.println("PLL with external 19.2MHz reference"); break;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Users\uditm_27jdw1v\AppData\Local\Temp\.arduinoIDE-
unsaved2024822-1096-

28/34
b9e7m8.w059q\sketch_sep22a\sketch_sep22a.ino:41:10:
note: suggested alternative: 'MPU6050_CLOCK_INTERNAL'
case MPU6050_CLOCK_EXTERNAL_19MHZ:
Serial.println("PLL with external 19.2MHz reference"); break;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~
MPU6050_CLOCK_INTERNAL
C:\Users\uditm_27jdw1v\AppData\Local\Temp\.arduinoIDE-
unsaved2024822-1096-
b9e7m8.w059q\sketch_sep22a\sketch_sep22a.ino:42:10:
error: 'MPU6050_CLOCK_EXTERNAL_32KHZ' was not
declared in this scope
case MPU6050_CLOCK_EXTERNAL_32KHZ:
Serial.println("PLL with external 32.768kHz reference");
break;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Users\uditm_27jdw1v\AppData\Local\Temp\.arduinoIDE-
unsaved2024822-1096-
b9e7m8.w059q\sketch_sep22a\sketch_sep22a.ino:42:10:
note: suggested alternative: 'MPU6050_CLOCK_INTERNAL'
case MPU6050_CLOCK_EXTERNAL_32KHZ:
Serial.println("PLL with external 32.768kHz reference");
break;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~
MPU6050_CLOCK_INTERNAL
C:\Users\uditm_27jdw1v\AppData\Local\Temp\.arduinoIDE-
unsaved2024822-1096-
b9e7m8.w059q\sketch_sep22a\sketch_sep22a.ino:46:10:
error: 'MPU6050_CLOCK_INTERNAL_8MHZ' was not
declared in this scope
case MPU6050_CLOCK_INTERNAL_8MHZ:
Serial.println("Internal 8MHz oscillator"); break;
^~~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Users\uditm_27jdw1v\AppData\Local\Temp\.arduinoIDE-
unsaved2024822-1096-
b9e7m8.w059q\sketch_sep22a\sketch_sep22a.ino:46:10:
note: suggested alternative: 'MPU6050_CLOCK_INTERNAL'
case MPU6050_CLOCK_INTERNAL_8MHZ:
Serial.println("Internal 8MHz oscillator"); break;
^~~~~~~~~~~~~~~~~~~~~~~~~~~
MPU6050_CLOCK_INTERNAL
Multiple libraries were found for "MPU6050.h"
Used:

29/34
C:\Users\uditm_27jdw1v\Documents\Arduino\libraries\MP
U6050-1.3.1
Not used:
C:\Users\uditm_27jdw1v\Documents\Arduino\libraries\Ard
uino-MPU6050-master
exit status 1

Compilation error: 'MPU6050_CLOCK_EXTERNAL_19MHZ'


was not declared in this scope

The error indicates that the clock source constants MPU6050_CLOCK_EXTERNAL_19MHZ ,


MPU6050_CLOCK_EXTERNAL_32KHZ , and MPU6050_CLOCK_INTERNAL_8MHZ are not declared in the
library you are using. The alternative suggestions like MPU6050_CLOCK_INTERNAL indicate that
the library you have installed doesn't support these constants.

Steps to Fix:
1. Use Supported Constants: Remove the unsupported constants and use only the
available ones.

2. Simplify Clock Source Checking: The MPU6050 library typically supports the following
clock sources:

MPU6050_CLOCK_KEEP_RESET

MPU6050_CLOCK_PLL_XGYRO

MPU6050_CLOCK_PLL_YGYRO

MPU6050_CLOCK_PLL_ZGYRO

MPU6050_CLOCK_INTERNAL

Here's the updated and corrected code:

cpp

#include <Wire.h>
#include <MPU6050.h> // Make sure to install this library by Jeff Rowberg

MPU6050 mpu;

void setup() {
Serial.begin(115200);
Wire.begin(); // Start I2C communication

30/34
Serial.println("Initializing MPU6050...");

// Initialize the MPU6050


if (!mpu.testConnection()) {
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
while (1); // Stay in loop if the sensor is not found
}

// Initialize the MPU6050 and set it to the default settings


mpu.initialize();

// Optional: set accelerometer offsets


// mpu.setXAccelOffset();
// mpu.setYAccelOffset();
// mpu.setZAccelOffset();

// Check settings and configuration


checkSettings();
}

void checkSettings() {
Serial.println();

// Check if sleep mode is enabled


Serial.print(" * Sleep Mode: ");
Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");

// Check the clock source


Serial.print(" * Clock Source: ");
switch (mpu.getClockSource()) {
case MPU6050_CLOCK_KEEP_RESET: Serial.println("Stops the clock and keeps the
timing generator in reset"); break;
case MPU6050_CLOCK_PLL_ZGYRO: Serial.println("PLL with Z axis gyroscope
reference"); break;
case MPU6050_CLOCK_PLL_YGYRO: Serial.println("PLL with Y axis gyroscope
reference"); break;
case MPU6050_CLOCK_PLL_XGYRO: Serial.println("PLL with X axis gyroscope
reference"); break;
case MPU6050_CLOCK_INTERNAL: Serial.println("Internal oscillator"); break;
default: Serial.println("Unknown clock source");
break;
}

31/34
// Check accelerometer range
Serial.print(" * Accelerometer: ");
switch (mpu.getFullScaleAccelRange()) {
case MPU6050_ACCEL_FS_2: Serial.println("+/- 2 g"); break;
case MPU6050_ACCEL_FS_4: Serial.println("+/- 4 g"); break;
case MPU6050_ACCEL_FS_8: Serial.println("+/- 8 g"); break;
case MPU6050_ACCEL_FS_16: Serial.println("+/- 16 g"); break;
}

// Check accelerometer offsets


Serial.print(" * Accelerometer offsets: ");
Serial.print(mpu.getXAccelOffset());
Serial.print(" / ");
Serial.print(mpu.getYAccelOffset());
Serial.print(" / ");
Serial.println(mpu.getZAccelOffset());

Serial.println();
}

void loop() {
// Variables for raw accelerometer data
int16_t ax, ay, az;

// Get the raw acceleration values


mpu.getAcceleration(&ax, &ay, &az);

// Convert raw accelerometer values to G-forces


float accelX = ax / 16384.0;
float accelY = ay / 16384.0;
float accelZ = az / 16384.0;

// Print raw and normalized acceleration values


Serial.print("Xraw = "); Serial.print(ax); Serial.print(" Yraw = ");
Serial.print(ay); Serial.print(" Zraw = "); Serial.println(az);
Serial.print("Xnorm = "); Serial.print(accelX); Serial.print(" Ynorm = ");
Serial.print(accelY); Serial.print(" Znorm = "); Serial.println(accelZ);

delay(100);
}

32/34
Key Changes:
Removed unsupported clock sources ( MPU6050_CLOCK_EXTERNAL_19MHZ ,
MPU6050_CLOCK_EXTERNAL_32KHZ , MPU6050_CLOCK_INTERNAL_8MHZ ).

Kept only the supported clock sources ( MPU6050_CLOCK_KEEP_RESET ,


MPU6050_CLOCK_PLL_XGYRO , etc.).

This code should now compile correctly with the library you're using. Let me know if you have
further issues!

also tell the connections

To connect the MPU6050 sensor to the Arduino, you will use the I2C protocol. Here are the
steps for wiring:

Connections:
1. MPU6050 Pin Layout:

VCC: Power supply pin.

GND: Ground.

SCL: I2C clock pin.

SDA: I2C data pin.

2. Arduino Pin Layout:

VCC: Connect this to the 5V pin on the Arduino (or 3.3V if your MPU6050 operates at
3.3V).

GND: Connect this to the GND pin of the Arduino.

SCL: Connect this to A5 (Analog pin 5) on Arduino Uno (SCL).

SDA: Connect this to A4 (Analog pin 4) on Arduino Uno (SDA).

Detailed Wiring:
MPU6050 Pin Arduino Pin

VCC 5V or 3.3V

GND GND

SCL A5 (SCL)

SDA A4 (SDA)

33/34
Diagram:
MPU6050 VCC → Arduino 5V/3.3V

MPU6050 GND → Arduino GND

MPU6050 SCL → Arduino A5 (SCL)

MPU6050 SDA → Arduino A4 (SDA)

After wiring, ensure the correct library is installed and upload the code to test the setup.

34/34

You might also like