IoT based Fall Detection using NodeMCU ESP8266 and Accelerometer MPU6050

IoT based Fall Detection using NodeMCU

The fall detection system is very useful for elderly people. It can notify the concerned person or family member whenever it detects any fall and can reduce the risk of delayed medical attention. This has led to the development of many different types of automated fall detection systems. Nowadays, you can find fall detectors in smartwatches, fitness trackers, and other types of wearables.  

 

So in this tutorial, we are going to build a fall detection device using NodeMCU and MPU6050 sensor module. MPU6050 sensor module features a gyroscope and an accelerometer. The gyroscope is used to determine the orientation and the accelerometer provides information about the angular parameter such as the three-axis data. To detect the fall, we will compare the acceleration magnitude with the threshold value. If the fall is detected, the device will send an SMS to the concerned person. NodeMCU is used here as a microcontroller and Wi-Fi module to connect with IFTTT to send SMS.

 

Components Required 

  • NodeMCU ESP8266
  • MPU6050 Accelerometer
  • Buzzer
  • Connecting Wires

 

Circuit Diagram

Circuit Diagram for IoT based Fall Detector using NodeMCU is given below.

IoT Based Fall Detector Circuit Diagram

The MPU6050 works on the I2C protocol, so we only need two wires to interface NodeMCU and MPU6050. The SCL and SDA pins of MPU6050 are connected to D1 and D2 pins of NodeMCU, while VCC and GND pins of MPU6050 are connected to 3.3V and GND of NodeMCU. We previously used MPU6050 to build gesture controlled robot.

IoT Based Fall Detector

 

MPU6050 Sensor Module

MPU6050 Module

The MPU6050 sensor module is complete 6-axis (3-axis Accelerometer and 3-axis Gyroscope) Micro-Electro-Mechanical Systems (MEMS) that is used to measure acceleration, velocity, orientation, displacement, and many other motion-related parameters. Apart from this, it also has an additional on-chip Temperature sensor.

 

The MPU6050 module is small in size and has low power consumption, high repetition, high shock tolerance, and low user price points. The MPU6050 comes with an I2C bus and Auxiliary I2C bus interface and can easily interfere with other sensors such as magnetometers and microcontrollers.

 

IFTTT Setup for Fall Detector

IFTTT (If This Then That) is a web-based service by which we can create chains of conditional statements, called applets. Using these applets, we can send Emails, Twitter, Facebook notifications. Here in this project, we are using IFTTT to send message notifications when the device detects a fall.

 

To use the IFTTT, sign in to your IFTTT account if you already have one or create an account. 

 

Now search for ‘Webhooks’ and click on the Webhooks in Services section.

IFTTT Setup

 

Now, in the Webhooks window, click on ‘Documentation’ in the upper right corner to get the private key.

Copy this key. It will be used in the program.

IFTTT Private Key

 

After getting the private key, now create an applet using Webhooks and Email services. To create an applet, click on your profile and then click on ‘Create.’

IFTTT Applet

 

 Now, in the next window, click on the ‘This’ icon.

IFTTT

 

Now search for Webhooks in the search section and click on ‘Webhooks.

IFTTT Webhooks Service

 

Now choose ‘Receive a Web Request’ trigger and in the next window, enter the event name as fall_detect and then click on create a trigger.

Now to complete the applet, click on ‘That’ to create a reaction for the fall_detect event.

FalI Detector using IFTTT

Here we are reacting to fall_detect event by sending a message. For that search for ‘Android device’ in the search section and choose ‘Android SMS.’

IFTTT Android Action

 

Now, it will ask you to enter the phone number and message body. Enter the Mobile Number and the message body and then click on ‘create action’ to complete the process.

IFTTT Action

 

Now we will create another applet to play a specific song when the fall is detected

For this, follow the same procedure as above but instead of ‘Android SMS’, click on ‘Android Device’ and then click on ‘Play a Specific Song’

IFTTT Commands

In the next step, enter the song name and then click on Create.

 

Code Explanation

The complete code for Fall Detector using NodeMCU is given at the end of the page. Here we are explaining some important parts.

 

As usual, start the code by including all the required libraries. The Wire.h library allows you to communicate with I2C / TWI devices while ESP8266.h library provides NodeMCU specific Wi-Fi routines that we are calling to connect to the network.

#include <Wire.h>
#include <ESP8266WiFi.h>

 

In the next lines, enter the Wi-Fi Name and password and IFTTT account credentials. 

const char *ssid = 
"Galaxy-M20"; // Enter your Wi-Fi Name
const char *pass = "ac312124"; // Enter your Wi-Fi Password
void send_event(const char *event);
const char *host = "maker.ifttt.com";
const char *privateKey = "hUAAAz0AVvc6-NW1UmqWXXv6VQWmpiGFxx3sV5rnaM9";

 

Inside the void setup(), initialize the baud rate, the wire library, and the data transmission through the power management register.

Serial.begin(115200);
pinMode(buzzer, OUTPUT);
Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B);
Wire.write(0);

 

Now inside the void loop(), read the MPU6050 sensor data. 2050, 77, 1947 are values for calibration of an accelerometer. Same for gyroscope, add the calibration values in the original values.

ax = (AcX-2050)/16384.00;
ay = (AcY-77)/16384.00;
az = (AcZ-1947)/16384.00;
gx = (GyX+270)/131.07;
gy = (GyY-351)/131.07;
gz = (GyZ+136)/131.07;

 

After getting the accelerometer and gyroscope values, calculate the amplitude vector of the accelerometer values.

float Raw_Amp = pow(pow(ax,2)+pow(ay,2)+pow(az,2),0.5);
 int Amp = Raw_Amp * 10; // Mulitiplied by 10 bcz values are between 0 to 1
 Serial.println(Amp);

 

This program first checks if the accelerometer values exceed the lower threshold, if yes, then it waits for 0.5 seconds and checks for the higher threshold. If the accelerometer values exceed the higher threshold, then it checks for the gyroscope values to calculate the change in orientation. If there is a sudden change in orientation, then it waits for 10 seconds and checks if the orientation remains the same. If yes, then it activates the Fall Detector alarm.

if (Amp<=2 && trigger2==false)
{                          //if amplitude breaks lower threshold (0.4g)
   trigger1=true;
   Serial.println("TRIGGER 1 ACTIVATED");
   }
 if (trigger1==true)
{
   trigger1count++;
   if (Amp>=12)
{                         //if AM breaks upper threshold (3g)
     trigger2=true;
     Serial.println("TRIGGER 2 ACTIVATED");
     trigger1=false; trigger1count=0;
     }
 }
 if (trigger2==true)
{
   trigger2count++;
   angleChange = pow(pow(gx,2)+pow(gy,2)+pow(gz,2),0.5); Serial.println(angleChange);
   if (angleChange>=30 && angleChange<=400)
{                        //if orientation changes by between 80-100 degrees
     trigger3=true; trigger2=false; trigger2count=0;
     Serial.println(angleChange);
     Serial.println("TRIGGER 3 ACTIVATED");
       }
   }
 if (trigger3==true)
{
    trigger3count++;
    if (trigger3count>=10)
{ 
       angleChange = pow(pow(gx,2)+pow(gy,2)+pow(gz,2),0.5);
                       //delay(10);
       Serial.println(angleChange); 
       if ((angleChange>=0) && (angleChange<=10))
{                     //if orientation changes remains between 0-10 degrees
           fall=true; trigger3=false; trigger3count=0;
           Serial.println(angleChange);
             }
       else
{                    //user regained normal orientation
          trigger3=false; trigger3count=0;
          Serial.println("TRIGGER 3 DEACTIVATED");
       }
     }
  }
 if (fall==true)
{                  //in event of a fall detection
   Serial.println("FALL DETECTED");
   send_event("fall_detect"); 
   fall=false;
   }

 

Inside the mpu_read loop(), read all the six registers for the X, Y, and Z axes of Accelerometer and Gyroscope.

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)
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)

 

Testing the IoT Fall Detector

Once your code and hardware are ready, upload the code. To test the project, take the MPU6050 in your hands and pretend to be walking slowly and then suddenly trip on a ledge as shown in the video given below. If the magnitude exceeds the threshold value, the device will activate the fall detection alarm and send a message to the registered number.

IoT Fall Detection Working

The complete code and working video are given at the end of the project.

Code

#include <Wire.h>
#include <ESP8266WiFi.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;
boolean fall = false; //stores if a fall has occurred
boolean trigger1=false; //stores if first trigger (lower threshold) has occurred
boolean trigger2=false; //stores if second trigger (upper threshold) has occurred
boolean trigger3=false; //stores if third trigger (orientation change) has occurred
byte trigger1count=0; //stores the counts past since trigger 1 was set true
byte trigger2count=0; //stores the counts past since trigger 2 was set true
byte trigger3count=0; //stores the counts past since trigger 3 was set true
int angleChange=0;
// WiFi network info.
const char *ssid =  "Galaxy-M20";     // Enter your WiFi Name
const char *pass =  "ac312124"; // Enter your WiFi Password
void send_event(const char *event);
const char *host = "maker.ifttt.com";
const char *privateKey = "hUAAAz0AVvc6-NW1UmqWXXv6VQWmpiGFxx3sV5rnaM9";
void setup(){
 Serial.begin(115200);
 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.println("Wrote to IMU");
  Serial.println("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");              // print ... till not connected
  }
  Serial.println("");
  Serial.println("WiFi connected");
 }
void loop(){
 mpu_read();
 ax = (AcX-2050)/16384.00;
 ay = (AcY-77)/16384.00;
 az = (AcZ-1947)/16384.00;
 gx = (GyX+270)/131.07;
 gy = (GyY-351)/131.07;
 gz = (GyZ+136)/131.07;
 // calculating Amplitute vactor for 3 axis
 float Raw_Amp = pow(pow(ax,2)+pow(ay,2)+pow(az,2),0.5);
 int Amp = Raw_Amp * 10;  // Mulitiplied by 10 bcz values are between 0 to 1
 Serial.println(Amp);
 if (Amp<=2 && trigger2==false){ //if AM breaks lower threshold (0.4g)
   trigger1=true;
   Serial.println("TRIGGER 1 ACTIVATED");
   }
 if (trigger1==true){
   trigger1count++;
   if (Amp>=12){ //if AM breaks upper threshold (3g)
     trigger2=true;
     Serial.println("TRIGGER 2 ACTIVATED");
     trigger1=false; trigger1count=0;
     }
 }
 if (trigger2==true){
   trigger2count++;
   angleChange = pow(pow(gx,2)+pow(gy,2)+pow(gz,2),0.5); Serial.println(angleChange);
   if (angleChange>=30 && angleChange<=400){ //if orientation changes by between 80-100 degrees
     trigger3=true; trigger2=false; trigger2count=0;
     Serial.println(angleChange);
     Serial.println("TRIGGER 3 ACTIVATED");
       }
   }
 if (trigger3==true){
    trigger3count++;
    if (trigger3count>=10){ 
       angleChange = pow(pow(gx,2)+pow(gy,2)+pow(gz,2),0.5);
       //delay(10);
       Serial.println(angleChange); 
       if ((angleChange>=0) && (angleChange<=10)){ //if orientation changes remains between 0-10 degrees
           fall=true; trigger3=false; trigger3count=0;
           Serial.println(angleChange);
             }
       else{ //user regained normal orientation
          trigger3=false; trigger3count=0;
          Serial.println("TRIGGER 3 DEACTIVATED");
       }
     }
  }
 if (fall==true){ //in event of a fall detection
   Serial.println("FALL DETECTED");
   send_event("fall_detect"); 
   fall=false;
   }
 if (trigger2count>=6){ //allow 0.5s for orientation change
   trigger2=false; trigger2count=0;
   Serial.println("TRIGGER 2 DECACTIVATED");
   }
 if (trigger1count>=6){ //allow 0.5s for AM to break upper threshold
   trigger1=false; trigger1count=0;
   Serial.println("TRIGGER 1 DECACTIVATED");
   }
  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)
 }
void send_event(const char *event)
{
  Serial.print("Connecting to "); 
  Serial.println(host);
    // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("Connection failed");
    return;
  }
    // We now create a URI for the request
  String url = "/trigger/";
  url += event;
  url += "/with/key/";
  url += privateKey;
  Serial.print("Requesting URL: ");
  Serial.println(url);
  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" + 
               "Connection: close\r\n\r\n");
  while(client.connected())
  {
    if(client.available())
    {
      String line = client.readStringUntil('\r');
      Serial.print(line);
    } else {
      // No data yet, wait a bit
      delay(50);
    };
  }
  Serial.println();
  Serial.println("closing connection");
  client.stop();
}

Video

35 Comments

I'm just commenting to let you be aware of what a outstanding encounter my girl gained going through your site. She noticed such a lot of issues, including how it is like to possess a marvelous helping mood to make many others with ease master certain specialized issues. You really surpassed our expected results. Many thanks for distributing the warm and helpful, dependable, educational and unique tips on that topic to Lizeth.

Thank you so much for providing individuals with an exceptionally breathtaking possiblity to read from this blog. It is usually very beneficial and also jam-packed with a great time for me personally and my office fellow workers to visit the blog particularly 3 times in one week to read through the latest issues you have. Not to mention, we're actually contented concerning the sensational suggestions served by you. Certain 1 facts in this article are ultimately the most efficient we have had.

I truly wanted to construct a quick note to appreciate you for all the awesome steps you are posting at this website. My time-consuming internet investigation has now been recognized with reasonable suggestions to share with my family. I would repeat that many of us visitors actually are definitely blessed to live in a fine network with so many lovely individuals with great opinions. I feel pretty happy to have used your entire web site and look forward to many more awesome moments reading here. Thanks a lot again for all the details.

I wish to voice my gratitude for your kindness giving support to those who really want guidance on the area of interest. Your very own commitment to passing the solution along has been amazingly interesting and have really permitted professionals like me to reach their pursuits. Your new insightful information denotes a lot a person like me and somewhat more to my colleagues. Many thanks; from all of us.

I am glad for writing to let you be aware of of the brilliant discovery our child undergone viewing your web page. She discovered plenty of things, which include what it's like to possess an awesome coaching nature to let a number of people very easily fully understand specific extremely tough matters. You actually did more than my expected results. I appreciate you for distributing the precious, dependable, explanatory and even easy thoughts on the topic to Mary.

I simply had to thank you very much again. I am not sure the things that I could possibly have worked on without these aspects revealed by you directly on my concern. It was the frightful concern for me personally, but taking a look at your professional approach you dealt with that took me to leap over gladness. I am just happier for the advice and thus have high hopes you know what a great job you happen to be undertaking training men and women with the aid of your web site. I am certain you haven't come across any of us.

I actually wanted to send a remark in order to appreciate you for these amazing points you are posting at this website. My extensive internet lookup has at the end been rewarded with reputable tips to go over with my pals. I would express that we visitors are really blessed to exist in a fine website with so many awesome individuals with interesting things. I feel really blessed to have come across the webpage and look forward to many more excellent minutes reading here. Thanks again for everything.

I just wanted to develop a simple comment so as to appreciate you for the superb points you are giving on this site. My time-consuming internet look up has now been honored with extremely good content to share with my co-workers. I 'd say that most of us site visitors actually are very much lucky to live in a wonderful network with so many special people with great plans. I feel somewhat fortunate to have come across your entire web pages and look forward to some more cool times reading here. Thank you again for all the details.

A lot of thanks for all of the labor on this site. Kate enjoys working on research and it's obvious why. Almost all notice all regarding the lively means you provide both interesting and useful ideas on your website and therefore cause participation from other ones about this subject while our own child is in fact starting to learn a lot of things. Have fun with the rest of the new year. You are always doing a tremendous job.

I and my buddies were studying the excellent tips on your web page and so then developed an awful suspicion I never thanked the web site owner for those strategies. Those boys happened to be totally warmed to read them and have now clearly been tapping into them. Appreciation for getting really considerate and also for settling on varieties of ideal subject matter millions of individuals are really desperate to learn about. My personal sincere regret for not expressing appreciation to earlier.

I wanted to post a remark in order to express gratitude to you for all of the precious concepts you are showing here. My long internet research has at the end been recognized with wonderful know-how to exchange with my companions. I would assert that many of us readers are very blessed to exist in a remarkable community with many marvellous individuals with great tips. I feel very much grateful to have come across the webpage and look forward to tons of more amazing moments reading here. Thanks once more for all the details.

I just tried to replicate this code but im getting trigger 1 activates only. Its not moving to the next condition. can you dm as soon as you read it

My spouse and i ended up being really joyful Chris managed to complete his web research via the ideas he made through your web page. It is now and again perplexing just to be giving out information and facts which usually a number of people have been selling. And we all do understand we have the blog owner to thank for that. The entire illustrations you made, the easy web site menu, the friendships you will help to engender - it's got mostly wonderful, and it's assisting our son in addition to our family do think that content is satisfying, and that is tremendously essential. Many thanks for the whole lot!

I together with my guys were found to be following the best information and facts found on your site and then quickly came up with a terrible suspicion I never expressed respect to the site owner for those techniques. All the young boys were certainly warmed to read through them and have in effect simply been making the most of them. I appreciate you for really being well accommodating and for making a decision on variety of extraordinary subject areas millions of individuals are really eager to know about. My very own honest regret for not expressing appreciation to earlier.

I truly wanted to compose a brief remark in order to say thanks to you for the amazing secrets you are placing here. My particularly long internet search has finally been rewarded with high-quality tips to share with my close friends. I would express that many of us readers are definitely blessed to live in a wonderful place with so many special individuals with interesting suggestions. I feel very much grateful to have come across your entire website page and look forward to many more enjoyable moments reading here. Thanks a lot once again for all the details.

I not to mention my pals have already been reading through the great pointers from the website then the sudden developed a terrible suspicion I never thanked the site owner for those secrets. All of the guys are actually absolutely glad to see all of them and have now clearly been loving these things. We appreciate you indeed being indeed considerate as well as for having these kinds of notable subject matter most people are really eager to know about. My personal sincere apologies for not expressing gratitude to you sooner.

I just wanted to construct a simple word to be able to express gratitude to you for all the superb steps you are showing at this website. My considerable internet investigation has finally been rewarded with reasonable insight to talk about with my family members. I would repeat that many of us readers are unequivocally fortunate to be in a very good network with many brilliant professionals with beneficial tactics. I feel pretty lucky to have encountered the site and look forward to really more amazing moments reading here. Thank you once again for everything.

I want to convey my appreciation for your kind-heartedness giving support to those individuals that really want assistance with this concept. Your personal commitment to passing the message around had become really functional and have regularly allowed some individuals much like me to get to their endeavors. Your new valuable guide can mean this much a person like me and still more to my mates. Warm regards; from each one of us.

I have to show some thanks to you just for rescuing me from this incident. Just after researching through the world wide web and obtaining principles that were not pleasant, I thought my entire life was done. Living without the presence of strategies to the problems you've solved by means of your guide is a serious case, and the kind that could have badly affected my entire career if I had not encountered your web site. Your own personal expertise and kindness in playing with a lot of stuff was tremendous. I don't know what I would've done if I had not come upon such a step like this. I can also now look forward to my future. Thank you so much for this impressive and sensible guide. I won't hesitate to endorse the website to any individual who would need counselling on this topic.

Good post. I learn something new and challenging on blogs I stumbleupon everyday. It's always exciting to read through content from other authors and practice something from their websites. |

I am also writing to make you know what a fantastic experience my child found viewing your web site. She noticed so many details, most notably what it's like to possess an excellent teaching style to have a number of people effortlessly have an understanding of some hard to do matters. You truly did more than visitors' expectations. I appreciate you for giving the powerful, trusted, revealing and easy tips on your topic to Evelyn.

I enjoy you because of your whole efforts on this web site. Betty really loves managing research and it is easy to understand why. I hear all relating to the powerful ways you convey sensible information via your web site and as well inspire participation from other individuals on the subject then our own daughter has always been understanding so much. Enjoy the rest of the year. You have been doing a splendid job.

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.