Heart Rate, Respiration and Sleep Sensing
Heart Rate, Respiration and Sleep Sensing
Overview
Section titled “Overview”Non-imagery physiological sensing is where ODM projects most often over-promise: what can be measured, to what accuracy, and what may be claimed externally are three very different things. This section sets the deliverable boundary. By the end you will be able to:
- Distinguish the practical ceilings of PPG, ECG and respiration-by-motion/thermal routes
- Implement a heart-rate readout that is usable at rest, and define what “unusable” means
- Explain why SpO₂ and sleep staging cannot be promised from DIY parts
- Write the disclaimer and privacy sections into delivery documents, keeping risk inside the contract
Prerequisites
Section titled “Prerequisites”Before starting this section, make sure you:
- Completed Sections 3 and 10 of Chapter 25 (analogue filtering; presence detection)
- Have a MAX30102-class PPG module, or an AD8232 single-lead ECG front end
- Have a fingertip pulse-oximeter or fitness band for comparison (compare heart rate only, never oxygen accuracy)
Key Concepts
Section titled “Key Concepts”Three routes, three ceilings
Section titled “Three routes, three ceilings”| Target | Typical parts | What it can do | What it cannot |
|---|---|---|---|
| Heart rate | PPG (red + IR, reflective), ECG front end | Beat-to-beat bpm at rest, reliable trends | Basically unusable during motion without heavier fusion |
| SpO₂ | Dual-wavelength PPG | Requires manufacturer calibration curves and stable perfusion | DIY designs must not promise SpO₂ accuracy |
| Respiration rate | Chest-band impedance, thermal nasal airflow, mmWave micro-motion, microphone | Breaths per minute and trends | Sub-0.1 breath/min precision is meaningless |
| Sleep | Inference from motion + bed occupancy + respiration | In/away from bed, movement counts, coarse periods | Sleep staging belongs to medical-grade devices |
| Skin temperature | Single-point thermopile (see Section 11) | Surface temperature trends | Replacing a clinical thermometer |
One decision rule: for this class of product, say “trend and alert”, never “diagnosis or medical conclusion”. Before signing anything, establish whether the customer wants elderly-care event alerting (deliverable) or medical diagnosis (we do not do).
What actually makes PPG hard
Section titled “What actually makes PPG hard”MAX30102-class parts integrate LED drivers, a photodiode and a FIFO over I2C (commonly address 0x57). The difficulty is everything after the raw samples:
- Motion artefact: any wrist movement perturbs baseline and amplitude together; simple thresholds then produce nonsense. Consumer wearables solve this with multi-sensor fusion and heavy algorithms — not with one part and a moving average
- Pressure and placement: too tight restricts blood flow, too loose admits ambient light. Bony prominences and poorly perfused fingers give weak signals
- Ambient light crossthrough: daylight is rich in near-infrared and lifts the baseline. Shading is mandatory (light guide plus hood), and firmware should check for saturation and zero drift
- Perfusion differences: cold hands and low-perfusion users give weaker signals; the same algorithm behaves differently person to person
- Sample rate versus power: heart-rate estimation needs a stable 25–100 SPS; undersampling or FIFO overflow drops beats, while continuous high-rate sampling kills battery life. Products usually settle for on-demand plus periodic trend
The minimum viable heart-rate pipeline
Section titled “The minimum viable heart-rate pipeline”Do not start with peak detection. Establish signal quality first:
- Take the IR channel and remove the slow baseline (long moving average or first-order high-pass)
- Light smoothing (3–5 point moving average) preserving pulse contour
- Quality gate: is peak-to-peak within a plausible band, has it been unchanged for too long (finger removed), is it saturated?
- Only when quality passes, estimate the period (autocorrelation or the median of recent peak intervals) and report the quality metric alongside
The key delivery point: reporting “cannot measure” is far more valuable than reporting a plausible number. A payload without a quality field will draw a lying heart-rate curve on the dashboard.
Why SpO₂ cannot be promised
Section titled “Why SpO₂ cannot be promised”SpO₂ relies on the AC/DC ratio of red and IR channels during pulsation, mapped through curves calibrated on large human samples. Without a manufacturer calibration curve, with unstable perfusion and placement variation, DIY readings have no basis for credibility. The only acceptable wording is “dual-wavelength oxygen trend reference, not a medical measurement”, and no SpO₂ accuracy figure should appear in contract specs.
Respiration and sleep: the workable non-imagery combinations
Section titled “Respiration and sleep: the workable non-imagery combinations”- Respiration rate: thermal array reading cyclic nasal temperature differences (connects to Section 11), mmWave chest micro-motion (connects to Section 10), chest-band impedance is the most direct but requires wearing something. For bedrooms I prefer radar or thermal, since nothing must be worn
- In bed / out of bed: mmWave presence plus a time window; PIR alone will declare an immobile sleeper as absent
- Movement counts: radar distance gating or a pressure strip, reported as events
- Sleep periods: inferred from “in bed + steady breathing + few movements” — a statistical description, not sleep staging
- Highest-value alerts: for independent-living scenarios, “no movement for a long time” or “left bed and did not return” beats any sleep score, and is far easier to accept at sign-off
Disclaimers and privacy that must be documented
Section titled “Disclaimers and privacy that must be documented”- Disclaimer: this product/module is not a medical device and must not be used for diagnosis or treatment decisions; data are for reference and alerting only
- Accuracy statement: write “at rest, heart rate is comparable to consumer devices”, never un-calibrated figures
- Privacy: bedroom and body data are sensitive personal information — define retention period, on-device processing, access control and notification; EU-facing customers add GDPR obligations
- Wear safety: prolonged skin contact can cause irritation or pressure injury, which the enclosure design and manual must flag; battery and charging safety follow whole-unit certification
- Observable failure: detached sensor, poor signal, lost link must have explicit states rather than being plotted as “heart rate 0”
Implementation
Section titled “Implementation”PPG pipeline skeleton with quality gating
Section titled “PPG pipeline skeleton with quality gating”#include <Wire.h>
const uint8_t MAX30102_ADDR = 0x57; // confirm by bus scan
void samplePpg() { // Use a vendor driver library for FIFO and register setup; this is the logic skeleton only. // 1) Read N raw samples (N covers 25–100 SPS over roughly 2–4 s) // 2) Remove baseline: value - longTermAverage // 3) Smooth: movAvg(x, 3) // 4) Quality gate: // bool qualityOk = (peakToPeak > MIN_P2P) && (peakToPeak < MAX_P2P) // && !saturated && (stddev > MIN_STD) && (now - lastMotionMs > 2000); // 5) Estimate the period only if quality passes; take the median of the last 8 intervals // 6) Publish bpm together with quality, p2p and sampleRate}This deliberately stops short of a complete implementation: PPG libraries and register initialisation differ between boards, and shipping one “complete” copy would mislead readers whose module differs. Initialise with the library for your part, then implement the six steps above.
Respiration from a thermal array: nasal cyclic temperature difference
Section titled “Respiration from a thermal array: nasal cyclic temperature difference”// Average a few cells over the nose region per frame, then estimate periodicity over 10–30 sfloat regionMean(float *px, uint8_t y0, uint8_t y1, uint8_t x0, uint8_t x1) { float sum = 0; uint8_t n = 0; for (uint8_t y = y0; y < y1; y++) for (uint8_t x = x0; x < x1; x++) { sum += px[y * 8 + x]; n++; } return n ? sum / n : NAN;}
// Key point: breathing produces only about 0.1–0.5 °C of cyclic variation — first verify// that the device's own noise floor can resolve it0.1–0.5 °C is a rule-of-thumb range, dependent on distance, target area and airflow. Capture a static sequence yourself to check the noise floor before committing to the approach — do not rely on second-hand conclusions.
Events, states and freshness
Section titled “Events, states and freshness”struct VitalSample { float bpm; uint8_t quality; // 0 = invalid, 1..255 signal quality float respRate; bool inBed; unsigned long ageMs; // data freshness; beyond threshold treat as sensor detached};
bool usable(const VitalSample &s) { return s.quality > 40 && !isnan(s.bpm) && millis() - s.ageMs < 15000;}Making quality and ageMs mandatory fields is the single most effective way to stop dashboards from lying.
Verification
Section titled “Verification”| Check | Expected result | Verified |
|---|---|---|
| 60 s at rest, against a fingertip oximeter | Stable difference (record the band; do not promise accuracy) | |
| Slight wrist movement / walking | Quality metric drops and the algorithm reports “unusable” instead of a wild number | |
| Before and after fitting the light hood | Baseline and noise improve measurably (by a window) | |
| Finger removed from the sensing area | Rapidly enters the invalid state instead of holding the last reading | |
| Cold hand vs warm hand | Record amplitude difference as a usage condition | |
| 30 min continuous wear | No systematic drift, no accumulating missed-beat error | |
| Respiration: 2 min supine vs stopwatch | Correct trend direction with an acceptable, measured error band | |
| Bed occupancy: empty vs stationary person | No false “in bed”; out-of-bed latency quantified |
One item to log separately: any case where an “invalid” reading was displayed as a valid number belongs in the defect list. In this product class it is the most serious failure mode.
Troubleshooting
Section titled “Troubleshooting”Issue 1: heart rate jumps wildly
Section titled “Issue 1: heart rate jumps wildly”Possible causes: motion artefact, loose wear leaking light, ambient light lifting the baseline, FIFO overflow losing samples, insufficient sample rate.
Solutions:
- Look at the quality metrics first, not at the algorithm: print
p2p,stddev, saturation flags to localise the cause - Add a shading structure and fix the wearing position (light guide, or a moulded finger sleeve / holder)
- Drive reads from the device interrupt (some parts expose FIFO-watermark interrupts) instead of polling too slowly
- Discard implausible values outright rather than smoothing them in
Issue 2: the device is not found on I2C
Section titled “Issue 2: the device is not found on I2C”Possible causes: address differs from the library default (0x57 is common, boards vary), a longer power-on initialisation than assumed, SDA/SCL swapped, pull-up or bus conflicts.
Solutions:
- Scan the bus, then set the code address
- Add a delay after power-on and retry initialisation three times
- Check whether the board carries level circuitry (some 5 V modules still work on a 3.3 V bus; the reverse needs threshold checking)
Issue 3: oxygen reading differs a lot from a medical device
Section titled “Issue 3: oxygen reading differs a lot from a medical device”Cause: missing manufacturer calibration curves, poor perfusion, placement and pressure differences — a principle limit, not a bug.
Solutions:
- Do not commit to SpO₂ accuracy externally; publish trend only. If the contract requires oxygen accuracy, use a certified finished module and whole-unit certification
- Fix the measurement conditions (same finger, seated, room temperature, shaded) and put those conditions in the manual
- Grade data credibility from dual-wavelength waveform quality and drop low-quality samples
Issue 4: whole night of missing data
Section titled “Issue 4: whole night of missing data”Possible causes: Wi-Fi disconnect, sampling disabled under a sleep policy, part misbehaving at low temperature, blocked upload queue.
Solutions:
- Local buffering with replay after reconnection, with an explicit capacity and overwrite policy
- Verify the sleep strategy is not switching acquisition off
- Give the upload queue overflow protection and a dropped-record counter; never fail silently
Best Practices
Section titled “Best Practices”- Do: design invalid states as first-class citizens — quality, freshness, out-of-bed, detached must all be expressible
- Do: standardise wording on “trend and alert”; publish only measured deviation bands, never datasheet marketing numbers
- Do: for bedroom and elder-care scenarios prefer non-imagery (radar/thermal) and treat privacy as a design constraint, not an afterthought
- Do: process data on-device where possible and upload the minimum, with retention period and access rights in the delivery documents
- Don’t: put DIY PPG oxygen values into contract specifications
- Don’t: claim sleep staging (deep/REM) — that requires medical-grade devices and validation
- Don’t: keep reporting the previous heart rate as current when there is no quality basis
Summary
Section titled “Summary”Key points of this section:
- Three routes, three ceilings: heart rate at rest is achievable; SpO₂ and sleep staging are not promiseable
- PPG difficulty lives after the raw signal: motion, wear, light leaks, perfusion — gate on quality before computing
- Non-imagery combinations are the stable choice for respiration and occupancy: radar for in/out of bed, thermal or radar for breathing trend, distance gating for movement
- Quality and freshness fields are mandatory, otherwise dashboards lie
- Disclaimers and privacy belong in the contract and manual as deliverables, not appendices
Next section: actuator selection and driving — servos, DC and stepper motors, solenoids, and their supply, run-away protection and power-on default states.
We provide ESP32 ODM design-to-manufacturing services. From prototype to production — the team behind this tutorial can build it with you.
💡 Mention tutorial.imagrove.com in your Alibaba chat with us — get 10% off your custom project quote.
First published attutorial.imagrove.com/sensor-module-selection/12-heart-rate-respiration-and-sleep-sensing/Please credit Imagrove and link back to this page when quoting or republishing.
Questions or issues with this tutorial?
Sign in with GitHub to leave a comment. If a step fails for you, tell us — we verify it and update the tutorial.
© Imagrove · ESP32 IoT Tutorial