Siddhant Kumar
Project 015 · Health & Wearables

Heart-Rate & SpO2 Band.

A wrist band that measures pulse rate and blood-oxygen saturation using photoplethysmography — built with the signal processing done properly, and with an honest account of what a wrist sensor can and cannot tell you.

Advanced 16–24 hours 40 min read WearableBLEHealth
Jump to source Bill of materials
Heart-Rate & SpO2 Band — reference build illustration MCU VCC · GND · SIG · NC
Difficulty
Advanced
Build time
16–24 hours
Indicative cost
₹2,700 – ₹3,500
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Health & Wearables
Last updated
28 July 2026
Contents — 25 sections

Project Overview

A wrist band that measures pulse rate and blood-oxygen saturation using photoplethysmography — built with the signal processing done properly, and with an honest account of what a wrist sensor can and cannot tell you.

Photoplethysmography is deceptively simple to demonstrate and genuinely difficult to do well. Shine light into skin, measure how much comes back, and the reflected intensity varies with each heartbeat as blood volume in the capillary bed changes. Getting a plausible-looking waveform takes twenty minutes. Getting a heart rate that is correct while the wearer moves, and an SpO₂ figure that means anything at all, takes the rest of this project.

The MAX30102 does the analogue work: two LEDs (red at 660 nm and infrared at 880 nm), a photodiode, an 18-bit ADC and ambient light cancellation, all in a 5.6 × 3.3 mm package. What it does not do is any of the signal processing. The raw output is a slowly drifting DC level with a small AC component riding on it — the pulsatile part is typically 0.5 to 2 % of the total signal. Everything interesting happens in that fraction.

The pipeline here is the standard clinical one, implemented explicitly rather than hidden in a library. A DC-removal filter tracks and subtracts the baseline. A band-pass filter from 0.5 to 4 Hz keeps the physiological range (30 to 240 bpm) and rejects both respiratory drift below it and noise above. Peak detection with an adaptive threshold and a physiological refractory period finds beats. And a signal-quality index gates the output, because a confident wrong heart rate is worse than no heart rate.

On SpO₂, this project is deliberately blunt about its limits. The ratio-of-ratios method is genuine physics and works. But a reflectance sensor on a wrist, calibrated with a generic curve rather than against a co-oximeter on real volunteers spanning a range of desaturations, is not a medical device and its absolute values should not be trusted. What it is good for is trends in a single individual under consistent conditions — which is still useful, and is what the firmware reports.

A wrist-worn fitness tracker
A wrist-worn fitness tracker. The optical sensor window must contact skin directly — a recess of even one millimetre halves the usable signal. Photograph sourced from Wikimedia Commons — Fitness tracker.jpg. Reused under the licence stated on that page; please check it before republishing.

What this project does

  • Measures red and infrared PPG at 100 Hz with the MAX30102 in SpO₂ mode.
  • Extracts heart rate through DC removal, band-pass filtering and adaptive peak detection.
  • Computes SpO₂ from the ratio of red to infrared AC/DC ratios.
  • Reports a signal-quality index and suppresses output when the reading is unreliable.
  • Rejects motion artefacts using a companion accelerometer.
  • Computes heart-rate variability (RMSSD) from beat-to-beat intervals during still periods.
  • Streams over BLE to a phone and logs locally when out of range.

Real-World Applications

SettingHow it is used
Resting heart-rate trackingA daily resting figure taken under consistent conditions is one of the more genuinely informative fitness metrics.
Heart-rate variability for training loadMorning RMSSD trends track autonomic recovery reasonably well when measured consistently.
Sleep heart-rate patternsOvernight is the ideal PPG condition — still wrist, stable temperature, hours of clean data.
Learning biomedical signal processingPPG is the most accessible real physiological signal, and every technique here transfers to ECG and EEG work.
Altitude and breathing exercisesSpO₂ trends during breath-holds or at altitude are visible even with an uncalibrated sensor.
Prototyping for a certified deviceUnderstanding this pipeline is a prerequisite for any serious work on medical wearables.

Deployment contexts where a build of this kind earns its keep.

Features & Capabilities

  • Explicit DSP pipeline — every filter stage is visible and tunable, not hidden in a black-box library.
  • Adaptive peak detection with a 300 ms refractory period, matching the physiological minimum beat interval.
  • Signal quality index derived from beat-interval regularity and perfusion amplitude.
  • Accelerometer gating — heart rate is only reported when the wrist is reasonably still.
  • RMSSD heart-rate variability computed over 60-second still windows.
  • BLE Heart Rate Service so any standard fitness app can read it.
  • Low-power duty cycling: the LEDs are the dominant load, so they run 25 % of the time.
  • Local ring buffer holding four hours of beat intervals for out-of-range logging.

Difficulty, Time & Required Skills

AttributeValue
Difficulty levelAdvanced
Estimated completion time16–24 hours
Indicative build cost₹2,700 – ₹3,500
Primary disciplineHealth & Wearables
Reference platformESP32 DevKit V1 (ESP-WROOM-32)

Skills you should have (or will pick up)

  • Arduino C++ with fixed-point and floating-point DSP
  • Digital filter concepts: IIR, cut-off frequency, group delay
  • I²C sensor configuration through registers
  • BLE GATT services and characteristics
  • Enough physiology to know what you are measuring

Bill of Materials

Every part below is commonly available from Indian and international hobby-electronics suppliers. Prices are indicative 2026 retail figures in Indian rupees and will drift — treat them as a budgeting guide, not a quotation.

ComponentKey specificationQtyApprox. cost
ESP32 DevKit V1 (ESP-WROOM-32)
Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly.
Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC1₹450
MAX30102 pulse oximeter + heart-rate sensor
Contact pressure dominates signal quality — a loose sensor gives a beautiful-looking, meaningless waveform.
Red 660 nm + IR 880 nm LEDs, 18-bit ADC, 50–3200 SPS, on-chip temperature1₹380
ADXL345 3-axis accelerometer
Built-in activity/free-fall interrupts let the MCU deep-sleep until something moves.
±2/4/8/16 g, 13-bit, 0.004 g/LSB, tap and free-fall interrupts, 3200 Hz1₹220
0.96″ SSD1306 OLED display
Static images burn in — invert or scroll the screen periodically.
128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C1₹250
18650 Li-ion cell 3400 mAh + holder
Never charge below 0 °C; always use a protected cell or a BMS.
3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge1₹450
TP4056 Li-ion charger + DW01 protection
Buy the version *with* protection ICs — the bare charger will over-discharge your cell.
1 A programmable CC/CV charge to 4.2 V ±1 %, over-discharge and short protection1₹45
Double-sided perfboard 7 × 9 cm + headers
Solder female headers so the MCU can be swapped without desoldering.
FR-4, 0.1″ pitch, plated through-holes, 24 × 18 grid1₹60
3D-printed wrist enclosure + strap
The optical window must sit flush against skin — a recessed sensor gives no usable signal.
TPU or PETG, 22 mm strap lugs1₹250
Black opaque skirt / light seal
Blocks ambient light leaking around the sensor. Improves SNR more than any firmware change.
Adhesive foam, 1 mm1₹60
4.7 kΩ I²C pull-ups1 % metal film1₹10

Estimated total: ₹2,175, excluding tools, shipping and consumables.

Tools and consumables

  • Soldering iron (temperature controlled, 350 °C) with 0.8 mm 60/40 or lead-free solder
  • Digital multimeter — continuity, DC volts and current ranges
  • Wire strippers, flush cutters and a small set of precision screwdrivers
  • Heat-shrink tubing and a heat gun (or a lighter, carefully)
  • A laptop with a USB port and the toolchain listed above

Hardware Specifications

PartSpecificationSupplyInterfaceReference
ESP32 DevKit V1 (ESP-WROOM-32)Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC3.3 V logic / 5 V USBUART, SPI, I²C, I²S, CAN, PWMDatasheet
MAX30102 pulse oximeter + heart-rate sensorRed 660 nm + IR 880 nm LEDs, 18-bit ADC, 50–3200 SPS, on-chip temperature1.8 V + 3.3 V (module regulates)I²C (0x57)Datasheet
ADXL345 3-axis accelerometer±2/4/8/16 g, 13-bit, 0.004 g/LSB, tap and free-fall interrupts, 3200 Hz2.0–3.6 VI²C / SPIDatasheet
0.96″ SSD1306 OLED display128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C3.3–5 VI²C (0x3C)Datasheet
18650 Li-ion cell 3400 mAh + holder3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge3.0–4.2 VHolder / spot-welded tabsDatasheet
TP4056 Li-ion charger + DW01 protection1 A programmable CC/CV charge to 4.2 V ±1 %, over-discharge and short protection4.5–5.5 V inmicro-USB / padsDatasheet
Double-sided perfboard 7 × 9 cm + headersFR-4, 0.1″ pitch, plated through-holes, 24 × 18 gridDatasheet

Consolidated electrical and interface specifications for every active part in the build.

Power Budget & Supply Sizing

Add up the typical active current of every part, then size the supply with at least 50 % headroom so transmit bursts and motor inrush never brown out the controller.

LoadSupply railTypical current (mA)Notes
ESP32 DevKit V1 (ESP-WROOM-32)3.3 V logic / 5 V USB160Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly.
MAX30102 pulse oximeter + heart-rate sensor1.8 V + 3.3 V (module regulates)5.5Contact pressure dominates signal quality — a loose sensor gives a beautiful-looking, meaningless waveform.
ADXL345 3-axis accelerometer2.0–3.6 V0.14Built-in activity/free-fall interrupts let the MCU deep-sleep until something moves.
0.96″ SSD1306 OLED display3.3–5 V20Static images burn in — invert or scroll the screen periodically.
TP4056 Li-ion charger + DW01 protection4.5–5.5 V in1000Buy the version *with* protection ICs — the bare charger will over-discharge your cell.

Summed typical draw is 1185.6399999999999 mA. With a 1.5× design margin the supply should deliver at least 1800 mA continuously at the stated rail voltage.

Software Requirements & Development Environment

Reference toolchain: Arduino IDE 2.3.x with the ESP32 board package 3.x (or PlatformIO on VS Code). Anything newer normally works; anything older may lack the board definitions used here.

  • Install the Arduino IDE 2.3.x (or PlatformIO if you prefer a real editor and dependency locking).
  • Add https://espressif.github.io/arduino-esp32/package_esp32_index.json under File → Preferences → Additional Board Manager URLs, then install esp32 from the Boards Manager.
  • Set the correct port under Tools → Port. On Linux add yourself to the dialout group: sudo usermod -aG dialout $USER and log out and back in.
  • Open the Serial Monitor at 115200 baud — every sketch here logs its state there.
  • Keep File → Preferences → Show verbose output during: compilation switched on while you are debugging build errors.

Required libraries

LibraryWhy it is neededInstall
WiFi (ESP32 core) bundledStation/AP connection management for the ESP32.Bundled with the ESP32 Arduino core
ArduinoJson 7.xZero-allocation JSON serialisation and parsing.Library Manager → "ArduinoJson" by Benoit Blanchon
Adafruit SSD1306 + GFX 2.5.xFramebuffer and text/graphics primitives for the OLED.Library Manager → "Adafruit SSD1306"
Preferences (NVS) bundledWear-levelled key/value storage in ESP32 flash for settings.Bundled with the ESP32 core

Block Diagram

The block diagram shows the functional decomposition of the system — what senses, what decides, what acts, and where the data ends up.

Heart-Rate & SpO2 Band — system block diagramFunctional block diagram of the Heart-Rate & SpO2 Band system. OpticalRed 660 nm LEDpulsedIR 880 nm LEDpulsedPhotodiode + ADC18-bit, 100 HzConditionDC removalbaseline trackingBand-pass 0.5–4 HzphysiologicalExtractPeak detectadaptive + refractoryRatio of ratiosSpO₂GateMotion gateaccelerometerQuality indexsuppress if poorraw FIFOAC signalcandidates
Heart-Rate & SpO2 Band — system block diagram

Circuit Diagram & Wiring

Every signal line in the build is shown below, followed by a pin-by-pin connection table you can work through with a multimeter in hand.

Heart-Rate & SpO2 Band — wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBMAX30102GPIO 21 / 22I²C at 0x57, 400 kHzMAX30102GPIO 27FIFO almost-fullinterruptADXL345GPIO 21 / 22Shared I²C, 0x53Battery dividerGPIO 341 MΩ / 1 MΩ, MOSFETgatedSSD1306 OLEDGPIO 21 / 22Shared I²C, 0x3CVibration motorGPIO 25Haptic feedbackButtonGPIO 33Wake / mode
Heart-Rate & SpO2 Band — wiring schematic
PeripheralPeripheral pinController pinSignal
MAX30102SDA / SCLGPIO 21 / 22I²C at 0x57, 400 kHz
MAX30102INTGPIO 27FIFO almost-full interrupt
ADXL345SDA / SCLGPIO 21 / 22Shared I²C, 0x53
Battery dividerMid-pointGPIO 341 MΩ / 1 MΩ, MOSFET gated
SSD1306 OLEDSDA / SCLGPIO 21 / 22Shared I²C, 0x3C
Vibration motorMOSFET gateGPIO 25Haptic feedback
ButtonNOGPIO 33Wake / mode

Wire one row at a time and tick it off — most "it does not work" reports trace back to a single swapped pair.

Wiring explanation

  • The MAX30102 module is 1.8 V core with a 3.3 V I²C interface. Most breakout boards include the regulator and level shifting — check yours does before connecting to a 3.3 V bus, because some bare modules do not.
  • The sensor must contact skin directly with no air gap. A 1 mm gap admits ambient light and reduces the pulsatile signal by more than half. Design the enclosure so the sensor face is proud of the surrounding surface, not recessed.
  • Fit an opaque skirt around the sensor. Ambient light — especially sunlight and fluorescent flicker at 100 Hz — is the largest noise source in reflectance PPG, and the MAX30102's ambient cancellation only handles so much.
  • Run I²C at 400 kHz. At 100 Hz sampling with two channels and an 18-bit FIFO, 100 kHz is marginal and you will drop samples.
  • The accelerometer must be rigidly attached to the same body as the sensor. If it can move independently, its motion signal does not correspond to the sensor's motion and the artefact rejection does nothing.
  • Keep the LED supply well decoupled. The MAX30102 pulses its LEDs at up to 50 mA, and the resulting supply ripple couples straight into the photodiode reading if the decoupling is inadequate.
An electrocardiogram waveform trace
A physiological waveform trace. PPG has a similar periodic structure to an ECG but measures blood volume rather than electrical activity. Photograph sourced from Wikimedia Commons — ECG trace.png. Reused under the licence stated on that page; please check it before republishing.

System Architecture

Read the stack from the bottom up: physical hardware, the firmware that drives it, the transport that moves data off the device, and the software a human actually looks at.

Heart-Rate & SpO2 Band — architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) · MAX30102 pulse oximeter + heart-ratesensorDriver layerwifi · arduinojson · ssd1306 · preferencesApplication logicsampling loop · filtering · thresholds · state machinePresentation layerlocal display · serial console · logged output
Heart-Rate & SpO2 Band — architecture stack

Working Principle

Every heartbeat pushes a pressure wave through the arterial tree, and in the capillary bed under the skin that wave momentarily increases blood volume. Haemoglobin absorbs light, so more blood means less light returns to the photodiode. The resulting signal has two parts: a large DC component from tissue, bone, venous blood and the baseline arterial volume, and a small AC component — typically 0.5 to 2 % of the DC at the wrist — that pulses with the heart. On a fingertip the AC fraction is five to ten times larger, which is exactly why clinical pulse oximeters clip to a finger and why wrist devices are harder.

Heart rate comes from the AC component alone, so the first job is removing the DC. A simple approach — subtracting a long moving average — introduces phase distortion. Better is a one-pole DC-blocking filter, y[n] = x[n] − x[n−1] + α·y[n−1] with α around 0.95, which removes DC with minimal group delay. What remains is band-pass filtered between 0.5 Hz (30 bpm) and 4 Hz (240 bpm): below that is respiratory and postural drift, above it is noise and the harmonics that confuse peak detection.

Peak detection then needs two guards. An adaptive threshold set to a fraction of a decaying running maximum handles the fact that signal amplitude varies with perfusion, temperature and how tight the strap is. And a refractory period of 300 ms — corresponding to 200 bpm, above any plausible resting rate — prevents the dicrotic notch, the secondary bump from aortic valve closure that appears in every PPG waveform, from being counted as a second beat. Missing that refractory period is the single most common cause of a heart rate that reads exactly double.

SpO₂ uses a different principle. Oxygenated and deoxygenated haemoglobin have different absorption spectra: at 660 nm (red) deoxyhaemoglobin absorbs much more than oxyhaemoglobin, while at 880 nm (infrared) the relationship reverses and is much flatter. Take the ratio of the pulsatile to non-pulsatile component at each wavelength, then take the ratio of those ratios: R = (AC_red/DC_red) / (AC_ir/DC_ir). Because both wavelengths pass through the same tissue, path length and most confounders cancel. R maps to saturation through an empirical curve.

That curve is where the honesty comes in. Clinical pulse oximeters are calibrated by inducing controlled hypoxia in human volunteers down to about 70 % saturation and fitting R against simultaneous arterial blood co-oximetry. You cannot do that. The commonly quoted approximation SpO₂ ≈ 110 − 25·R is a rough linearisation of that curve for transmissive fingertip sensors, and applying it to a reflectance wrist sensor introduces further error. It will track your saturation going down during a breath-hold; it will not give you a number a clinician should act on.

The maths behind it

DC-blocking and band-pass filters

plainDC-blocking and band-pass filters
DC blocker (one-pole high-pass):
  y[n] = x[n] − x[n−1] + α·y[n−1],   α = 0.95
  −3 dB at  f = (1 − α) · fs / (2π) = 0.05 × 100 / 6.283 ≈ 0.8 Hz

Low-pass (4-point moving average at fs = 100 Hz):
  y[n] = (x[n] + x[n−1] + x[n−2] + x[n−3]) / 4
  −3 dB at approximately 0.44 × fs / N = 11 Hz

Cascaded, the pass band is roughly 0.8–11 Hz, which
covers 48–660 bpm — deliberately wider than the
physiological range so the filter does not distort
the pulse morphology used for quality assessment.

Ratio of ratios and SpO₂

plainRatio of ratios and SpO₂
R = (AC_red / DC_red) / (AC_ir / DC_ir)

AC measured peak-to-peak over one beat,
DC measured as the mean over the same window.

Empirical linearisation (transmissive fingertip):
  SpO₂ ≈ 110 − 25 · R

  R = 0.5  →  97.5 %
  R = 0.8  →  90.0 %
  R = 1.0  →  85.0 %

This curve is NOT valid for a reflectance wrist
sensor without individual calibration. Report the
trend; do not report the absolute number as clinical.

Heart-rate variability (RMSSD)

plainHeart-rate variability (RMSSD)
Given successive RR intervals (ms) over a window:

  RMSSD = sqrt( (1/(N−1)) · Σ (RR[i+1] − RR[i])² )

Example: RR = [860, 902, 875, 918, 890] ms
  diffs   = [42, −27, 43, −28]
  squares = [1764, 729, 1849, 784]
  mean    = 5126 / 4 = 1281.5
  RMSSD   = 35.8 ms

Typical resting adult RMSSD: 20–90 ms.
Only compare a person against their own baseline —
between-individual variation is enormous.

Signal quality index

plainSignal quality index
SQI combines perfusion and rhythm regularity:

  perfusion  = AC_ir / DC_ir          (want > 0.005)
  regularity = 1 − (σ_RR / μ_RR)      (want > 0.85)
  motion     = 1 − min(1, σ_accel / 0.5)

  SQI = 0.4·min(1, perfusion/0.02) + 0.4·regularity + 0.2·motion

Suppress the displayed heart rate when SQI < 0.5.
A suppressed reading is honest; a confident wrong
one is not.

Program Flowchart

The firmware is a single cooperative loop. Nothing blocks for long, so networking, sensing and the user interface all stay responsive.

Heart-Rate & SpO2 Band — firmware flowchartControl flow through the main program loop. Boot: configure MAX30102registersRead FIFO on interrupt (100Hz)Remove DC, band-pass 0.5–4 HzWrist still (accelvariance low)?yesmark unreliableDetect peak above adaptivethresholdInterval within 300–2000ms?accept beatrejectUpdate HR, RMSSD and SpO₂Publish over BLE, log locally
Heart-Rate & SpO2 Band — firmware flowchart

Assembly Instructions

Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.

Step-by-Step Implementation Guide

Work through these in order. Each step ends in something you can observe, so a failure is always localised to the step you just finished.

Complete Source Code

The listing below is complete and compiles as written — there are no elided sections. Read the annotations under each block before you upload it.

cppppg-band.ino
/* ═══════════════════════════════════════════════════════════════
   Heart-Rate & SpO2 Band — ESP32 + MAX30102 + ADXL345

   The full PPG pipeline written out explicitly: FIFO read, DC removal,
   band-pass, adaptive peak detection with a refractory period, ratio-
   of-ratios SpO2, motion gating and a signal quality index.

   Not a medical device. Trends only.
   ══════════════════════════════════════════════════════════════════ */

#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_ADXL345_U.h>
#include <math.h>

#define MAX30102_ADDR 0x57
#define FS            100          // sample rate, Hz
#define BUF_LEN       500          // 5 s of history
#define REFRACTORY_MS 300          // 200 bpm ceiling
#define RR_HISTORY     32

Adafruit_SSD1306 oled(128, 64, &Wire, -1);
Adafruit_ADXL345_Unified accel(1);

/* ── raw and filtered buffers ───────────────────────────────── */
float irFilt[BUF_LEN], redFilt[BUF_LEN];
uint32_t irRaw[BUF_LEN], redRaw[BUF_LEN];
int bufIdx = 0;

float dcIr = 0, dcRed = 0;
float prevIrIn = 0, prevIrOut = 0, prevRedIn = 0, prevRedOut = 0;

uint32_t rrIntervals[RR_HISTORY];
uint8_t  rrCount = 0, rrHead = 0;
uint32_t lastBeatMs = 0;
float    heartRate = 0, spo2 = 0, sqi = 0, rmssd = 0;
float    accelVariance = 0;

/* ── MAX30102 register access ───────────────────────────────── */
void maxWrite(uint8_t reg, uint8_t val) {
  Wire.beginTransmission(MAX30102_ADDR);
  Wire.write(reg); Wire.write(val);
  Wire.endTransmission();
}

uint8_t maxRead(uint8_t reg) {
  Wire.beginTransmission(MAX30102_ADDR);
  Wire.write(reg);
  Wire.endTransmission(false);
  Wire.requestFrom(MAX30102_ADDR, 1);
  return Wire.read();
}

void maxBegin() {
  maxWrite(0x09, 0x40);            // reset
  delay(100);

  maxWrite(0x02, 0xC0);            // INT enable: A_FULL + PPG_RDY
  maxWrite(0x04, 0x00);            // FIFO write pointer
  maxWrite(0x05, 0x00);            // overflow counter
  maxWrite(0x06, 0x00);            // FIFO read pointer

  // FIFO config: sample averaging x4, rollover enabled, almost-full at 17
  maxWrite(0x08, (0x02 << 5) | (1 << 4) | 0x0F);

  maxWrite(0x09, 0x03);            // mode: SpO2 (red + IR)

  // SpO2 config: ADC range 4096 nA, 100 Hz, 411 us pulse width (18-bit)
  maxWrite(0x0A, (0x01 << 5) | (0x03 << 2) | 0x03);

  maxWrite(0x0C, 0x24);            // LED1 (red) current ~7 mA
  maxWrite(0x0D, 0x24);            // LED2 (IR)  current ~7 mA
}

// Reads one sample pair from the FIFO. Returns false when empty.
bool maxReadFifo(uint32_t &red, uint32_t &ir) {
  uint8_t wr = maxRead(0x04), rd = maxRead(0x06);
  if (wr == rd) return false;

  Wire.beginTransmission(MAX30102_ADDR);
  Wire.write(0x07);                          // FIFO data register
  Wire.endTransmission(false);
  Wire.requestFrom(MAX30102_ADDR, 6);
  if (Wire.available() < 6) return false;

  red = ((uint32_t)Wire.read() << 16) | ((uint32_t)Wire.read() << 8) | Wire.read();
  ir  = ((uint32_t)Wire.read() << 16) | ((uint32_t)Wire.read() << 8) | Wire.read();
  red &= 0x03FFFF;                           // 18-bit resolution
  ir  &= 0x03FFFF;
  return true;
}

/* ── filters ────────────────────────────────────────────────── */
// One-pole DC blocker: removes baseline with minimal phase distortion.
float dcBlock(float x, float &prevIn, float &prevOut, float alpha = 0.95f) {
  float y = x - prevIn + alpha * prevOut;
  prevIn = x; prevOut = y;
  return y;
}

// 4-point moving average low-pass, cheap and adequate at 100 Hz.
float lowPass(float x, float *hist) {
  hist[3] = hist[2]; hist[2] = hist[1]; hist[1] = hist[0]; hist[0] = x;
  return (hist[0] + hist[1] + hist[2] + hist[3]) * 0.25f;
}

/* ── peak detection ─────────────────────────────────────────── */
bool detectBeat(float sample, uint32_t nowMs) {
  static float runningMax = 0, threshold = 0;
  static float prev = 0, prevPrev = 0;
  static bool rising = false;

  runningMax = fmaxf(sample, runningMax * 0.999f);   // slow decay
  threshold = runningMax * 0.55f;

  bool isPeak = prev > threshold && prev > prevPrev && prev > sample && rising;
  rising = sample > prev;
  prevPrev = prev; prev = sample;
  if (!isPeak) return false;

  // Refractory period rejects the dicrotic notch — the single most
  // common cause of a heart rate that reads exactly double.
  if (nowMs - lastBeatMs < REFRACTORY_MS) return false;

  uint32_t rr = nowMs - lastBeatMs;
  lastBeatMs = nowMs;
  if (rr < 300 || rr > 2000) return false;           // 30–200 bpm plausible

  rrIntervals[rrHead] = rr;
  rrHead = (rrHead + 1) % RR_HISTORY;
  if (rrCount < RR_HISTORY) rrCount++;
  return true;
}

/* ── derived metrics ────────────────────────────────────────── */
void updateHeartRate() {
  if (rrCount < 5) { heartRate = 0; return; }

  // Median of the last 8 intervals: far more robust than a mean
  // when one interval is corrupted by a missed or extra beat.
  uint32_t recent[8];
  int n = rrCount < 8 ? rrCount : 8;
  for (int i = 0; i < n; i++)
    recent[i] = rrIntervals[(rrHead + RR_HISTORY - 1 - i) % RR_HISTORY];
  for (int i = 1; i < n; i++) {                      // insertion sort
    uint32_t k = recent[i]; int j = i - 1;
    while (j >= 0 && recent[j] > k) { recent[j + 1] = recent[j]; j--; }
    recent[j + 1] = k;
  }
  uint32_t med = recent[n / 2];
  heartRate = 60000.0f / med;
}

void updateRmssd() {
  if (rrCount < 10) { rmssd = 0; return; }
  double acc = 0; int n = 0;
  for (int i = 1; i < rrCount; i++) {
    int a = (rrHead + RR_HISTORY - i) % RR_HISTORY;
    int b = (rrHead + RR_HISTORY - i - 1) % RR_HISTORY;
    double d = (double)rrIntervals[a] - (double)rrIntervals[b];
    acc += d * d; n++;
  }
  rmssd = n ? sqrt(acc / n) : 0;
}

void updateSpo2() {
  // AC = peak-to-peak of the filtered signal, DC = mean of the raw.
  float irMin = 1e9, irMax = -1e9, redMin = 1e9, redMax = -1e9;
  double irDc = 0, redDc = 0;
  for (int i = 0; i < BUF_LEN; i++) {
    irMin = fminf(irMin, irFilt[i]);   irMax = fmaxf(irMax, irFilt[i]);
    redMin = fminf(redMin, redFilt[i]); redMax = fmaxf(redMax, redFilt[i]);
    irDc += irRaw[i]; redDc += redRaw[i];
  }
  irDc /= BUF_LEN; redDc /= BUF_LEN;
  if (irDc < 10000 || redDc < 10000) { spo2 = 0; sqi = 0; return; }  // no finger

  float acIr = irMax - irMin, acRed = redMax - redMin;
  float perfusion = acIr / (float)irDc;

  float R = (acRed / (float)redDc) / (acIr / (float)irDc);
  float est = 110.0f - 25.0f * R;
  spo2 = est < 70 ? 0 : (est > 100 ? 100 : est);

  // Quality: perfusion, rhythm regularity and stillness.
  float mean = 0, var = 0;
  for (int i = 0; i < rrCount; i++) mean += rrIntervals[i];
  if (rrCount) mean /= rrCount;
  for (int i = 0; i < rrCount; i++) {
    float d = rrIntervals[i] - mean; var += d * d;
  }
  float sd = rrCount ? sqrtf(var / rrCount) : 1e9;
  float regularity = mean > 0 ? 1.0f - fminf(1.0f, sd / mean) : 0;
  float motion = 1.0f - fminf(1.0f, accelVariance / 0.5f);

  sqi = 0.4f * fminf(1.0f, perfusion / 0.02f) + 0.4f * regularity + 0.2f * motion;
}

/* ── motion ─────────────────────────────────────────────────── */
void updateMotion() {
  static float hist[16]; static uint8_t h = 0;
  sensors_event_t e; accel.getEvent(&e);
  float mag = sqrtf(e.acceleration.x * e.acceleration.x +
                    e.acceleration.y * e.acceleration.y +
                    e.acceleration.z * e.acceleration.z);
  hist[h] = mag; h = (h + 1) % 16;

  float mean = 0; for (float v : hist) mean += v; mean /= 16;
  float var = 0;  for (float v : hist) { float d = v - mean; var += d * d; }
  accelVariance = sqrtf(var / 16);
}

/* ── setup / loop ───────────────────────────────────────────── */
void setup() {
  Serial.begin(115200);
  Wire.begin(21, 22);
  Wire.setClock(400000);                     // 100 kHz drops samples at 100 Hz

  oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  accel.begin(0x53);
  accel.setRange(ADXL345_RANGE_2_G);
  maxBegin();

  Serial.println("PPG band running — keep the wrist still for a clean reading");
}

void loop() {
  static float irLp[4] = {0}, redLp[4] = {0};
  uint32_t red, ir;

  while (maxReadFifo(red, ir)) {
    uint32_t now = millis();

    float irF  = lowPass(dcBlock((float)ir,  prevIrIn,  prevIrOut),  irLp);
    float redF = lowPass(dcBlock((float)red, prevRedIn, prevRedOut), redLp);

    irRaw[bufIdx] = ir;   redRaw[bufIdx] = red;
    irFilt[bufIdx] = irF; redFilt[bufIdx] = redF;
    bufIdx = (bufIdx + 1) % BUF_LEN;

    // Invert: more blood absorbs more light, so a beat is a DIP in
    // the raw signal and a peak once inverted.
    if (detectBeat(-irF, now)) {
      updateHeartRate();
      updateRmssd();
    }
  }

  static uint32_t lastSlow = 0;
  if (millis() - lastSlow < 250) return;
  lastSlow = millis();

  updateMotion();
  updateSpo2();

  bool reliable = sqi >= 0.5f && accelVariance < 0.5f && heartRate > 30;

  oled.clearDisplay();
  oled.setTextColor(SSD1306_WHITE);
  oled.setTextSize(3); oled.setCursor(0, 0);
  if (reliable) oled.printf("%3.0f", heartRate);
  else          oled.print("---");
  oled.setTextSize(1); oled.setCursor(64, 14); oled.print("bpm");

  oled.setCursor(0, 30);
  if (reliable && spo2 > 0) oled.printf("SpO2 %.0f%% (trend only)", spo2);
  else                      oled.print("SpO2 --");

  oled.setCursor(0, 42); oled.printf("HRV %.0f ms", rmssd);
  oled.setCursor(0, 54); oled.printf("SQI %.2f  %s", sqi,
                                     accelVariance > 0.5f ? "MOVING" : "still");
  oled.display();

  Serial.printf("HR %.0f  SpO2 %.0f  RMSSD %.0f  SQI %.2f  accel %.2f\n",
                heartRate, spo2, rmssd, sqi, accelVariance);
}
maxWrite(0x08, ...) sample averaging ×4The MAX30102 can average samples in hardware before they reach the FIFO. Averaging four samples at 400 Hz to give 100 Hz output improves SNR by 6 dB for free and reduces I²C traffic fourfold.
LED current 0x24 (~7 mA)Higher LED current gives more signal and more power draw and more skin heating. 7 mA is a good starting point for a wrist; a finger clip can use less, and dark or thick skin may need more. This is the parameter to tune first if the signal is weak.
detectBeat(-irF, ...)The sign inversion is not cosmetic. Increased blood volume absorbs more light, so a heartbeat is a downward deflection in the raw photodiode signal. Feeding the un-inverted signal to a peak detector finds the wrong features entirely.
REFRACTORY_MS = 300The dicrotic notch — the secondary bump from aortic valve closure — appears 200–300 ms after the main peak in every PPG waveform. Without a refractory period it is counted as a beat and the reported rate is exactly double, which is the classic symptom.
Median of 8 intervals, not meanOne missed beat doubles an interval and one spurious beat halves it. A mean is badly corrupted by either; a median is immune to up to three outliers in eight.
irDc < 10000 → no fingerA very low DC level means the sensor is not against skin. Reporting an SpO₂ derived from ambient light is worse than reporting nothing, so the whole computation is skipped.
reliable gate before displayThe display shows dashes rather than a number when quality is poor. This is the most important design decision in the whole project — a wearable that always shows a confident number teaches you to trust numbers that are sometimes wrong.

Configuration & Calibration

Configuration steps

  • Set the LED currents (registers 0x0C and 0x0D) for your skin and enclosure. Start at 0x24 and increase until the raw IR DC level sits between roughly 50 000 and 150 000 counts — too low is noisy, too high saturates the ADC.
  • Set I²C to 400 kHz. At 100 kHz the FIFO overflows at 100 Hz with two channels and you lose samples silently.
  • Tune the peak threshold fraction (0.55 of the running maximum). Lower catches weak pulses and admits noise; higher is robust and misses beats during low perfusion.
  • Set the motion gate threshold from your own accelerometer variance while sitting still versus walking. The 0.5 default is a starting point, not a universal value.
  • Leave the SpO₂ calibration constants alone unless you can validate against a reference oximeter, and label the output as a trend regardless.

Calibration procedure

An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.

  1. Set the operating point

    Watch the raw IR DC level with the band on. Adjust LED current until it sits in the middle of the ADC range. A saturated ADC produces a flat top on the waveform and destroys the AC measurement that everything depends on.

  2. Validate heart rate against a reference

    Compare against a chest strap or a manual pulse count over 60 seconds, at rest and after light exercise. Agreement within 3 bpm at rest is achievable; during movement expect worse, which is what the motion gate is for.

  3. Establish your own SpO₂ baseline

    Record your resting value over several sessions. It will probably not be 98 % — a reflectance wrist sensor with a generic curve is commonly off by several points. What matters is that a breath-hold produces a visible downward trend from your baseline.

  4. Check the strap tension effect

    Measure perfusion index at three strap tensions. Too loose admits light and loses signal; too tight restricts blood flow and also loses signal. There is a clear optimum and it is worth finding once.

Testing Procedure & Expected Output

Test from the bottom up. Confirm power, then each sensor in isolation, then the integrated loop — the first failing step tells you exactly where to look.

TestWhat you should see
Place the sensor on a fingertipRaw IR DC of 50 000–150 000 counts and a clearly periodic filtered waveform.
Read heart rate at restA stable figure within about 3 bpm of a manual count over 60 seconds.
Check for the doubling errorThe reported rate should not sit at exactly twice your pulse. If it does, the refractory period is not being applied.
Remove the sensor from skinDisplay shows dashes within a few seconds — not a stale or invented number.
Wave the wrist vigorouslySQI drops, "MOVING" appears, and the heart rate is suppressed rather than showing motion artefact.
Hold your breath for 45 secondsA visible downward SpO₂ trend of several points, recovering within a minute of resuming breathing.
Sit still for two minutes and read RMSSDA value between roughly 20 and 90 ms for a healthy adult at rest, repeatable across sessions.
Compare readings in bright sunlight and indoorsSimilar quality if the light seal is effective. A large degradation outdoors means ambient light is leaking in.

Bench-test checklist. If a row fails, stop and fix it before moving on.

Expected output

With everything wired and the firmware uploaded, the Serial Monitor at 115200 baud should look similar to the trace below. Values will differ; the shape of the output should not.

Troubleshooting: Common Errors & Fixes

Heart rate reads exactly double the real value

Likely cause. The dicrotic notch is being counted as a beat.

Fix. Enforce the 300 ms refractory period after each accepted beat, and raise the adaptive threshold fraction. The dicrotic notch is always smaller than the systolic peak, so a threshold at 55 % of the running maximum should exclude it.

The waveform is flat or barely moves

Likely cause. Sensor not in contact, LED current too low, or the ADC saturated.

Fix. Check the raw DC level. Near zero means no contact or the LEDs are off; near the 262 143 maximum means saturation. Adjust LED current until DC sits mid-range, and ensure the sensor face contacts skin with no gap.

The reading is fine indoors and useless outside

Likely cause. Ambient light, particularly sunlight, swamping the photodiode.

Fix. Fit an opaque skirt around the sensor and make the enclosure light-tight. This improves outdoor SNR more than any amount of filtering. The MAX30102 ambient-light cancellation helps but cannot overcome direct sunlight leaking around the sensor.

FIFO overflows and samples are lost

Likely cause. I²C too slow, or the loop is not reading the FIFO often enough.

Fix. Set the bus to 400 kHz and drain the FIFO in a while loop rather than reading one sample per iteration. Enable sample averaging in register 0x08 to reduce the sample rate reaching the FIFO.

SpO₂ reads 100 % constantly, or an implausible value

Likely cause. The AC amplitude is too small to measure reliably, or the DC estimate includes the filtered rather than the raw signal.

Fix. AC must come from the band-passed signal and DC from the raw signal — mixing them makes R meaningless. Also confirm perfusion index exceeds about 0.005; below that the ratio is dominated by noise.

Readings differ substantially between people

Likely cause. Skin tone, tissue thickness and perfusion all affect reflectance PPG.

Fix. This is a real and well-documented limitation, not a bug. Darker skin absorbs more at 660 nm, which reduces the red channel signal and biases R. Higher LED current helps; individual calibration helps more; and the honest answer is to report trends per person rather than absolute values across people.

The sketch will not upload — "Failed to connect" or "avrdude: stk500_recv()"

Likely cause. The bootloader is not being reached: wrong port, wrong board, a serial monitor holding the port open, or a USB cable that only carries power.

Fix. Close every serial monitor, confirm Tools → Board and Port, and swap to a known data-capable USB cable. On an ESP32 hold BOOT while the IDE prints "Connecting…", then release. If a peripheral is wired to the UART pins (GPIO 1/3 on ESP32, D0/D1 on Uno) unplug it — it fights the programmer.

The board resets in a loop, or the serial monitor prints "Brownout detector was triggered"

Likely cause. The supply cannot deliver peak current. Wi-Fi transmit bursts, relay coils and servos all pull far more than their average draw.

Fix. Power peripherals from a separate regulated supply with a common ground rather than from the board 5 V pin. Add a 470–1000 µF electrolytic capacitor across the supply near the load, and use a real power adapter rather than a laptop USB port.

Serial monitor shows garbage characters

Likely cause. Baud rate mismatch between Serial.begin() and the monitor, or a floating/shared UART line.

Fix. Set the monitor to 115200 to match the sketch. If it still garbles, the crystal or the USB bridge is being confused by noise — shorten the cable and keep motor wiring away from the USB lead.

An I²C device is not detected

Likely cause. Wrong address, missing pull-ups, swapped SDA/SCL, or a bus too long for the pull-up value.

Fix. Run an I²C scanner sketch first — it should print the device address. Most breakout boards include 4.7 kΩ pull-ups, but if you have chained four of them the parallel resistance is too low; remove the pull-ups from all but one board. Keep the bus under 30 cm at 100 kHz.

Performance Optimisation

  • Enable hardware sample averaging in the MAX30102 rather than averaging in firmware — it improves SNR before the ADC and costs no CPU.
  • Duty-cycle the LEDs for battery operation. They dominate consumption, and measuring for 15 seconds every minute gives a resting heart rate that is just as useful at a quarter of the power.
  • Use the interrupt pin rather than polling the FIFO pointers. Polling at 100 Hz over I²C wastes both bus bandwidth and CPU.
  • Replace every delay() with a millis() comparison — blocking delays are the single most common cause of dropped readings.
  • Sample sensors on a fixed cadence and publish on a slower one; you almost never need to transmit at the sampling rate.
  • Move networking into its own FreeRTOS task so a slow DNS lookup cannot stall the control loop.
  • Use uint8_t / uint16_t where the range allows; on an 8-bit AVR a 32-bit add costs four times as much.
  • For battery builds use deep sleep between samples: an ESP32 drops from ~160 mA awake to about 10 µA asleep, which is the difference between days and months of runtime.
  • Profile before optimising — print micros() deltas around each stage and fix the slowest one first.

Safety Precautions

  • This is not a medical device. Do not use it to diagnose anything or to make a treatment decision. If you have symptoms, see a doctor with a certified oximeter.
  • The SpO₂ figure in particular should never be treated as clinical. A reflectance wrist sensor with a generic calibration curve can be several percentage points off, and error increases exactly where it matters most — at low saturation.
  • Keep LED current modest. High-current LEDs against skin for hours cause local heating; the MAX30102 datasheet gives thermal limits and they exist for a reason.
  • Never sell or distribute a device like this as a health monitor. In most jurisdictions that requires regulatory clearance, and the requirement is there because uncalibrated devices have caused real harm.
  • Lithium cells vent and burn when abused. Only use protected cells or a proper BMS, never charge below 0 °C, and never leave a charging pack unattended on a wooden desk.
  • Wear eye protection when soldering or cutting, and solder in a ventilated space — rosin flux fumes are a respiratory irritant.
  • Power the circuit through a bench supply with a current limit while you are testing. A 300 mA limit turns a wiring mistake into a beep instead of a dead board.
  • Disconnect power before changing any wiring. Hot-plugging a sensor onto a live bus is the fastest way to lose a controller.

Maintenance

  • Re-check every screw terminal and header after the first week — thermal cycling loosens connections that felt tight on day one.
  • Log pack voltage. When resting voltage after a full charge drops below about 4.0 V, the cell is near end of life — replace it.
  • Recalibrate at the interval given in the calibration section, and keep the constants in a text file next to the firmware — not only in flash.
  • Keep a short logbook of firmware versions and what changed. Six months later you will not remember why that constant is 1.083.

Future Improvements & Upgrades

A working v1 is a platform, not a finish line. These are the upgrades that add the most capability for the least rework.

  • Add adaptive motion artefact cancellation using the accelerometer as a reference in an LMS adaptive filter, which recovers usable heart rate during walking rather than merely suppressing it.
  • Add a green LED channel (530 nm). Green penetrates less deeply and is far more motion-robust for heart rate, which is why every commercial wrist wearable uses it — red and IR are only needed for SpO₂.
  • Add respiratory rate extraction from the respiratory sinus arrhythmia modulation of the RR intervals, which needs no extra hardware.
  • Add proper BLE Heart Rate Service so any standard fitness app can consume the data.
  • Add per-user SpO₂ calibration against a reference oximeter across a small range, which materially improves the absolute figures for that individual.
  • Design a proper PCB. Once the breadboard version has run for a month, moving to a two-layer board removes the intermittent-contact failures that dominate prototype faults.
  • Add connectivity — an ESP32 and an MQTT publish turn a local gadget into something you can graph, alert on and analyse over months.
  • Add persistent local storage (microSD or the on-chip flash) so a network outage does not create a hole in your data.
  • Move configuration out of the source: a captive-portal setup page or a JSON config file makes the build reusable without a recompile.
  • Add a battery and solar option so the unit survives a power cut and can be sited away from a socket.
  • Write a small test harness that feeds synthetic sensor values through the decision logic, so you can validate thresholds without physically triggering the event.

Frequently Asked Questions

Why is my wrist reading so much worse than a fingertip?

Physics. The pulsatile fraction of the signal at a fingertip is typically 2–10 % of the DC level; at the wrist it is 0.5–2 %. There is simply less arterial blood volume change under a wrist sensor. That is why clinical oximeters clip to a finger and why wrist devices need far better signal processing to achieve worse accuracy.

Can I trust the SpO₂ number?

No, not as an absolute value. The ratio-of-ratios physics is sound, but the mapping from R to saturation must be calibrated empirically against arterial blood gas measurements in volunteers, which no hobby project can do. What you can trust is the direction: hold your breath and it will fall, which is genuinely useful for observing your own physiology.

Why does it read double sometimes?

The dicrotic notch. Every PPG waveform has a secondary bump 200–300 ms after the main peak, caused by the aortic valve closing and the pressure wave reflecting. Without a refractory period the peak detector counts it as a beat. The 300 ms guard in this code exists for exactly that reason.

Green, red or infrared LEDs?

Green (around 530 nm) for heart rate — it penetrates less deeply, is more strongly absorbed by haemoglobin, and is much less affected by motion. Red and infrared for SpO₂, because you need two wavelengths with different oxy/deoxy absorption ratios. Commercial wearables use green for continuous heart rate and switch on red and IR only for periodic SpO₂ spot checks.

Does skin tone affect accuracy?

Yes, measurably, and it is a serious and well-documented issue in the field. Higher melanin absorbs more light, particularly at shorter wavelengths, which reduces signal and biases the red/IR ratio. Studies have found clinically significant SpO₂ overestimation in patients with darker skin using commercial devices. Raising LED current and calibrating per individual both help; pretending the problem does not exist does not.

How much battery does it use?

The LEDs dominate: at 7 mA each running continuously in SpO₂ mode, plus the ESP32, expect 25–40 mA average, which is about a day from a 1000 mAh cell. Duty-cycling to 15 seconds per minute takes it to roughly four days without losing anything useful for resting-rate tracking.

References & Learning Resources

These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.

  1. MAX30102 high-sensitivity pulse oximeter and heart-rate sensor — datasheetAnalog Devices
  2. Allen, "Photoplethysmography and its application in clinical physiological measurement"Physiological Measurement, 2007
  3. Tamura et al., "Wearable Photoplethysmographic Sensors — Past and Present"Electronics, 2014
  4. Sjoding et al., "Racial Bias in Pulse Oximetry Measurement"New England Journal of Medicine, 2020
  5. Shaffer & Ginsberg, "An Overview of Heart Rate Variability Metrics and Norms"Frontiers in Public Health, 2017
  6. Elgendi, "On the Analysis of Fingertip Photoplethysmogram Signals"Current Cardiology Reviews, 2012
  7. FDA guidance on pulse oximeters for medical purposesUS FDA