ESP32 with MAX30102 Pulse Oximeter and Heart Rate Sensor

The MAX30102 is a small optical sensor that measures heart rate and blood oxygen saturation (SpO2). It contains a red LED, an infrared LED and a photodetector, and it talks to a microcontroller over I2C. In this tutorial you connect a MAX30102 module to an ESP32 and print the heart rate and SpO2 to the Serial Monitor.

Illustration

The project uses the SparkFun MAX3010x library, which includes the algorithm that converts the raw red and infrared readings into beats per minute and an SpO2 percentage. This project is for learning and hobby use only. It is not a medical device and must not be used to diagnose or monitor any health condition.

How the MAX30102 Works

The sensor shines light into your fingertip and measures how much of it comes back.

  1. The sensor turns on its red and infrared LEDs, one after the other.
  2. Light passes through the fingertip and a photodetector measures the amount that is reflected back.
  3. Each heartbeat pushes more blood through the finger, so the amount of absorbed light changes slightly with every pulse.
  4. Oxygen-rich and oxygen-poor blood absorb red and infrared light differently, so the ratio between the two signals tells how much oxygen the blood carries.
  5. The ESP32 reads the raw samples over I2C and passes them to the library algorithm.
  6. The algorithm finds the pulse peaks to calculate the heart rate and uses the red to infrared ratio to estimate SpO2.

The heart rate is the number of beats per minute, found from the time between two pulse peaks:

Heart rate (BPM) = 60 / time between two beats in seconds

Hardware and Settings

ItemChoiceReason
MicrocontrollerESP32 development boardReads the sensor and prints the results
SensorMAX30102 moduleMeasures heart rate and SpO2
Jumper WiresFemale-to-female or male-to-femaleConnects the module to the board
BreadboardOptionalHolds the module while testing
USB CableUSB data cablePowers and programs the ESP32

Wiring Connections

Connect the MAX30102 module to the ESP32 as shown below.

MAX30102 to ESP32

MAX30102 PinESP32 PinFunction
VIN3V3Sensor power
GNDGNDCommon ground
SDAGPIO21I2C data
SCLGPIO22I2C clock
INTNot connectedInterrupt output, not used in this sketch

GPIO21 and GPIO22 are the default I2C pins on most ESP32 development boards. Pin labels and the position of pins can differ between module manufacturers, so check the markings on your board before connecting.

Installing the Library

  1. Open the Arduino IDE and go to Sketch > Include Library > Manage Libraries.
  2. Search for SparkFun MAX3010x and install SparkFun MAX3010x Pulse and Proximity Sensor Library.
  3. Make sure the ESP32 board package is installed under Tools > Board > Boards Manager.

Complete Code

ESP32 reads the red and infrared signals from the MAX30102 and prints heart rate and SpO2 to the Serial Monitor.
#include <Wire.h>
#include "MAX30105.h"
#include "spo2_algorithm.h"

MAX30105 particleSensor;

const int32_t bufferLength = 100;   // 100 samples = about 4 seconds at 25 samples per second
uint32_t irBuffer[bufferLength];
uint32_t redBuffer[bufferLength];

int32_t spo2;
int8_t validSPO2;
int32_t heartRate;
int8_t validHeartRate;

const uint32_t fingerThreshold = 50000;  // IR value below this means no finger is on the sensor

void readSamples(int from, int to) {
  for (int i = from; i < to; i++) {
    // Wait until the sensor has a new sample
    while (!particleSensor.available()) {
      particleSensor.check();
    }
    redBuffer[i] = particleSensor.getRed();
    irBuffer[i] = particleSensor.getIR();
    particleSensor.nextSample();
  }
}

void calculate() {
  maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer,
                                         &spo2, &validSPO2,
                                         &heartRate, &validHeartRate);
}

void setup() {
  Serial.begin(115200);
  Wire.begin(21, 22);  // SDA = GPIO21, SCL = GPIO22

  if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) {
    Serial.println("MAX30102 not found. Check the wiring and power.");
    while (true) {
      delay(1000);
    }
  }

  byte ledBrightness = 60;  // 0 to 255
  byte sampleAverage = 4;   // 1, 2, 4, 8, 16 or 32
  byte ledMode = 2;         // 2 = red and infrared LEDs
  int sampleRate = 100;     // samples per second
  int pulseWidth = 411;     // microseconds
  int adcRange = 4096;      // ADC range in nA

  particleSensor.setup(ledBrightness, sampleAverage, ledMode,
                       sampleRate, pulseWidth, adcRange);

  Serial.println("Place your fingertip on the sensor and keep it still.");

  // Collect the first 100 samples
  readSamples(0, bufferLength);
  calculate();
}

void loop() {
  // Drop the oldest 25 samples and keep the newest 75
  for (int i = 25; i < bufferLength; i++) {
    redBuffer[i - 25] = redBuffer[i];
    irBuffer[i - 25] = irBuffer[i];
  }

  // Collect 25 new samples
  readSamples(bufferLength - 25, bufferLength);

  if (irBuffer[bufferLength - 1] < fingerThreshold) {
    Serial.println("No finger detected.");
    return;
  }

  calculate();

  Serial.print("Heart rate: ");
  if (validHeartRate) {
    Serial.print(heartRate);
    Serial.print(" BPM");
  } else {
    Serial.print("--");
  }

  Serial.print("   SpO2: ");
  if (validSPO2) {
    Serial.print(spo2);
    Serial.println(" %");
  } else {
    Serial.println("--");
  }
}

How the Code Works

  • particleSensor.setup() sets the LED brightness, averaging, sample rate and ADC range of the sensor.
  • readSamples() waits for new data and stores the red and infrared values in two buffers.
  • maxim_heart_rate_and_oxygen_saturation() analyses 100 samples and returns the heart rate and SpO2 together with a valid flag for each result.
  • The sketch works as a sliding window. In every pass of loop() it discards the oldest 25 samples, adds 25 new ones and recalculates, so a new result appears about every second.
  • If the infrared value is below fingerThreshold, no finger is on the sensor and the sketch skips the calculation.

Uploading and Testing

  1. Connect the ESP32 to your computer using a USB cable.
  2. Open the Arduino IDE and select your ESP32 board under Tools > Board, for example ESP32 Dev Module.
  3. Select the correct serial port under Tools > Port.
  4. Copy the code into a new sketch and upload it. If the upload does not start, hold the BOOT button on the ESP32 while the IDE shows "Connecting...".
  5. Open the Serial Monitor and set the baud rate to 115200.
  6. Rest your index fingertip lightly on the sensor and keep it still. Do not press hard, because too much pressure reduces blood flow and weakens the signal.
  7. After a few seconds the Serial Monitor shows the heart rate and SpO2. A reading of -- means the result is not valid yet.

Expect the values to vary a little between readings. Finger movement, ambient light and cold fingers all affect the result.

Improving Accuracy

  • Cover the sensor and your finger with your other hand or a dark cloth to block ambient light.
  • Keep your hand relaxed and still while the sensor collects samples.
  • Warm your fingers if they are cold, because cold fingers have weak blood flow.
  • Increase ledBrightness if the signal is weak, or reduce it if the infrared value is very high.
  • Compare the heart rate with a reliable device to see how far the readings can differ.

Common Problems

  • The Serial Monitor shows "MAX30102 not found": Check the SDA and SCL wires, confirm the module is powered from 3V3 and make sure the wires are firmly connected.
  • Heart rate and SpO2 always show --: Place your finger on the sensor, keep it still and wait at least 10 seconds. Check that the sensor window is clean.
  • The Serial Monitor shows "No finger detected" with a finger on the sensor: Press slightly harder, or lower fingerThreshold for your module.
  • The readings jump around: Keep the finger still, block ambient light and avoid pressing too hard on the sensor.
  • The code does not compile because spo2_algorithm.h is missing: Install the SparkFun MAX3010x library again and restart the Arduino IDE.
  • The Serial Monitor displays unreadable characters: Set the baud rate to 115200, matching Serial.begin(115200) in the sketch.

Summary

This project connects a MAX30102 pulse oximeter and heart rate sensor to an ESP32 over I2C. The sensor measures red and infrared light reflected from a fingertip, and the SparkFun library algorithm converts the readings into a heart rate in beats per minute and an SpO2 percentage. You learned how the sensor works, how to wire it to the ESP32 and how to use a sliding window of samples to get a new result every second. The values are only estimates for learning and experiments, not for medical use.