Wearable Personal Health Monitoring Device with ESP32

As technology continues to evolve, we find ourselves in an era where personal health monitoring devices have become increasingly popular. These devices provide us with valuable insights into our vital signs, fitness activities, and overall health status. In this blog post, I will guide you through the process of building an advanced personal health monitoring wearable device using the ESP32 microcontroller. With this device, you'll be able to monitor your vital signs, track fitness activities, and gain meaningful health insights. So, let's dive in and start building!


Part 1: Getting Started with ESP32


Before we begin building our personal health monitoring device, let's familiarize ourselves with the ESP32 microcontroller and set up the development environment.


1.1 Understanding ESP32:

The ESP32 is a powerful microcontroller that integrates Wi-Fi and Bluetooth capabilities, making it an excellent choice for wearable devices. It features a dual-core processor, ample RAM, and a wide range of built-in peripherals.


1.2 Setting Up the Development Environment:

To start working with the ESP32, follow these steps:


Step 1: Install Arduino IDE:

Download and install the latest version of the Arduino IDE from the official Arduino website (https://www.arduino.cc/en/software).


Step 2: Install ESP32 Board Support Package:

Launch the Arduino IDE and go to "File" > "Preferences." In the "Additional Boards Manager URLs" field, paste the following URL:

https://dl.espressif.com/dl/package_esp32_index.json


Click "OK" to save the preferences. Then, navigate to "Tools" > "Board" > "Boards Manager." Search for "esp32" and install the "ESP32" board by Espressif Systems.


Step 3: Select the ESP32 Board:

Connect your ESP32 board to your computer via a USB cable. In the Arduino IDE, go to "Tools" > "Board" and select your ESP32 board variant from the list.


Step 4: Install Required Libraries:

To make our development process smoother, we need to install a few libraries. Go to "Sketch" > "Include Library" > "Manage Libraries." Search for and install the following libraries:

- Adafruit SSD1306

- Adafruit GFX Library

- PubSubClient

- DHT Sensor Library


With the development environment set up, we can now proceed to the hardware requirements for our personal health monitoring device.


Part 2: Hardware Requirements


2.1 ESP32 Dev Board:

To build our personal health monitoring device, we need an ESP32 development board. There are several options available in the market, such as the ESP32 DevKitC or NodeMCU-32S. Choose the one that suits your needs and budget.


2.2 Heart Rate Sensor:

A heart rate sensor is a vital component for monitoring heart rate variability and detecting anomalies. There are various heart rate sensor modules available, such as the MAX30102 or the Pulse Sensor Amped. Select a suitable heart rate sensor for your project.


2.3 Accelerometer and Gyroscope:

To track fitness activities and monitor movement, we'll need an accelerometer and gyroscope. The MPU-6050 module combines both sensors and is commonly used in wearable devices.


2.4 OLED Display:

An OLED display is essential for providing real-time feedback to the user. The SSD1306-based OLED displays are widely supported and easy to integrate into ESP32 projects. Consider using a 128x64 pixels OLED display module.


2.5 Temperature and Humidity Sensor:

To monitor the environmental conditions around the user, we'll incorporate a temperature and humidity sensor. The DHT11 or DHT22 sensors are affordable and readily available options


2.6 Power Supply:

For a wearable device, a compact and rechargeable power supply is crucial. A small LiPo battery with a capacity of 500mAh or higher should be sufficient.


Part 3: Circuit Connections and Wiring


Now that we have gathered all the necessary components, let's proceed with the circuit connections and wiring. Follow the steps below to ensure proper connectivity.


3.1 Heart Rate Sensor:

Connect the heart rate sensor to the ESP32 as follows:

- Connect the VCC pin of the heart rate sensor to the 3.3V pin on the ESP32.

- Connect the GND pin of the heart rate sensor to the GND pin on the ESP32.

- Connect the SDA pin of the heart rate sensor to the SDA pin (GPIO21) on the ESP32.

- Connect the SCL pin of the heart rate sensor to the SCL pin (GPIO22) on the ESP32.


3.2 Accelerometer and Gyroscope:

Connect the MPU-6050 module to the ESP32 as follows:

- Connect the VCC pin of the MPU-6050 module to the 3.3V pin on the ESP32.

- Connect the GND pin of the MPU-6050 module to the GND pin on the ESP32.

- Connect the SDA pin of the MPU-6050 module to the SDA pin (GPIO21) on the ESP32.

- Connect the SCL pin of the MPU-6050 module to the SCL pin (GPIO22) on the ESP32.


3.3 OLED Display:

Connect the OLED display to the ESP32 as follows:

- Connect the VCC pin of the OLED display to the 3.3V pin on the ESP32.

- Connect the GND pin of the OLED display to the GND pin on the ESP32.

- Connect the SDA pin of the OLED display to the SDA pin (GPIO4) on the ESP32.

- Connect the SCL pin of the OLED display to the SCL pin (GPIO15) on the ESP32.


3.4 Temperature and Humidity Sensor:

Connect the temperature and humidity sensor to the ESP32 as follows:

- Connect the VCC pin of the sensor to the 3.3V pin on the ESP32.

- Connect the GND pin of the sensor to the GND pin on the ESP32.

- Connect the data pin of the sensor to GPIO27 on the ESP32.


3.5 Power Supply:

Connect the LiPo battery to the ESP32 as follows:

- Connect the positive (+) terminal of the LiPo battery to the VIN pin on the ESP32.

- Connect the negative (-) terminal of the LiPo battery to the GND pin on the ESP32.


Part 4: Programming the ESP32


Now that our circuit connections are complete, it's time to program the ESP32 to monitor vital signs, track fitness activities, and provide health insights. We'll be using the Arduino IDE and the necessary libraries to simplify the development process. Follow the steps below to write the code for our personal health monitoring device.


4.1 Including the Required Libraries:

Before we start writing the code, we need to include the necessary libraries. Open the Arduino IDE and go to "Sketch" > "Include Library" > "Manage Libraries." Search for and install the following libraries if you haven't done so already:

- Adafruit SSD1306

- Adafruit GFX Library

- PubSubClient

- DHT Sensor Library


4.2 Initializing Libraries and Variables:

Let's start by initializing the libraries and defining the variables needed for our project. Add the following code at the beginning of your sketch:


#include <Wire.h>

#include <Adafruit_SSD1306.h>

#include <Adafruit_GFX.h>

#include <WiFi.h>

#include <PubSubClient.h>

#include <DHT.h>


#define SCREEN_WIDTH 128

#define SCREEN_HEIGHT 64

#define OLED_ADDRESS 0x3C


// Initialize the OLED display

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_ADDRESS);


// Wi-Fi credentials

const char* ssid = "YourWiFiSSID";

const char* password = "YourWiFiPassword";


// MQTT broker details

const char* mqtt_server = "mqtt_server_ip";

const char* mqtt_topic = "health_monitoring";


// Heart rate sensor pins

const int heartRatePin = 21;

const int ledPin = 2;


// Accelerometer and gyroscope object

MPU6050 mpu;


// Temperature and humidity sensor object

#define DHTPIN 27

#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);


// Variables to store sensor data

float temperature;

float humidity;

int heartRate;

float accelX, accelY, accelZ;

float gyroX, gyroY, gyroZ;


Make sure to replace "YourWiFiSSID" and "YourWiFiPassword" with your actual Wi-Fi credentials. Also, set the appropriate MQTT server IP and topic.


4.3 Setup Function:

The setup function is called once at the beginning of the sketch. In this function, we'll initialize the OLED display, connect to Wi-Fi, and configure the MQTT client. Add the following code after the variable definitions:


void setup() {

  // Initialize the OLED display

  display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDRESS);

  display.clearDisplay();

  display.setTextColor(WHITE);

  display.setTextSize(1);

  display.setCursor(0, 0);


  // Connect to Wi-Fi

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);

    display.println("Connecting to Wi-Fi...");

    display.display();

  }

  display.clearDisplay();

  display.println("Connected to Wi-Fi!");

  display.display();

  

  // Initialize the MQTT client

  client.setServer(mqtt_server, 1883);

  client.setCallback(callback);


  // Initialize the MPU-6050 sensor

  mpu.initialize();


  // Initialize the DHT sensor

  dht.begin();

}


4.4 Loop Function:

The loop function is where our main code execution occurs. It runs continuously once the setup function has completed. In this function, we'll read sensor data, publish it to the MQTT broker, and update the OLED display. Add the following code inside the loop function:


void loop()


 {

  // Read sensor data

  temperature = dht.readTemperature();

  humidity = dht.readHumidity();

  heartRate = getHeartRate();

  mpu.getMotion6(&accelX, &accelY, &accelZ, &gyroX, &gyroY, &gyroZ);


  // Publish sensor data to MQTT broker

  publishData();


  // Update the OLED display

  updateDisplay();


  // Check for incoming MQTT messages

  client.loop();

  

  delay(1000);

}


4.5 Supporting Functions:

We'll now add the supporting functions to our code. These functions handle reading the heart rate, publishing data to the MQTT broker, and updating the OLED display. Add the following code at the end of your sketch:


// Function to read heart rate

int getHeartRate() {

  // Code to read heart rate using the heart rate sensor

}


// Function to publish sensor data to MQTT broker

void publishData() {

  // Code to publish sensor data to MQTT broker

}


// Function to update the OLED display

void updateDisplay() {

  // Code to update the OLED display with sensor data

}


// MQTT callback function

void callback(char* topic, byte* payload, unsigned int length) {

  // Code to handle incoming MQTT messages

}


In the "getHeartRate" function, implement the logic to read the heart rate from the heart rate sensor. In the "publishData" function, publish the sensor data to the MQTT broker using the PubSubClient library. In the "updateDisplay" function, update the OLED display with the sensor data. The "callback" function handles incoming MQTT messages.


Part 5: Completing the Code and Additional Features


In this final part, we will complete the code for our personal health monitoring device and explore additional features to enhance its functionality. Let's continue where we left off.


5.1 Completing the Code:

To finalize the code, we need to implement the remaining sections and functions. Here's the complete code with the missing sections:


#include <Wire.h>

#include <Adafruit_SSD1306.h>

#include <Adafruit_GFX.h>

#include <WiFi.h>

#include <PubSubClient.h>

#include <DHT.h>

#include <Wire.h>

#include <Adafruit_MPU6050.h>


#define SCREEN_WIDTH 128

#define SCREEN_HEIGHT 64

#define OLED_ADDRESS 0x3C


Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_ADDRESS);


const char* ssid = "YourWiFiSSID";

const char* password = "YourWiFiPassword";

const char* mqtt_server = "mqtt_server_ip";

const char* mqtt_topic = "health_monitoring";


const int heartRatePin = 21;

const int ledPin = 2;


Adafruit_MPU6050 mpu;

#define DHTPIN 27

#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);


float temperature;

float humidity;

int heartRate;

float accelX, accelY, accelZ;

float gyroX, gyroY, gyroZ;


WiFiClient espClient;

PubSubClient client(espClient);


void setup() {

  display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDRESS);

  display.clearDisplay();

  display.setTextColor(WHITE);

  display.setTextSize(1);

  display.setCursor(0, 0);


  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);

    display.println("Connecting to Wi-Fi...");

    display.display();

  }

  display.clearDisplay();

  display.println("Connected to Wi-Fi!");

  display.display();

  

  client.setServer(mqtt_server, 1883);

  client.setCallback(callback);


  mpu.begin();

  dht.begin();

}


void loop() {

  temperature = dht.readTemperature();

  humidity = dht.readHumidity();

  heartRate = getHeartRate();

  mpu.getMotion6(&accelX, &accelY, &accelZ, &gyroX, &gyroY, &gyroZ);


  publishData();

  updateDisplay();


  client.loop();

  

  delay(1000);

}


int getHeartRate() {

  // Code to read heart rate using the heart rate sensor

  // Implement the logic to read the heart rate from the sensor

}


void publishData() {

  // Code to publish sensor data to MQTT broker

  String payload = "Temperature: " + String(temperature) + "°C\n";

  payload += "Humidity: " + String(humidity) + "%\n";

  payload += "Heart Rate: " + String(heartRate) + " bpm\n";

  payload += "Acceleration (X, Y, Z): " + String(accelX) + ", " + String(accelY) + ", " + String(accelZ) + "\n";

  payload += "Gyroscope (X, Y, Z): " + String(gyroX) + ", " + String(gyroY) + ", " + String(gyroZ) + "\n";


  if (client.connect("esp32Client")) {

    client.publish(mqtt_topic, payload.c_str());

  }

}


void updateDisplay() {

  // Code to update the OLED display with sensor data

  display.clearDisplay


();

  display.setTextSize(1);

  display.setCursor(0, 0);

  display.println("Temperature: " + String(temperature) + "°C");

  display.println("Humidity: " + String(humidity) + "%");

  display.println("Heart Rate: " + String(heartRate) + " bpm");

  display.println("Acceleration (X, Y, Z):");

  display.println(String(accelX) + ", " + String(accelY) + ", " + String(accelZ));

  display.println("Gyroscope (X, Y, Z):");

  display.println(String(gyroX) + ", " + String(gyroY) + ", " + String(gyroZ));

  display.display();

}


void callback(char* topic, byte* payload, unsigned int length) {

  // Code to handle incoming MQTT messages

  // Implement the logic to handle incoming messages if needed

}


Make sure to replace "YourWiFiSSID" and "YourWiFiPassword" with your actual Wi-Fi credentials. Set the appropriate MQTT server IP and topic.


5.2 Additional Features:

To enhance the functionality of our personal health monitoring device, you can consider implementing the following features:


5.2.1 Data Storage: Instead of only publishing the sensor data to the MQTT broker, you can save it to an SD card or a cloud database for later analysis and visualization.


5.2.2 Real-time Alerts: Implement a mechanism to send alerts or notifications to the user's smartphone or email if certain vital signs exceed predefined thresholds.


5.2.3 Sleep Monitoring: Use the accelerometer and gyroscope data to analyze sleep patterns, detect sleep stages, and provide insights into sleep quality.


5.2.4 GPS Tracking: Integrate a GPS module to track the user's outdoor activities, such as running or cycling, and provide distance, speed, and route information.


5.2.5 Mobile App Integration: Develop a mobile app that can connect to the ESP32 device via Bluetooth or Wi-Fi, allowing users to view real-time data, set personalized goals, and receive personalized health recommendations.


Remember to consider factors such as power consumption, data privacy, and user interface design while implementing these additional features.


Future improvements


Here are some ideas for future improvements and enhancements to your personal health monitoring device:


1. User Interface: Improve the user interface of the OLED display by adding graphical representations of data, such as charts or icons. This can make it easier for users to interpret and understand their health information at a glance.


2. Machine Learning Algorithms: Implement machine learning algorithms to analyze the collected data and provide more advanced health insights. For example, you could develop algorithms to detect anomalies in heart rate patterns or predict potential health issues based on historical data.


3. Sleep Tracking: Enhance the sleep monitoring feature by incorporating additional sensors like a light sensor or a pulse oximeter. This can provide more accurate data on sleep quality and help identify sleep disorders like sleep apnea.


4. Integration with Health Platforms: Integrate your device with popular health platforms or fitness apps. This allows users to sync their data with other health and fitness services, access comprehensive reports, and participate in challenges or wellness programs.


5. Customizable Alerts: Give users the ability to set personalized alerts and notifications based on their specific health goals or thresholds. For example, users could receive notifications when their heart rate goes above a certain level during exercise.


6. Long-Term Data Analysis: Develop a feature that allows users to analyze their long-term health data trends. This can include generating reports, visualizing historical data, and identifying patterns or correlations between different health parameters.


7. Energy Efficiency: Optimize the power consumption of the device by implementing power-saving techniques, such as sleep modes for different components or using low-power sensors. This ensures longer battery life and overall improved usability.


8. Wireless Data Synchronization: Enable wireless data synchronization with a mobile app or a cloud service. This eliminates the need for physical connections and provides users with seamless access to their health data across multiple devices.


9. Personalized Recommendations: Utilize the collected data to provide personalized health recommendations to users. This can include exercise routines, dietary suggestions, or reminders for medication intake based on individual health profiles.


10. Wearable Design Improvements: Continuously refine the design of the wearable device to make it more comfortable, aesthetically pleasing, and user-friendly. Consider using flexible or biocompatible materials for improved wearability and ergonomics.


Remember to always prioritize user privacy and data security when implementing new features or connecting to external services. Regularly update and maintain your device's firmware to address any security vulnerabilities.


These are just a few ideas to inspire future improvements for your personal health monitoring device. Feel free to adapt or combine them based on your specific goals and requirements. Good luck with your project!


Happy monitoring and tracking!