DEV Community

Shilleh
Shilleh

Posted on

How to Measure Heart Rate and Blood Oxygen Levels with MAX30102 Sensor on a Raspberry Pi Using Python

The MAX30102 is a compact, powerful sensor that allows you to measure heart rate and blood oxygen levels (SpO2) with high precision. This tutorial will guide you through connecting the MAX30102 sensor to a Raspberry Pi, setting up the necessary software, and writing Python code to obtain accurate heart rate and SpO2 readings. This is Part 1 of a series. In the next post, we’ll set up a Flask app to display the data in real time!

What You Will Need

  • Raspberry Pi (any model with I2C support)
  • MAX30102 Heart Rate and SpO2 sensor
  • Jumper wires
  • Breadboard (optional, for easier connections)
  • Internet connection for downloading software and libraries

— — -

Before we delve into the topic, we invite you to support our ongoing efforts and explore our various platforms dedicated to enhancing your IoT projects:

  • Subscribe to our YouTube Channel: Stay updated with our latest tutorials and project insights by subscribing to our channel at YouTube — Shilleh.
  • Support Us: Your support is invaluable. Consider buying me a coffee at Buy Me A Coffee to help us continue creating quality content.
  • Hire Expert IoT Services: For personalized assistance with your IoT projects, hire me on UpWork.

ShillehTek Website (Exclusive Discounts):

https://shillehtek.com/collections/all

ShillehTekAmazon Store:

ShillehTek Amazon Store — US

ShillehTek Amazon Store — Canada

ShillehTek Amazon Store — Japan

Step 1: Wiring the MAX30102 Sensor

Image description

Wiring Connections for MAX30102 Sensor:

  • VCC: Connect to 3.3V (Pin 1) on the Raspberry Pi — Power
  • GND: Connect to GND (Pin 6) on the Raspberry Pi — Ground
  • SDA: Connect to SDA (GPIO 2, Pin 3) on the Raspberry Pi — I2C Data
  • SCL: Connect to SCL (GPIO 3, Pin 5) on the Raspberry Pi — I2C Clock Optionally you can use a breadboard as well or connect directly to the sensor.

Image description

If using a breadboard, the connection would look like above. Where the sensor is inserted into the breadboard, along with jumper wires.

Step 2: Enable I2C on Raspberry Pi

Before diving into the code, ensure that the I2C interface is enabled on your Raspberry Pi:

Open the terminal and run the Raspberry Pi configuration tool:



sudo raspi-config


Enter fullscreen mode Exit fullscreen mode

Navigate to Interface Options > I2C and select Yes to enable the I2C interface.

Reboot the Raspberry Pi to apply the changes.

Step 3: Download and Set Up the MAX30102 Library

Download the MAX30102 library and its dependencies. You can find the library here: MAX30102 GitHub Repository.

Clone the repository to your Raspberry Pi’s Desktop, you can go to the link and download and unzip the repo

Image description

Or you can clone the code on your computer using git



cd ~/Desktop
git clone https://github.com/doug-burrell/max30102.git


Enter fullscreen mode Exit fullscreen mode

Navigate to the directory where you downloaded the repository, you can use the cd command in the terminal



cd max30102


Enter fullscreen mode Exit fullscreen mode

Unzip all the files and ensure they are in the same directory as your Python script to avoid any import errors.

Step 4: Install Required Python Packages

You need to install a few Python packages to interface with the MAX30102 sensor and handle I2C communication:



sudo apt-get update
sudo apt-get install -y python3-pip python3-smbus i2c-tools


Enter fullscreen mode Exit fullscreen mode

Step 5: Python Code to Read Heart Rate and SpO2

With the wiring complete and software installed, it’s time to write the Python script to read data from the sensor:



import max30102
import hrcalc
import time

# Initialize the MAX30102 sensor
m = max30102.MAX30102()

def read_sensor():
        while True:
            # Read data from the sensor
            red, ir = m.read_sequential()
            # Calculate heart rate and SpO2
            hr, hr_valid, spo2, spo2_valid = hrcalc.calc_hr_and_spo2(ir, red)

            # Check if valid readings are obtained
            if hr_valid and spo2_valid:
                print("Heart Rate: ", hr, "BPM")
                print("SpO2 Level: ", spo2, "%")
            else:
                print("Invalid readings. Please try again.")

            # Wait for a short time before reading again
            time.sleep(1)

if __name__ == "__main__":
    read_sensor()


Enter fullscreen mode Exit fullscreen mode

How the Code Works:

  • Import Libraries: We import the max30102 library to interact with the sensor, hrcalc to perform heart rate and SpO2 calculations, and time for delays.
  • Initialize the Sensor: The MAX30102() class initializes the sensor to begin readings.
  • Read and Calculate: The read_sequential() function reads the raw red and IR light data. These values are then used to calculate the heart rate (hr) and SpO2 levels using hrcalc.calc_hr_and_spo2().
  • Display Results: The script checks if the readings are valid and prints the heart rate and SpO2 level if they are. If not, it prompts the user to try again.
  • Loop: The script runs in an infinite loop, continuously reading and displaying data until interrupted.

Remember to place your index finger gently on the sensor for the most accurate readings. Now you’re all set to work with your MAX30102 sensor in a controlled and efficient environment!

Here is an example output you will see once you start placing your finger on the sensor, otherwise it will show invalid. Good luck!

Image description

Conclusion
You now have a working setup to measure heart rate and blood oxygen levels using a MAX30102 sensor and Raspberry Pi. This setup provides a solid foundation for further projects, such as creating a web interface to visualize data in real time. Stay tuned for Part 2, where we’ll build a Flask app to display these readings dynamically on a web page!

Feel free to share your thoughts, questions, or improvements in the comments below.

Top comments (0)