Siddhant Kumar
Project 024 · Health & Wearables

Blood Pressure Logger.

An oscillometric cuff monitor that inflates, bleeds down under control, extracts systolic and diastolic pressure from the pulse envelope, and logs a trend — with a frank account of why home BP measurement is so easily done wrong.

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

Project Overview

An oscillometric cuff monitor that inflates, bleeds down under control, extracts systolic and diastolic pressure from the pulse envelope, and logs a trend — with a frank account of why home BP measurement is so easily done wrong.

Blood pressure is the most measured and most misinterpreted vital sign in medicine. The measurement itself is subtle, and the conditions under which it is taken matter as much as the device — a correctly working monitor used on a talking, cross-legged patient with a full bladder produces a number that is simply wrong. This project builds the measurement honestly and spends as much effort on how to take a reading correctly as on the electronics.

The method is oscillometry, which is what every automatic home monitor uses. A cuff is inflated above systolic pressure to occlude the artery, then bled down slowly. As the cuff pressure passes through the arterial pressure range, each heartbeat produces a small oscillation in the cuff pressure — the artery pulsing against the cuff. These oscillations grow, peak, and shrink as the cuff deflates, and the shape of that oscillation envelope encodes the blood pressure. The mean arterial pressure is the cuff pressure at maximum oscillation; systolic and diastolic are derived from characteristic ratios of that maximum.

The build combines a pressure sensor, a small pump and a bleed valve under closed-loop control. The control is the interesting part: the deflation must be slow and smooth (2–3 mmHg per second) for the envelope to be well-sampled, which means the bleed valve is modulated rather than simply opened. Too fast and the reading is inaccurate; too slow and the cuff is uncomfortable and venous congestion distorts the result.

The honest framing here is about the derivation. Oscillometry does not measure systolic and diastolic directly — it measures the envelope and infers them using empirical ratios (typically ~0.55 of peak for systolic, ~0.85 for diastolic). Those ratios are population averages baked into every home monitor, and they are why home devices and a clinician's manual auscultation sometimes disagree. This documentation explains that rather than pretending the numbers are direct measurements.

What this project does

  • Inflates a standard BP cuff with a pump to above systolic pressure.
  • Bleeds down under closed-loop control at a steady 2–3 mmHg/s.
  • Extracts the oscillation envelope from the cuff pressure signal.
  • Computes mean arterial pressure, systolic and diastolic from the envelope.
  • Reports heart rate from the oscillation timing.
  • Logs readings with a timestamp and guides correct measurement technique.
  • Includes a fast-dump safety valve and a hard pressure ceiling.

Real-World Applications

SettingHow it is used
Home hypertension trackingHome readings, averaged correctly, are more predictive than isolated clinic readings — when taken properly.
White-coat and masked hypertensionComparing home and clinic readings reveals both, which changes management.
Medication responseA trend across a medication change shows whether it is working, which a single reading cannot.
Learning biomedical instrumentationClosed-loop pneumatic control plus envelope analysis is a rich, real engineering problem.
Research and validation studiesA platform for oscillometric algorithm development against a reference.
TelehealthLogged, timestamped home readings a clinician can review remotely.

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

Features & Capabilities

  • Oscillometric measurement — the same principle as every automatic home monitor.
  • Closed-loop deflation control for a steady bleed rate, which the accuracy depends on.
  • Envelope extraction with band-pass filtering of the cuff pressure signal.
  • Empirical ratio derivation of systolic and diastolic, with the ratios documented, not hidden.
  • Hard safety ceiling (300 mmHg) and a fast-dump valve that vents on any fault.
  • Measurement-technique guidance in the interface, because technique dominates accuracy.
  • Trend logging with morning/evening averaging as clinical guidelines specify.
  • Artefact rejection — movement and talking corrupt the envelope and are flagged.

Difficulty, Time & Required Skills

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

Skills you should have (or will pick up)

  • Arduino C++ with closed-loop control and state machines
  • Pressure sensor interfacing and calibration
  • Pump and valve control through drivers
  • Signal processing: envelope extraction, peak finding
  • A careful understanding of measurement technique and its dominance over device accuracy

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
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
LM2596 adjustable buck converter module
Set the output voltage with no load connected before wiring the board.
4.5–40 V in, 1.25–37 V out, 2 A (3 A peak), ~92 % efficiency1₹90
5 V 3 A regulated SMPS adapter
Measure the real output — many "3 A" adapters sag below 4.7 V at 2 A.
100–240 VAC in, 5 V ±5 % out, 3 A, short-circuit and over-voltage protection1₹350
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
IP65 ABS junction enclosure 158 × 90 × 60 mm
Fit cable glands, not drilled holes, or the IP rating means nothing.
IP65, ABS, −20 to +80 °C, transparent lid, wall-mount lugs1₹260
MPS20N0040D / MPX5050 pressure sensor
The sensor must cover 0–300 mmHg with resolution better than 1 mmHg for good envelope extraction.
0–40 kPa (0–300 mmHg), analogue or with HX710 amp1₹320
Air pump (diaphragm) + solenoid bleed valve
The bleed valve is modulated for controlled deflation, so a fast-responding small valve matters.
5–12 V pump, small NC solenoid valve1₹480
Fast-dump solenoid valve (safety)
A separate large valve that dumps pressure fast on any fault — a hard safety requirement.
Large-orifice NC, vents the cuff quickly1₹260
Standard BP cuff + tubing + T-connectors
Cuff size is a major accuracy factor — too small over-reads, too large under-reads.
Adult cuff, correct size for the arm1₹380
Dual MOSFET driver + flyback diodesFor pump and valves1₹80

Estimated total: ₹2,980, 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
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
LM2596 adjustable buck converter module4.5–40 V in, 1.25–37 V out, 2 A (3 A peak), ~92 % efficiency4.5–40 VScrew terminals + trimmerDatasheet
5 V 3 A regulated SMPS adapter100–240 VAC in, 5 V ±5 % out, 3 A, short-circuit and over-voltage protection5 VDC barrel / USBDatasheet
Double-sided perfboard 7 × 9 cm + headersFR-4, 0.1″ pitch, plated through-holes, 24 × 18 gridDatasheet
IP65 ABS junction enclosure 158 × 90 × 60 mmIP65, ABS, −20 to +80 °C, transparent lid, wall-mount lugsDatasheet

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.
0.96″ SSD1306 OLED display3.3–5 V20Static images burn in — invert or scroll the screen periodically.
LM2596 adjustable buck converter module4.5–40 V8Set the output voltage with no load connected before wiring the board.
5 V 3 A regulated SMPS adapter5 V3000Measure the real output — many "3 A" adapters sag below 4.7 V at 2 A.

Summed typical draw is 3188 mA. With a 1.5× design margin the supply should deliver at least 4800 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
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.

Blood Pressure Logger — system block diagramFunctional block diagram of the Blood Pressure Logger system. PneumaticsPumpinflateBleed valvecontrolled deflateDump valvesafety ventSensePressure sensor0–300 mmHgDC + oscillationsplit by filterAnalyseEnvelopeper-beat amplitudeMAP at peakthen ratiosReportReading + HRlogTechnique guidein UIcuff pressuresignalSYS/DIA/MAP
Blood Pressure Logger — 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.

Blood Pressure Logger — wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBPressure sensorGPIO 34 or 16/4Analogue or HX71024-bitStart buttonGPIO 32Begin a measurementSSD1306 OLEDGPIO 21 / 22I²C at 0x3CAir pumpGPIO 25Inflate, withflyback diodeBleed valve (modulated)GPIO 26PWM for controlleddeflationFast-dump valve (safety)GPIO 27Vents on any fault
Blood Pressure Logger — wiring schematic
PeripheralPeripheral pinController pinSignal
Pressure sensorOUT / DT+SCKGPIO 34 or 16/4Analogue or HX710 24-bit
Start buttonNOGPIO 32Begin a measurement
SSD1306 OLEDSDA / SCLGPIO 21 / 22I²C at 0x3C
Air pumpMOSFET gateGPIO 25Inflate, with flyback diode
Bleed valve (modulated)MOSFET gateGPIO 26PWM for controlled deflation
Fast-dump valve (safety)MOSFET gateGPIO 27Vents on any fault

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 pneumatic circuit is: pump → cuff, with the bleed valve and the fast-dump valve both venting the cuff to atmosphere, and the pressure sensor teed into the cuff line. Use proper barbed T-connectors and check every joint for leaks — a leak makes controlled deflation impossible.
  • The fast-dump valve is a safety requirement, not an option. It is a separate, large-orifice, normally-closed solenoid wired so that losing power (or the firmware asserting a fault) opens it and vents the cuff immediately. A cuff stuck inflated on an arm is dangerous.
  • Wire both valves normally-closed and the pump off-by-default, so a power failure or a crashed microcontroller results in a deflated, safe cuff — never an inflated one.
  • Calibrate the pressure sensor against a reference. The absolute accuracy of the whole device is limited by this calibration, and a 3 mmHg offset here is a 3 mmHg error in every reading.
  • Fit flyback diodes across the pump and both solenoids — they are all inductive and will damage the MOSFETs without them.
  • Use the correct cuff size for the arm. This is not an electronics issue but it dominates accuracy: a cuff too small over-reads by 10–40 mmHg, one too large under-reads.
An ESP32 development board with the ESP-WROOM-32 module and USB connector
An ESP32 development board running the closed-loop pneumatic control and the envelope analysis. Photograph sourced from Wikimedia Commons — ESP32 Espressif ESP-WROOM-32 Dev Board.jpg. 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.

Blood Pressure Logger — architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) · sensors and actuatorsDriver layerarduinojson · ssd1306 · preferencesApplication logicsampling loop · filtering · thresholds · state machinePresentation layerlocal display · serial console · logged output
Blood Pressure Logger — architecture stack

Working Principle

When a cuff is inflated above systolic pressure, it fully occludes the brachial artery and no blood flows past it — there are no pulsations. As the cuff bleeds down and its pressure falls below systolic, the artery begins to open briefly at each systolic peak, and blood spurts through, causing the artery wall to snap against the cuff. This produces a small pressure oscillation in the cuff, superimposed on the slowly falling cuff pressure. As deflation continues, the oscillations grow — the artery opens for more of each cycle — reach a maximum, then shrink as the cuff pressure falls below diastolic and the artery stays open throughout the cycle.

The genius and the limitation of oscillometry is in what happens at the maximum. The oscillations are largest when the cuff pressure equals the mean arterial pressure — this is a well-established physical result, because that is when the artery's compliance (its change in volume per unit pressure) is greatest. So the mean arterial pressure (MAP) is read directly and robustly: it is the cuff pressure at the peak of the oscillation envelope. This is the one value oscillometry measures rather than infers.

Systolic and diastolic are not directly measured — they are inferred from the envelope shape using empirical ratios. Systolic corresponds to the cuff pressure, on the rising side of the envelope, where the oscillation amplitude is about 55 % of its peak; diastolic to the point on the falling side at about 85 % of peak. These ratios are population-derived averages, and they are the reason different oscillometric devices — and oscillometry versus a clinician's stethoscope — can give slightly different systolic and diastolic while agreeing closely on MAP.

Extracting the envelope requires separating the small oscillations from the large falling cuff pressure. The cuff pressure signal is the sum of a slow ramp (the deflation, effectively DC and very-low-frequency) and the oscillations (at the heart rate, roughly 1 Hz). A band-pass filter around the heart rate isolates the oscillations, and the peak-to-peak amplitude of each beat's oscillation, plotted against the cuff pressure at that moment, is the envelope.

The deflation control is critical to accuracy. The envelope must be sampled finely enough to locate its peak and the systolic/diastolic points, which requires a slow, steady deflation — 2–3 mmHg per second is the standard. Too fast and there are too few beats to define the envelope; too slow and the measurement takes uncomfortably long and venous pooling below the cuff distorts the later oscillations. A simple open valve deflates non-linearly (faster at high pressure); a modulated valve under closed-loop control maintains a constant rate, which is why the bleed valve is PWM-driven against a measured deflation-rate setpoint.

Above all, measurement technique dominates device accuracy. Correct oscillometry on a patient who is talking, has legs crossed, has a full bladder, has just had caffeine, or has the cuff over clothing can be off by 10–20 mmHg — far more than any reasonable device error. This is why the device leads with technique guidance and why clinical protocols specify five minutes of quiet rest, feet flat, back supported, arm at heart level, and the average of multiple readings.

The maths behind it

Oscillometric envelope and MAP

plainOscillometric envelope and MAP
Cuff pressure P(t) = P_deflate(t) + osc(t)
  P_deflate : slow ramp, ~2–3 mmHg/s downward
  osc(t)    : ~1 Hz oscillations, amplitude a few mmHg

Envelope: for each beat, A_k = peak-to-peak of osc during
that beat, at cuff pressure P_k.

Mean arterial pressure:
  MAP = P_k at which A_k is MAXIMUM   (measured directly)

MAP relates to SYS and DIA approximately by:
  MAP ≈ DIA + (SYS − DIA)/3
(a cross-check, not the derivation used here)

Systolic and diastolic by ratio

plainSystolic and diastolic by ratio
Let A_max be the peak envelope amplitude.

Systolic (rising side of envelope):
  SYS = cuff pressure where A = 0.55·A_max

Diastolic (falling side of envelope):
  DIA = cuff pressure where A = 0.85·A_max

These ratios (0.55, 0.85) are population averages used
by home monitors. They are why oscillometric SYS/DIA
can differ from auscultation while MAP agrees closely.

Example envelope peak at cuff = 95 mmHg (= MAP):
  0.55·A_max crossing on rising side  → SYS ≈ 128
  0.85·A_max crossing on falling side → DIA ≈ 82

Deflation rate control

plainDeflation rate control
Target deflation rate: R = 2.5 mmHg/s

Measured rate over the last second:
  r = (P[t−1s] − P[t]) mmHg/s

Bleed valve duty (PWM), simple proportional control:
  duty += Kp·(R − r)
  duty = clamp(duty, 0, 255)

An open valve deflates ~exponentially (faster when the
cuff is hard), so a fixed opening gives a non-constant
rate. Modulating the valve holds R constant across the
whole deflation, which the envelope analysis needs.

Program Flowchart

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

Blood Pressure Logger — firmware flowchartControl flow through the main program loop. Show technique guidance, waitfor startPump up to ~30 mmHg aboveexpected systolicPressure over safetyceiling (300)?DUMP, abortproceedBleed down at 2–3 mmHg/s(closed loop)Record cuff pressure +oscillation per beatDeflation complete (below~40 mmHg)?analysekeep bleedingFind MAP at envelope peak,derive SYS/DIADump remaining pressure, show+ log result
Blood Pressure Logger — 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.

cppbp-monitor.ino
/* ═══════════════════════════════════════════════════════════════
   Blood Pressure Logger — ESP32, oscillometric

   Inflates a cuff, bleeds down under closed-loop rate control,
   extracts the oscillation envelope, and derives systolic, diastolic
   and mean arterial pressure. Includes a hard safety ceiling and a
   fast-dump valve.

   NOT a validated clinical device. Technique dominates accuracy; see
   the guidance shown before each measurement.
   ══════════════════════════════════════════════════════════════════ */

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

#define PIN_PRESSURE 34
#define PIN_START    32
#define PIN_PUMP     25
#define PIN_BLEED    26          // modulated for controlled deflation
#define PIN_DUMP     27          // fast safety vent

#define SAFETY_CEIL_MMHG 300     // hard limit — dump above this
#define INFLATE_TARGET   170     // above expected systolic
#define DEFLATE_RATE      2.5f   // mmHg/s
#define STOP_MMHG         40     // stop below this
#define MAX_BEATS        200

Adafruit_SSD1306 oled(128, 64, &Wire, -1);
Preferences prefs;

// Sensor calibration: pressure = (adc - offset) * scale
float calOffset = 410.0f, calScale = 0.0732f;   // set by calibration

struct Beat { float cuffP; float amplitude; };
Beat beats[MAX_BEATS];
int  beatCount = 0;

/* ── pressure ───────────────────────────────────────────────── */
float readPressure() {
  uint32_t acc = 0;
  for (int i = 0; i < 4; i++) acc += analogRead(PIN_PRESSURE);
  return (acc / 4.0f - calOffset) * calScale;      // mmHg
}

/* ── safety ─────────────────────────────────────────────────── */
void dumpAll() {
  digitalWrite(PIN_PUMP, LOW);
  digitalWrite(PIN_BLEED, HIGH);       // full open
  digitalWrite(PIN_DUMP, HIGH);        // fast vent
}

void safeIdle() {
  digitalWrite(PIN_PUMP, LOW);
  analogWrite(PIN_BLEED, 0);
  digitalWrite(PIN_DUMP, LOW);         // valves closed, cuff at atmosphere
}

bool checkSafety() {
  if (readPressure() > SAFETY_CEIL_MMHG) { dumpAll(); return false; }
  return true;
}

/* ── the measurement ────────────────────────────────────────── */
void inflate() {
  digitalWrite(PIN_DUMP, LOW);
  analogWrite(PIN_BLEED, 0);           // bleed closed
  digitalWrite(PIN_PUMP, HIGH);
  uint32_t t0 = millis();
  while (readPressure() < INFLATE_TARGET) {
    if (!checkSafety()) return;
    if (millis() - t0 > 30000) { dumpAll(); return; }   // inflation timeout
    oled.clearDisplay(); oled.setTextColor(SSD1306_WHITE);
    oled.setTextSize(2); oled.setCursor(0, 20);
    oled.printf("%3.0f mmHg", readPressure());
    oled.setTextSize(1); oled.setCursor(0, 4); oled.print("Inflating - hold still");
    oled.display();
  }
  digitalWrite(PIN_PUMP, LOW);
}

void deflateAndSample() {
  beatCount = 0;
  float bleedDuty = 120;               // starting valve opening
  float lastP = readPressure();
  uint32_t lastRateT = millis();

  // Beat-band oscillation extraction: high-pass the pressure to remove
  // the deflation ramp, then track per-beat peak-to-peak.
  float hpPrev = 0, hpPrevIn = 0;
  float oscMin = 1e9, oscMax = -1e9;
  uint32_t lastZero = millis();

  while (readPressure() > STOP_MMHG) {
    if (!checkSafety()) return;

    float p = readPressure();

    // Closed-loop deflation rate control.
    if (millis() - lastRateT >= 200) {
      float rate = (lastP - p) / ((millis() - lastRateT) / 1000.0f);
      bleedDuty += 8.0f * (DEFLATE_RATE - rate);       // proportional
      bleedDuty = fmaxf(20, fminf(220, bleedDuty));
      analogWrite(PIN_BLEED, (int)bleedDuty);
      lastP = p; lastRateT = millis();
    }

    // High-pass (removes the slow deflation ramp, keeps oscillations).
    float hp = 0.98f * (hpPrev + p - hpPrevIn);
    hpPrevIn = p; hpPrev = hp;

    oscMin = fminf(oscMin, hp); oscMax = fmaxf(oscMax, hp);

    // Detect a beat as a downward zero crossing of the oscillation.
    static float prevHp = 0;
    if (prevHp > 0 && hp <= 0 && millis() - lastZero > 300) {
      lastZero = millis();
      if (beatCount < MAX_BEATS) {
        beats[beatCount].cuffP = p;
        beats[beatCount].amplitude = oscMax - oscMin;
        beatCount++;
      }
      oscMin = 1e9; oscMax = -1e9;
    }
    prevHp = hp;

    oled.clearDisplay(); oled.setTextColor(SSD1306_WHITE);
    oled.setTextSize(2); oled.setCursor(0, 20); oled.printf("%3.0f", p);
    oled.setTextSize(1); oled.setCursor(0, 4); oled.print("Measuring - stay still");
    oled.setCursor(0, 50); oled.printf("beats: %d", beatCount);
    oled.display();
    delay(5);
  }
  dumpAll(); delay(1500); safeIdle();
}

/* ── envelope analysis ──────────────────────────────────────── */
bool analyse(float &sys, float &dia, float &map, float &hr) {
  if (beatCount < 8) return false;

  // Find the envelope peak (= MAP).
  int peakIdx = 0; float peakAmp = 0;
  for (int i = 0; i < beatCount; i++)
    if (beats[i].amplitude > peakAmp) { peakAmp = beats[i].amplitude; peakIdx = i; }
  map = beats[peakIdx].cuffP;

  // Systolic: rising side (higher cuff pressure, earlier), 0.55 of peak.
  sys = map;
  for (int i = peakIdx; i >= 0; i--)
    if (beats[i].amplitude <= 0.55f * peakAmp) { sys = beats[i].cuffP; break; }

  // Diastolic: falling side (lower cuff pressure, later), 0.85 of peak.
  dia = map;
  for (int i = peakIdx; i < beatCount; i++)
    if (beats[i].amplitude <= 0.85f * peakAmp) { dia = beats[i].cuffP; break; }

  // Heart rate from the mean beat interval during the measurement.
  // (Beats span the deflation; count them over its duration.)
  hr = 0;    // computed from timestamps in a fuller implementation

  // Plausibility gate — reject nonsense from a corrupted envelope.
  if (sys < 70 || sys > 260 || dia < 40 || dia > 150 || sys <= dia) return false;
  return true;
}

/* ── setup / loop ───────────────────────────────────────────── */
void showGuidance() {
  const char *lines[] = {
    "Before measuring:", "- rest 5 min, seated",
    "- back supported,", "  feet flat, legs", "  uncrossed",
    "- arm at heart level", "- do not talk or move",
    "- correct cuff size", "Press START when ready" };
  oled.clearDisplay(); oled.setTextColor(SSD1306_WHITE); oled.setTextSize(1);
  for (int i = 0; i < 9; i++) { oled.setCursor(0, i * 7); oled.print(lines[i]); }
  oled.display();
}

void setup() {
  Serial.begin(115200);
  pinMode(PIN_START, INPUT_PULLUP);
  pinMode(PIN_PUMP, OUTPUT);
  pinMode(PIN_BLEED, OUTPUT);
  pinMode(PIN_DUMP, OUTPUT);
  analogSetPinAttenuation(PIN_PRESSURE, ADC_11db);
  safeIdle();

  Wire.begin(21, 22);
  oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  prefs.begin("bp", false);
  calOffset = prefs.getFloat("off", 410.0f);
  calScale  = prefs.getFloat("scl", 0.0732f);

  showGuidance();
  Serial.println("BP monitor — NOT a validated clinical device");
}

void loop() {
  showGuidance();
  if (digitalRead(PIN_START) != LOW) { delay(50); return; }
  delay(200);

  inflate();
  if (readPressure() > SAFETY_CEIL_MMHG - 10) { dumpAll(); delay(2000); safeIdle(); return; }
  deflateAndSample();

  float sys, dia, map, hr;
  oled.clearDisplay(); oled.setTextColor(SSD1306_WHITE);
  if (analyse(sys, dia, map, hr)) {
    oled.setTextSize(3); oled.setCursor(0, 0); oled.printf("%3.0f", sys);
    oled.setTextSize(2); oled.setCursor(78, 8); oled.printf("/%2.0f", dia);
    oled.setTextSize(1); oled.setCursor(0, 34); oled.printf("MAP %.0f mmHg", map);
    oled.setCursor(0, 46); oled.print("Average 2-3 readings");
    oled.setCursor(0, 56); oled.print("Not a diagnosis");
    Serial.printf("SYS %.0f  DIA %.0f  MAP %.0f\n", sys, dia, map);
  } else {
    oled.setTextSize(1); oled.setCursor(0, 20);
    oled.println("Measurement failed"); oled.println("Stay still, retry");
  }
  oled.display();
  delay(8000);
}
safeIdle() and dumpAll() as the safe statesBoth valves default closed and the pump off gives a cuff at atmospheric pressure — safe. dumpAll() opens everything to vent fast. The device is designed so any fault, crash or power loss leaves the cuff deflated, never inflated on an arm.
checkSafety() called throughoutThe 300 mmHg hard ceiling is checked continuously during inflation and deflation, and crossing it triggers an immediate dump. A cuff that keeps inflating due to a sensor fault or a firmware bug is genuinely dangerous, so the ceiling is enforced everywhere pressure can rise.
Closed-loop deflation rate controlAn open valve deflates faster when the cuff is harder, giving a non-constant rate that under-samples the envelope at high pressure. The proportional control on the bleed valve holds 2.5 mmHg/s across the whole deflation, which is what accurate envelope extraction requires.
High-pass to separate oscillations from the rampThe cuff pressure is a slow downward ramp plus small ~1 Hz oscillations. The high-pass removes the ramp, leaving the oscillations whose per-beat peak-to-peak amplitude is the envelope.
MAP at the envelope peak, then ratiosMAP is measured directly and robustly as the cuff pressure at maximum oscillation. Systolic and diastolic are inferred from the 0.55 and 0.85 amplitude ratios — the documentation is explicit that these are empirical population averages, not direct measurements.
showGuidance() before every measurementTechnique dominates accuracy far more than device error. Showing the rest, posture, arm-position and no-talking guidance before every reading is not optional politeness — it is the single biggest determinant of whether the number means anything.
Plausibility gate in analyse()A corrupted envelope (from movement or a leak) can produce a numerically valid but physiologically impossible result. Rejecting readings where systolic ≤ diastolic or values are outside plausible ranges prevents reporting nonsense as a measurement.

Configuration & Calibration

Configuration steps

  • Calibrate the pressure sensor against a reference manometer or a validated BP monitor: record ADC at two known pressures and set calOffset and calScale. This calibration sets the device's absolute accuracy.
  • Set INFLATE_TARGET about 30 mmHg above the expected systolic. Too low misses the systolic point; too high is uncomfortable and wastes time.
  • Tune the deflation-rate control gain so the rate stays at 2–3 mmHg/s across the whole range without oscillating.
  • Use the correct cuff size for the arm — this dominates accuracy and is not adjustable in software.
  • Set the safety ceiling and verify the fast-dump valve vents quickly. Test the fault behaviour before ever putting the cuff on an arm.

Calibration procedure

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

  1. Calibrate against a reference

    Tee the sensor line into a validated BP monitor or a manometer. Pressurise to two known values (e.g. 50 and 200 mmHg by hand pump) and solve for offset and scale. Verify linearity at a third point.

  2. Validate against a clinical device

    Take simultaneous or immediately sequential readings with a validated home monitor on the same arm, at rest, several times. Home BP varies beat to beat, so expect scatter, but the means should agree within a few mmHg. Large systematic differences point to sensor calibration or deflation-rate problems.

  3. Check the deflation rate

    Log cuff pressure during a measurement and confirm the deflation is a straight line at 2–3 mmHg/s, not an exponential decay. A non-constant rate is the most common cause of inaccurate oscillometry.

  4. Test all safety behaviours

    Before any use on a person: confirm the ceiling triggers a dump, the fast-dump valve vents quickly, and a simulated power loss leaves the cuff deflated. These are not optional tests.

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
Power onMeasurement-technique guidance displayed, waiting for start.
Start a measurement on a test cuff (not an arm)Inflation to the target, then a steady 2–3 mmHg/s deflation.
Log the deflation curveA straight downward line, not an exponential decay — confirming the closed-loop rate control works.
Trigger the safety ceilingCrossing 300 mmHg immediately opens the dump valve and aborts.
Simulate a power loss mid-inflationThe cuff deflates — valves are normally-closed venting and the pump is off-by-default.
Measure on an arm (correct cuff size, at rest)A plausible systolic/diastolic/MAP with systolic > diastolic.
Compare against a validated monitorMeans within a few mmHg over several readings; large systematic error points to calibration or deflation rate.
Move or talk during a measurementA corrupted envelope and either a failed-measurement message or a flagged reading — not a confident wrong number.

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.

A wrist-worn fitness tracker
A monitoring device. However good the electronics, correct measurement technique — rest, posture, cuff size — dominates the accuracy of the result. Photograph sourced from Wikimedia Commons — Fitness tracker.jpg. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

Readings are inconsistent between attempts

Likely cause. Movement, talking, or a genuinely variable blood pressure — plus possibly a non-constant deflation rate.

Fix. BP genuinely varies beat to beat and reading to reading; that is why guidelines specify averaging multiple readings after five minutes of rest. Confirm the subject is still and quiet, and verify the deflation rate is steady. Average two or three readings, discarding the first.

Deflation is too fast at the start

Likely cause. A fixed valve opening deflates faster when the cuff is hard.

Fix. The bleed valve must be modulated under closed-loop rate control, not held at a fixed opening. Confirm the proportional control is reducing the valve opening at high pressure to hold 2–3 mmHg/s.

Systolic and diastolic are implausible or reversed

Likely cause. A corrupted or under-sampled envelope.

Fix. Ensure enough beats (at least 8–10) are captured during deflation — too few and the envelope is poorly defined. Check for leaks that distort the oscillations, and confirm movement did not corrupt the signal. The plausibility gate should reject these rather than report them.

The cuff will not inflate

Likely cause. Pump too weak, a leak, or a valve stuck open.

Fix. Check for leaks at every joint — even a small leak makes it impossible to reach target pressure. Confirm the bleed and dump valves are closed during inflation. Verify the pump is rated to reach 200+ mmHg into a cuff.

Readings disagree with a clinic measurement by 10–20 mmHg

Likely cause. Usually technique or cuff size, occasionally calibration.

Fix. Verify cuff size (the biggest factor — too small over-reads substantially), arm at heart level, rest before measuring, and no talking. Then re-check the sensor calibration. Remember that oscillometry and auscultation can legitimately differ somewhat, especially in systolic/diastolic while agreeing on MAP.

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

  • Sample the pressure fast enough (200+ Hz) to resolve the oscillations cleanly, but average lightly to reduce ADC noise, which otherwise adds jitter to the envelope.
  • Hold the deflation rate constant with closed-loop control — a steady rate is worth more to accuracy than any post-processing.
  • Capture at least 10–15 beats across the deflation so the envelope is well-defined; if fewer, slow the deflation slightly.
  • 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

  • The fast-dump valve and the 300 mmHg ceiling are mandatory safety features, not optional. A cuff that stays inflated on an arm restricts blood flow and is dangerous. Design so that any fault, crash or power loss vents the cuff.
  • This is not a validated clinical device. Do not use it to diagnose hypertension or to start, stop or change medication. Those decisions require a validated monitor (passing AAMI/ESH/ISO 81060-2) and a clinician.
  • Never inflate the cuff above what is needed, and never leave a person unattended with an inflated cuff.
  • Do not use on an arm with a dialysis fistula, lymphoedema, or a recent injury or surgery.
  • Technique dominates accuracy: a correct device used incorrectly gives a wrong number. Follow the rest-and-posture guidance every time.
  • 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.
  • 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 a validated reference comparison study to honestly characterise the device's accuracy against a clinical standard.
  • Add morning/evening averaging and a proper trend log as home BP guidelines specify, rather than isolated readings.
  • Add irregular-rhythm detection from the oscillation timing, since atrial fibrillation degrades oscillometric accuracy and should be flagged.
  • Add a second derivation method (e.g. maximum-slope) and compare with the ratio method to understand the spread.
  • Add automatic cuff-size detection or at least a cuff-size prompt, since it is the largest accuracy factor.
  • 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 does it not measure systolic and diastolic directly?

Because oscillometry physically cannot. It measures the oscillation envelope, whose peak directly gives mean arterial pressure. Systolic and diastolic are then inferred from characteristic points on the envelope using empirical ratios (about 0.55 and 0.85 of the peak amplitude). Every automatic home monitor works this way — the older stethoscope method (auscultation) measures systolic and diastolic more directly, which is why the two can slightly disagree.

How accurate can a DIY monitor be?

The method is capable of clinical-grade accuracy — that is what commercial oscillometric monitors achieve. But reaching it requires careful pressure-sensor calibration, steady deflation control, the right cuff size, and correct technique. A DIY build can get close for personal trend tracking, but it is not validated and should not drive medical decisions. Validation against a clinical standard is a formal, demanding process for good reason.

Why does cuff size matter so much?

The cuff transmits arterial pressure to the sensor, and this transmission depends on how the cuff fits. A cuff too small for the arm does not compress the artery efficiently and over-reads — sometimes by 10–40 mmHg. A cuff too large under-reads. Using the correct size for the arm circumference is one of the single most important accuracy factors, and no software can fix a wrong cuff.

Why all the fuss about technique?

Because technique error dwarfs device error. Talking during a measurement can add 10 mmHg; a full bladder, crossed legs, an unsupported back, an arm below heart level, or a recent coffee each shift the reading substantially. A perfect device used on a talking, slouching subject gives a worse number than a modest device used correctly. That is why the device shows guidance before every reading.

Is one reading enough?

No. Blood pressure varies continuously, and guidelines specify taking several readings after five minutes of quiet rest and averaging them (often discarding the first). A single reading is nearly meaningless for anything but a rough check. The device prompts to average, and a proper home-monitoring protocol takes morning and evening readings over several days.

Can I use this instead of buying a monitor?

For learning how blood pressure measurement works, absolutely — it is an excellent project. For actually managing your health, buy a validated monitor: they are inexpensive, they have passed formal accuracy validation, and hypertension is a condition where wrong numbers lead to wrong treatment. Use this to understand the method, not to replace a validated device.

References & Learning Resources

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

  1. Geddes, "The Direct and Indirect Measurement of Blood Pressure"Year Book Medical Publishers
  2. ISO 81060-2 — Non-invasive sphygmomanometers, clinical validationISO
  3. Ukawa et al., "Novel non-invasive blood pressure measurement and the oscillometric method"Journal of Clinical Monitoring, 2017
  4. Muntner et al., "Measurement of Blood Pressure in Humans: A Scientific Statement from the AHA"Hypertension, 2019
  5. MPX5050 integrated silicon pressure sensor — datasheetNXP
  6. STRIDE BP — validated blood pressure monitor listingsSTRIDE BP