Fitness band : IOT project using NodeMCU and Pulse sensor

Our generation has adapted sedentary life style very much and its becoming it’s too hard  now to get back into healthy lifestyle. So it’s of dire importance now to keep our activity in check than ever. To adapt a healthy lifestyle its important to be watchful about the amount of calories we consume and burn per day. It is advised to burn at least 500 to 600 calories in a day apart from the calories burnt by our body to regulate body functions. Fitness bands have took the market by storm by helping us to be mindful about the number of calories burnt per day. This conceptual fitness band is an IOT project that uses heart beat to calculate the calories burned and help user to monitor his/her activity level using smartphone application.

Check out other IOT projects in our website.

How Fitness band works:

This fitness band system uses heart beat sensor to measure the activity of heart in Beats per minute ( BPM ). Heart beat is a key parameter to understand physical activity. When perform any physical activity our heart rate goes high and when we relax heart beat will be back to normal. This makes heart beat a great parameter to understand the number of calories burned. Along with heart beat rate we require other parameters such as gender, age and weight of user. These parameters will help us to deduce the calories burnt for a given time.

When the system ON, NodeMCU will await start instruction from Blynk app which is connected to Local network with NodeMCU via WiFI. Then user needs to enter personal profile details such as gender, age and weight. Once done, user can turn ON the fitness band by using “Device ON” button in Blynk app. Now NodeMCU will start reading heart beat analog data and keeps track of the time as well.

This fitness band uses PLSNSR1 pulse sensor to measure the rate of heart beat. The input heart beat is translated to beats per minute and calories burned in NodeMCU. The resultant output data is transmitted back to Blynk app to display in the user interface.

In the user interface the BPM ( Beats per minute ) will be updated every second and amount of calories burned will be updated every 10 seconds to help the user to monitor the level of intensity of his/her fitness regime.

Once the session is complete, user need to turn off the system using Blynk app interface. Now an email with amount of calories burned and duration of session will be sent to users email to help keep a log of their calories burned.

IOT Fitness band features:

  1. Calculates average heartbeat rate in BPM(bits per minute).
  2. Determines and updates total calories burnt in the cloud for every 10 seconds.
  3. User can control when to start and stop the fitness bands activity through IOT application or Smartphone.
  4. Sends an alert email to the user about the average heart beat (BPM) and calories burnt.
  5. LED indicator that blinks in relation to the speed of user heart beat.

Hardware required:

  1. NodeMCU
  2. Pulse sensor(PLSNSR1)
  3. LED
  4. Resistor (220 Ohm)
  5. Jumper wires

Circuit diagram:

User interface ( Blynk App ) :

The above snapshot shows the user interface of the Blynk app UI used with this Fitness band project. Blynk is an application that provides cloud functionality to embedded projects. It allows users to build their own User interface based on the needs of their project.

The application takes the below three inputs

  1. Sex
  2. Age
  3. Weight

After valid inputs are given, the system can be turned ON. The ON or OFF button serves as an ON/OFF switch for the band. When user activates this button the above three parameters will be sent to NodeMCU via cloud which enables calories calculation. When invalid inputs are given in Age and weight fields i.e is zero then the fitness tracker system will remain in OFF state.

The NodeMCU after processing the sensor data will update the app interface fields such – BPM (updated every second) and Calories burned (once in 10 seconds). This will help user in live monitoring of their calories burned and assess the intensity of their fitness regime.

The user can turn OFF the device once he/ she completes the fitness session. Turning the device OFF will trigger an email with their activity report to their mailbox.

Formulas:

The formulas that is required to convert heart beat rate into calories burnt are: –

For male

Calories burn = ((-55.0969 + (0.6309*HR) + (0.1988*W) + (0.2017*A))/4.184 )*60*T

For Female

Calories burn = ((-20.4022+(0.4472*HR) – (0.1263*W) + (0.074*A))/4.184)*60*T

Where
HR – Heartbeat Rate (in BPM)
W   – Weight (in Kilograms)
A    – Age(in years)
T    – Duration time of exercise(in hours)

Prototype:

Connecting fitness band to IOT cloud:

Add your Smartphone SSID and Password in the code and upload to NodeMCU. Use the Authorization token that is generated from your Blynk app in the code. Wait for NodeMCU to connect with your smartphone. When the devices are paired, the NodeMCU will wait for Device ON command from user.

Calculation and Updating of BPM, Calories burnt will be performed until NodeMCU receives Device OFF command. If you intend to change the smartphone you want to use to pair with fitness band, change must be made in the code replacing SSID and password of the target device.

Algorithm:

  1. Wait for the connection with Blynk app.
  2. Read the input from the Blynk user interface – age, weight and gender from user.
  3. Wait for Device ON button to be activated and if it is activated go to to step 6.
  4. If ON button is activated, save the current system time in a variable.
  5. Read the sensor analog input data (heart beat ) and convert them in to Beats per minute ( BPM ). Upload the BPM to Blynk UI.
  6. Calculate the calories burnt every 10 seconds. Upload the calories burnt to Blynk UI.
  7. Repeat the process until ON button is deactivated(OFF).
  8. Display the final calories burnt and BPM in Blynk UI.

Code :

Include the necessary header files to your Arduino IDE directory : ESP8266WiFi.h, BlynkSimpleEsp8266.h . This Fitness band project was built and tested by Nihar Gupta. You can find the Fitness band – Github repository here.

// Include header files 
#define BLYNK_PRINT Serial
#include<ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

// Auth token generated by Blynk
char auth[] = "gTJf3EcGRGacgcW24I-OWcmj70OlwjZ2";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Your SSID";          //Replace with your SSID
char pass[] = "Your Password";      //Replace with your password

// Extenal LED 
int led_pin = D6;

// Variables required for calibrations
const int postingInterval = 10 * 1000; 
int rate[10];                    
unsigned long sampleCounter = 0; 
unsigned long lastBeatTime = 0;  
unsigned long lastTime = 0, N;
int BPM = 0;
int IBI = 0;
int P = 512;
int T = 512;
int thresh = 512;  
int amp = 100;                   
int Signal;
boolean Pulse = false;
boolean firstBeat = true;          
boolean secondBeat = true;
boolean QS = false;    

//Variables required to calculations 
boolean time_noted=false;
unsigned long starting_time=0;        //starting time of the device in millis second
boolean mail_sent=false;    
unsigned long average_bpm=0;          // stores average bpm
unsigned long bpm_counted=0;          // stores number of times bpm is calculated
boolean male=true;
int weight=0;
int age=0;
int start_button=0;
int does_mail_send =0;
int heart_rate=0;
float calorie_burn;
float time_duration=0;
float total_calorie_burn=0;

// Setup block
void setup() {
  // put your setup code here, to run once:
   Serial.begin(115200);

   //Pinmodes 
   pinMode(A0,INPUT);
   pinMode(led_pin,OUTPUT);

   //Blynk setup
   Blynk.begin(auth, ssid, pass); 

}

void loop() {
  // put your main code here, to run repeatedly:
  Blynk.run();    // Blynk will run continuously

  // here if block will execute when start button in the blynk is ON
  if(start_button==1 && time_noted==true){
    
    if(check_if_data_is_correct()==false) continue;   // checks if the user has entered age, gender and weight before turning on the device
    
    //Serial.println("BPM is Calculating");
    calculate_bpm();        
    if(millis()-starting_time>=10000){
        calculate_calories_10sec();  // calculate calories burnt for every 10 minutes
    }
  } 
  // else if block will get executed when the starts button gets off
  else if(mail_sent==true){
    calculate_calories_10sec();
    send_email();
    mail_sent=false;
    reset_bpm();    // reset the variables when device gets OFF
  }

}

// checks if the user has entered age, gender and weight before turning on the device
bool check_if_data_is_correct(){
  if(weight<=0 || age<=0){
    Blynk.virtualWrite(V9, LOW);
    start_button=0;
    time_noted=false;
    reset_bpm();
   return false;
  }
  return true;
}

// This function calculates calories burnt in every 10 seconds and update it into blynk
void calculate_calories_10sec(){
  starting_time=millis();
  heart_rate=average_bpm/bpm_counted;
  if(male==true){
    Serial.println("Male");
    calorie_burn=(float)( ((-55.0969+(0.6309*heart_rate)+(0.1988*weight)+(0.2017*age))/4.184)*60*0.00277778);
  }
  else{
    Serial.println("Female");
    calorie_burn=(float)( ((-20.4022+(0.4472*heart_rate)-(0.1263*weight)+(0.074*age))/4.184)*60*0.00277778);
  }
  total_calorie_burn+=calorie_burn;
  Serial.println(weight);
  Serial.println(age);
  Serial.println(average_bpm);
  Serial.println(bpm_counted);
  Serial.println(calorie_burn);
  Serial.println(time_duration);
  Serial.println(starting_time);
  Blynk.virtualWrite(V7,total_calorie_burn);
}

// this function is used to send email to the user about his status when the device gets off
void send_email()
{ 
  if(does_mail_send == 0){
    String msg="Hi Nihar Gupta. Your average heart beat is:"+(String)heart_rate+". Your "+(String)calorie_burn+"calories are burned during the time of"+(String)time_duration+"Hrs";
    Blynk.email("youremail@yourdomain.com", "Heart Beat Notification", msg); //Replace with your email
    does_mail_send = 1;
  }
}

// Reset the variables when the device is get off
void reset_bpm(){
  average_bpm=0;
  bpm_counted=0;
  total_calorie_burn=0;
  Blynk.virtualWrite(V7,0);
  Blynk.virtualWrite(V1,0);
}

// This function will take care to initilize BPM
void calculate_bpm(){
  if (QS == true) {
   Serial.println("BPM: "+ String(BPM));
   Blynk.virtualWrite(V1,BPM);
   average_bpm+=BPM;
   bpm_counted++;
   QS = false;
   } else if (millis() >= (lastTime + 2)) {
     readPulse();
     lastTime = millis();
   }
        
}

// This function will read the analog data and calibrate the data into BPM
void readPulse() {
  Signal = analogRead(A0);       
  analogWrite(led_pin,Signal);    
  sampleCounter += 2;                           
  int N = sampleCounter - lastBeatTime;   
  detectSetHighLow();
  if (N > 250) {  
    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI / 5) * 3) )
      pulseDetected();
  }
  if (Signal < thresh && Pulse == true) {  
    Pulse = false;
    amp = P - T;
    thresh = amp / 2 + T;  
    P = thresh;
    T = thresh;
  }
  if (N > 2500) {
    thresh = 512;
    P = 512;
    T = 512;
    lastBeatTime = sampleCounter;
    firstBeat = true;            
    secondBeat = true;           
  }
}
void detectSetHighLow() {
  if (Signal < thresh && N > (IBI / 5) * 3) {
    if (Signal < T) {                       
      T = Signal;                         
    }
  }
  if (Signal > thresh && Signal > P) {    
    P = Signal;                           
  }                                       
}

// This calibration is when a pulse is detected
void pulseDetected() {
  Pulse = true;                           
  IBI = sampleCounter - lastBeatTime;     
  lastBeatTime = sampleCounter;           

  if (firstBeat) {                       
    firstBeat = false;                 
    return;                            
  }
  if (secondBeat) {                    
    secondBeat = false;                
    for (int i = 0; i <= 9; i++) {   
      rate[i] = IBI;
    }
  }

  word runningTotal = 0;                   

  for (int i = 0; i <= 8; i++) {          
    rate[i] = rate[i + 1];            
    runningTotal += rate[i];          
  }

  rate[9] = IBI;                      
  runningTotal += rate[9];            
  runningTotal /= 10;                 
  BPM = 60000 / runningTotal;         
  QS = true;
}                           

// To know Start button in blynk is ON/OFF
BLYNK_WRITE(V9) 
{
  start_button = param.asInt();
  if(start_button==1 && time_noted==false){
    starting_time=millis();
    mail_sent=false;
    does_mail_send=0;
    time_noted = true;
  }
  else if(start_button==0 && time_noted==true){
    mail_sent = true;
    time_noted=false;
  }
}

// Update gender when it is changed
BLYNK_WRITE(V2){
  switch(param.asInt()){
    case 1:{ male=true;
             break;
           }
    case 2:{male=false;
            break;      
           }
  }
}

// update weight when it is changed in Blynk
BLYNK_WRITE(V3){
  weight = param.asInt();
}

// update age when it is changed in Blynk
BLYNK_WRITE(V4){
  age=param.asInt();
}

Hope this project will be useful to you. Post your thoughts, comments and queries in the comments section below. Check out other Arduino projects in our website.


Leave a Comment

Your email address will not be published. Required fields are marked *