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.
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
| Setting | How it is used |
|---|---|
| Resting heart-rate tracking | A daily resting figure taken under consistent conditions is one of the more genuinely informative fitness metrics. |
| Heart-rate variability for training load | Morning RMSSD trends track autonomic recovery reasonably well when measured consistently. |
| Sleep heart-rate patterns | Overnight is the ideal PPG condition — still wrist, stable temperature, hours of clean data. |
| Learning biomedical signal processing | PPG is the most accessible real physiological signal, and every technique here transfers to ECG and EEG work. |
| Altitude and breathing exercises | SpO₂ trends during breath-holds or at altitude are visible even with an uncalibrated sensor. |
| Prototyping for a certified device | Understanding 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
| Attribute | Value |
|---|---|
| Difficulty level | Advanced |
| Estimated completion time | 16–24 hours |
| Indicative build cost | ₹2,700 – ₹3,500 |
| Primary discipline | Health & Wearables |
| Reference platform | ESP32 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.
| Component | Key specification | Qty | Approx. 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 DAC | 1 | ₹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 temperature | 1 | ₹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 Hz | 1 | ₹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²C | 1 | ₹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 discharge | 1 | ₹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 protection | 1 | ₹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 grid | 1 | ₹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 lugs | 1 | ₹250 |
| Black opaque skirt / light seal Blocks ambient light leaking around the sensor. Improves SNR more than any firmware change. | Adhesive foam, 1 mm | 1 | ₹60 |
| 4.7 kΩ I²C pull-ups | 1 % metal film | 1 | ₹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
| Part | Specification | Supply | Interface | Reference |
|---|---|---|---|---|
| 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 DAC | 3.3 V logic / 5 V USB | UART, SPI, I²C, I²S, CAN, PWM | Datasheet |
| MAX30102 pulse oximeter + heart-rate sensor | Red 660 nm + IR 880 nm LEDs, 18-bit ADC, 50–3200 SPS, on-chip temperature | 1.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 Hz | 2.0–3.6 V | I²C / SPI | Datasheet |
| 0.96″ SSD1306 OLED display | 128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C | 3.3–5 V | I²C (0x3C) | Datasheet |
| 18650 Li-ion cell 3400 mAh + holder | 3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge | 3.0–4.2 V | Holder / spot-welded tabs | Datasheet |
| TP4056 Li-ion charger + DW01 protection | 1 A programmable CC/CV charge to 4.2 V ±1 %, over-discharge and short protection | 4.5–5.5 V in | micro-USB / pads | Datasheet |
| Double-sided perfboard 7 × 9 cm + headers | FR-4, 0.1″ pitch, plated through-holes, 24 × 18 grid | — | — | Datasheet |
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.
| Load | Supply rail | Typical current (mA) | Notes |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | 3.3 V logic / 5 V USB | 160 | Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly. |
| MAX30102 pulse oximeter + heart-rate sensor | 1.8 V + 3.3 V (module regulates) | 5.5 | Contact pressure dominates signal quality — a loose sensor gives a beautiful-looking, meaningless waveform. |
| ADXL345 3-axis accelerometer | 2.0–3.6 V | 0.14 | Built-in activity/free-fall interrupts let the MCU deep-sleep until something moves. |
| 0.96″ SSD1306 OLED display | 3.3–5 V | 20 | Static images burn in — invert or scroll the screen periodically. |
| TP4056 Li-ion charger + DW01 protection | 4.5–5.5 V in | 1000 | Buy 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.jsonunder 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
dialoutgroup:sudo usermod -aG dialout $USERand 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
| Library | Why it is needed | Install |
|---|---|---|
| WiFi (ESP32 core) bundled | Station/AP connection management for the ESP32. | Bundled with the ESP32 Arduino core |
| ArduinoJson 7.x | Zero-allocation JSON serialisation and parsing. | Library Manager → "ArduinoJson" by Benoit Blanchon |
| Adafruit SSD1306 + GFX 2.5.x | Framebuffer and text/graphics primitives for the OLED. | Library Manager → "Adafruit SSD1306" |
| Preferences (NVS) bundled | Wear-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.
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.
| Peripheral | Peripheral pin | Controller pin | Signal |
|---|---|---|---|
| MAX30102 | SDA / SCL | GPIO 21 / 22 | I²C at 0x57, 400 kHz |
| MAX30102 | INT | GPIO 27 | FIFO almost-full interrupt |
| ADXL345 | SDA / SCL | GPIO 21 / 22 | Shared I²C, 0x53 |
| Battery divider | Mid-point | GPIO 34 | 1 MΩ / 1 MΩ, MOSFET gated |
| SSD1306 OLED | SDA / SCL | GPIO 21 / 22 | Shared I²C, 0x3C |
| Vibration motor | MOSFET gate | GPIO 25 | Haptic feedback |
| Button | NO | GPIO 33 | Wake / 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.
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.
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
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₂
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)
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
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.
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.
/* ═══════════════════════════════════════════════════════════════
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);
}
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.
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.
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.
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.
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.
| Test | What you should see |
|---|---|
| Place the sensor on a fingertip | Raw IR DC of 50 000–150 000 counts and a clearly periodic filtered waveform. |
| Read heart rate at rest | A stable figure within about 3 bpm of a manual count over 60 seconds. |
| Check for the doubling error | The reported rate should not sit at exactly twice your pulse. If it does, the refractory period is not being applied. |
| Remove the sensor from skin | Display shows dashes within a few seconds — not a stale or invented number. |
| Wave the wrist vigorously | SQI drops, "MOVING" appears, and the heart rate is suppressed rather than showing motion artefact. |
| Hold your breath for 45 seconds | A visible downward SpO₂ trend of several points, recovering within a minute of resuming breathing. |
| Sit still for two minutes and read RMSSD | A value between roughly 20 and 90 ms for a healthy adult at rest, repeatable across sessions. |
| Compare readings in bright sunlight and indoors | Similar 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
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 amillis()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_twhere 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
References & Learning Resources
These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.
- MAX30102 high-sensitivity pulse oximeter and heart-rate sensor — datasheetAnalog Devices
- Allen, "Photoplethysmography and its application in clinical physiological measurement"Physiological Measurement, 2007
- Tamura et al., "Wearable Photoplethysmographic Sensors — Past and Present"Electronics, 2014
- Sjoding et al., "Racial Bias in Pulse Oximetry Measurement"New England Journal of Medicine, 2020
- Shaffer & Ginsberg, "An Overview of Heart Rate Variability Metrics and Norms"Frontiers in Public Health, 2017
- Elgendi, "On the Analysis of Fingertip Photoplethysmogram Signals"Current Cardiology Reviews, 2012
- FDA guidance on pulse oximeters for medical purposesUS FDA