BPM, SpO₂, ECG & Body.Tempr. - Patient Health Monitor using ESP32 via Live Web Dashboard

Overview

An ESP32-based Patient Health Monitoring System that can monitor important health parameters in real time using a live web dashboard.

Components Required

Following are the components required to make the ESP32 Patient Health Monitor with Live Web Dashboard. All these components can be purchased from the given links.

S.N.Components NameQuantityPurchase Link
1ESP32 Board1Amazon | AliExpress
2AD8232 ECG Sensor1Amazon | AliExpress
3MAX30102 Pulse Oximeter1Amazon | AliExpress
4ADS1115 ADC Module1Amazon | AliExpress
5BME280 Sensor1Amazon | AliExpress
610K NTC Thermistor1Amazon | AliExpress
710K Resistor1Amazon | AliExpress
810uF Electrolytic Capacitor1Amazon | AliExpress
90.1uF Ceramic Capacitor5Amazon | AliExpress
10Jumper Wires4Amazon | AliExpress

Block Diagram of ESP32 Patient Health Monitor

Let’s take a look at the block diagram of the ESP32-based Patient Health Monitor with Live Web Dashboard.


This project measures heart rate/BPM, SpO2 blood oxygen, ECG waveform, body temperature, room temperature, and humidity. The ESP32 reads data from multiple sensors and displays everything on a clean web dashboard that can be opened from a phone, tablet, or PC on the same Wi-Fi network.

Fig: Block Diagram ESP32 Patient Health Monitor

The system is divided into four main sensor paths connected to the ESP32 DevKit v1:

  • ECG path — AD8232 → ADS1115 AIN0 → ESP32 (BPM + waveform)
  • SpO₂ path — MAX30102 → I2C → ESP32 (blood oxygen)
  • Body temperature path — 10K NTC divider → ADS1115 AIN1 → ESP32
  • Environment path — BME280 → I2C → ESP32 (room temp + humidity)

The AD8232 ECG sensor module is a single-lead heart rate monitor front-end used to acquire biopotential signals from the human body. It includes an integrated instrumentation amplifier, filter, and right-leg drive circuitry to produce a clean analog ECG output suitable for microcontroller ADC input. Go through AD8232 Arduino Tutorial for more info.


AD8232 ECG Sensor Module

The ESP32 reads all sensor data, calculates BPM from ECG R-peaks, hosts REST APIs, and serves the live dashboard through the built-in web server. Any phone, tablet, or PC on the same Wi-Fi network can open the ESP32 IP address to view real-time vitals and the ECG waveform.

AD8232 ECG Sensor
Fig: AD8232 ECG Sensor

The module outputs an analog ECG signal that is read by the microcontroller ADC Pin. It also provides lead-off detection (LO+ and LO−) pins, which go HIGH when electrodes lose contact with the skin. This helps the firmware and dashboard show a safe flat-line trace and a “LEADS OFF” warning instead of displaying invalid cardiac data.

Features & Specifications

FeatureSpecification
Operating Voltage3.3V (compatible with ESP32)
Output TypeAnalog ECG signal (ECG_OUT)
Lead ConfigurationSingle-lead (3-electrode: RA, LA, RL)
Lead-Off DetectionLO+ and LO− digital outputs
Shutdown PinSDN (GPIO 5 — HIGH = enable)
ApplicationsHeart rate monitoring, ECG waveform display

Electrode Placement

Red (RA) → Right Arm or right wrist

Yellow (LA) → Left Arm or left wrist

Green (RL) → Right Leg or lower abdomen (driven reference)

Fig: Typical Electrode Placement

MAX30102 Pulse Oximeter Sensor

The MAX30102 is an integrated pulse oximetry sensor module. It uses red and infrared LEDs with a photodetector to measure light absorption through the finger and calculate SpO₂ (blood oxygen saturation). Go through MAX30102 Arduino Tutorial for more info.

Fig: Different MAX30102 Modules

In this project, the MAX30102 communicates with the ESP32 over I2C at address 0x57. It can measure Heart Beat in BPM, Blood Oxygen Concentration in percentage and temperature as well. In this project, the MAX30102 is used to only measure Blood Oxygent Concentration SPO2 (%).

FeatureSpecification
InterfaceI2C @ 0x57
MeasurementSpO₂ (%), finger detection
Operating Voltage3.3V (module level)
Normal SpO₂ Range95% – 100%

BME280 Environmental Sensor

The BME280 is a high-precision digital sensor that combines temperature, humidity, and barometric pressure measurement in a single compact module. In this project, it is used specifically for room environmental monitoring — tracking ambient temperature and relative humidity. Refer to ESP32 BME280 Tutorial for more detailed guide.

Fig: BME280 Environmental Sensor Module

Features & Specifications

FeatureSpecification
InterfaceI2C @ 0x76 (ADDR = GND)
Temperature Range−40°C to +85°C
Humidity Range0% to 100% RH
Accuracy (Temp)±1°C typical
LibraryAdafruit BME280 + Adafruit Unified Sensor
Update Rate in FirmwareEvery 2 seconds

10K NTC Thermistor (Body Temperature Sensor)

Body temperature is measured using a 10K NTC thermistor in a classic voltage divider circuit. Unlike the BME280 which measures room air temperature digitally over I2C, the NTC probe measures skin or body contact temperature through an analog signal read by the ADS1115.

Fig: 10K NTC Thermistor

NTC Voltage Divider Circuit

The thermistor circuit uses:

  • R2 — 10K fixed series resistor to 3.3V
  • R3 — 10K NTC thermistor to GND
  • TEMP_SENSE node → ADC of MCU
As body temperature increases, NTC resistance decreases and the voltage at ADC rises.

Specifications

ParameterValue
ADS1115 ChannelAIN1 (not AIN0)
Thermistor10K NTC @ 25°C
Series Resistor (R2)10K ohm
Supply Voltage3.3V
Beta Coefficient3950
ADS GainGAIN_ONE (±4.096V)
Typical Skin Reading~35°C – 37°C with good contact

ADS1115 16-Bit ADC

The ADS1115 is a 16-bit analog-to-digital converter that communicates through the I2C interface. It is commonly used when a microcontroller needs to read analog signals with higher resolution than its built-in ADC. You may follow ADS1115 ESP32 Guide for more information.

ADS1115
  • 16-bit resolution for accurate analog signal measurement
  • I2C interface for easy connection with microcontrollers
  • Four analog input channels: AIN0, AIN1, AIN2, and AIN3
  • Programmable gain amplifier for measuring small voltage signals
  • Configurable data rate for different sampling requirements

The ADS1115 can be used to measure different types of analog signals such as sensor outputs, voltage dividers, battery voltage, pressure sensors, temperature sensors, and other low-voltage signals. Its programmable gain settings make it useful for both general-purpose analog readings and more sensitive signal measurements.


Circuit Diagram

Let’s take a look at the schematic of the ESP32-based Patient Health Monitor project. The schematic is designed in EasyEDA.

Schematic ESP32 Patient Health Monitor
Fig: Schematic ESP32 Patient Health Monitor

Main Circuit Blocks

The schematic (Board1, Version V1.0) contains five functional blocks connected to the ESP32:

RefModuleRole
U1ESP32 DevKit-v1Main MCU, Wi-Fi, web server
U3AD8232ECG analog front-end
U4MAX30102Pulse oximeter (SpO₂)
U5BME280Room temperature & humidity
U6ADS111516-bit ADC for ECG + NTC

ESP32 Pin Connections

D21GPIO 21I2C SDA (shared bus)
D22GPIO 22I2C SCL (shared bus)
D5GPIO 5AD8232 SDN (sensor enable, HIGH = run)
D18GPIO 18AD8232 LO+ (lead-off detect)
D19GPIO 19AD8232 LO− (lead-off detect)

I2C Device Addresses

Device I2C Address Bus Pins
ADS1115 (U6) 0x48 SDA / SCL
MAX30102 (U4) 0x57 SDA / SCL
BME280 (U5) 0x76 SDA / SCL (ADDR = GND)

AD8232 ECG Signal Path

  • ECG_OUT → ADS1115 A0 (AIN0)
  • ECG_SDN → ESP32 GPIO 5 (OUTPUT HIGH in setup)
  • LO+ → ESP32 GPIO 18 (INPUT)
  • LO− → ESP32 GPIO 19 (INPUT)
  • 3.3V / GND → AD8232 power with decoupling capacitors

NTC Body Temperature Divider

  • 3.3V → R2 (10K) → TEMP_SENSE node → R3 (10K NTC) → GND
  • TEMP_SENSE → ADS1115 A1 (AIN1)

Power Supply & Decoupling

All modules run from 3.3V. The schematic includes decoupling capacitors on each sensor rail:

  • C1 — 10µF bulk capacitor
  • C2, C4, C5, C6, C7 — 100nF ceramic capacitors near IC power pins

These capacitors reduce power supply noise and help keep the ECG trace clean on the dashboard.


PCB Designing & Gerber Files

The schematic of the ESP32 Patient Health Monitor was created in EasyEDA, and from there it was converted into a compact PCB layout.
Fig: PCB Designing
The board is designed with mostly through-hole components to make assembly easier. You can view the 2D view of the PCB.
Fig: PCB 3D View

All of the critical components, including the ESP32 module, ADS1115, sensor connectors, and power filtering capacitors, are placed on the front side of the PCB, which makes assembly easier and more reliable.

Here are the links of files that you can download for PCB manufacturing and PCB assembly services.

  1. Download: Schematic PDF
  2. Download: Gerber File

Assembly of the ESP32 Patient Health Monitor

After I ordered the custom PCB, I received it within just 3 days. The PCB quality was very good, and it looked clean and professional. It is a double-sided PCB, which makes the circuit compact and neat.

PCB for ESP32 Patient Health Monitor
Fig: PCB for ESP32 Patient Health Monitor

Then I started soldering and assembling all the components on the board. For the ESP32 board, ADS1115, MAX30102, BME280, and AD8232 ECG module, I used female header pins where needed. This makes it easy to remove or replace the modules later if required.

Assembly-1
Fig: Assembly-1

I also soldered the required decoupling capacitors (10µF and 100nF) on different parts of the PCB as shown in the schematic. These capacitors help to keep the power supply stable and reduce noise in the ECG signal. For the MAX30102 module and NTC thermistor probe, I used jumper wires to connect them to the PCB terminal blocks.

Assembly-2
Fig: Assembly-2

After soldering all the parts, I connected the ECG electrode cable, SpO₂ sensor, and NTC temperature probe, then completed the final assembly of the IoT ESP32 Patient Health Monitor device.

ESP32 AD8232 MAX30102 Thermistor ADS1115
Fig: ESP32 AD8232 MAX30102 Thermistor ADS1115


Source Code / Program

Let us take a look at the programming part of this project.

The code starts by including the required libraries for Wi-Fi, web server, I2C sensors, and the dashboard page stored in PROGMEM. The WiFi and WebServer libraries are used to connect the ESP32 to the local network and host the live patient health dashboard. The Adafruit ADS1X15 library reads ECG and NTC values from the ADS1115. The Adafruit BME280 library reads room temperature and humidity. The SparkFun MAX3010x library with spo2_algorithm.h calculates SpO₂ from MAX30102 data.

In the Wi-Fi section, the SSID and password are added so the ESP32 can connect to the network. After connecting, the ESP32 prints its IP address in the Serial Monitor at 115200 baud. This IP address can be opened in a browser to access the professional web dashboard.

The code is divided into two main parts: the main Patient_Health_Monitor.ino file for ESP32 sensor control and API, and the dashboard_page.h file for the live web dashboard interface.

main.ino

Copy the following code and paste it to your Arduino IDE editor window. Create a new sketch folder named Patient_Health_Monitor and save this file as Patient_Health_Monitor.ino.

/*
 * Patient Health Monitor
 *
 * I2C (SDA=21, SCL=22): BME280 @0x76, ADS1115 @0x48, MAX30102 @0x57
 * ADS1115 AIN0: AD8232 ECG   AIN1: NTC body temp
 * ECG_SDN -> D5, LO+ -> D18, LO- -> D19
 */
 
#include <wifi .h="">
#include <webserver .h="">
#include <wire .h="">
#include <math .h="">
#include <adafruit_ads1x15 .h="">
#include <adafruit_sensor .h="">
#include <adafruit_bme280 .h="">
#include <max30105 .h="">
#include <spo2_algorithm .h="">
#include "dashboard_page.h"
 
const char* WIFI_SSID = "****************";
const char* WIFI_PASSWORD = "***************";
 
static const int I2C_SDA_PIN = 21;
static const int I2C_SCL_PIN = 22;
static const int ECG_SDN_PIN = 5;
static const int LO_PLUS_PIN = 18;
static const int LO_MINUS_PIN = 19;
 
static const uint8_t ECG_CHANNEL = 0;
static const uint8_t THERMISTOR_CHANNEL = 1;
static const uint8_t ADS1115_I2C_ADDR = 0x48;
static const uint8_t BME280_I2C_ADDR = 0x76;
 
static const uint16_t SAMPLE_INTERVAL_MS = 8;
static const uint16_t SLOW_SENSOR_MS = 2000;
static const uint8_t ECG_QUEUE_SIZE = 28;
 
static const float SUPPLY_VOLTAGE = 3.3f;
static const float SERIES_RESISTOR_OHMS = 10000.0f;
static const float NTC_NOMINAL_OHMS = 10000.0f;
static const float NTC_NOMINAL_TEMP_C = 25.0f;
static const float NTC_BETA = 3950.0f;
 
static const long FINGER_IR_THRESHOLD = 50000;
static const int32_t SPO2_BUFFER_LENGTH = 100;
static const int32_t SPO2_SHIFT_SAMPLES = 25;
 
WebServer server(80);
Adafruit_ADS1115 ads;
Adafruit_BME280 bme;
MAX30105 particleSensor;
 
bool bmeOk = false;
bool maxOk = false;
 
unsigned long lastSampleMs = 0;
unsigned long lastSlowMs = 0;
unsigned long lastDebugMs = 0;
 
int lastEcgValue = 512;
int lastRawAdc = 0;
float lastVoltage = 0.0f;
bool lastLeadsOff = true;
int lastLoPlus = 0;
int lastLoMinus = 0;
 
int ecgQueue[ECG_QUEUE_SIZE];
volatile uint8_t ecgQWrite = 0;
volatile uint8_t ecgQRead = 0;
 
int ecgBpm = -1;
int32_t ecgBaseline = 512;
int ecgSignalLevel = 0;
bool ecgBeatArmed = true;
unsigned long lastRPeakMs = 0;
 
float roomTempC = 0.0f;
float roomHumidity = 0.0f;
float bodyTempC = -999.0f;
int spo2Pct = -1;
bool fingerDetected = false;
 
uint32_t irBuffer[100];
uint32_t redBuffer[100];
int32_t spo2 = 0;
int8_t validSPO2 = 0;
int32_t maximHeartRate = 0;
int8_t validMaximHeartRate = 0;
 
byte sampleIndex = 0;
bool bufferFilled = false;
 
char jsonBuffer[384];
 
bool leadsOff() {
  lastLoPlus = digitalRead(LO_PLUS_PIN);
  lastLoMinus = digitalRead(LO_MINUS_PIN);
  return (lastLoPlus == HIGH) || (lastLoMinus == HIGH);
}
 
float readChannelVoltage(uint8_t channel) {
  int32_t sum = 0;
  for (uint8_t i = 0; i < 4; i++) {
    sum += ads.readADC_SingleEnded(channel);
    yield();
  }
  return ads.computeVolts((int16_t)(sum / 4));
}
 
float ntcResistanceFromVoltage(float voltage) {
  if (voltage <= 0.001f || voltage >= SUPPLY_VOLTAGE - 0.001f) {
    return NAN;
  }
  return SERIES_RESISTOR_OHMS * voltage / (SUPPLY_VOLTAGE - voltage);
}
 
float ntcResistanceToCelsius(float resistance) {
  if (isnan(resistance) || resistance <= 0.0f) {
    return NAN;
  }
  float steinhart = resistance / NTC_NOMINAL_OHMS;
  steinhart = log(steinhart);
  steinhart /= NTC_BETA;
  steinhart += 1.0f / (NTC_NOMINAL_TEMP_C + 273.15f);
  steinhart = 1.0f / steinhart;
  return steinhart - 273.15f;
}
 
float readBodyTemperatureC() {
  const float voltage = readChannelVoltage(THERMISTOR_CHANNEL);
  const float resistance = ntcResistanceFromVoltage(voltage);
  return ntcResistanceToCelsius(resistance);
}
 
int readEcgValue() {
  lastRawAdc = ads.readADC_SingleEnded(ECG_CHANNEL);
  lastVoltage = ads.computeVolts(lastRawAdc);
  return map(lastRawAdc, 0, 32767, 0, 1023);
}
 
void ecgQueueClear() {
  ecgQRead = 0;
  ecgQWrite = 0;
}
 
void ecgQueuePush(int value) {
  const uint8_t next = (uint8_t)((ecgQWrite + 1) % ECG_QUEUE_SIZE);
  if (next == ecgQRead) {
    ecgQRead = (uint8_t)((ecgQRead + 1) % ECG_QUEUE_SIZE);
  }
  ecgQueue[ecgQWrite] = value;
  ecgQWrite = next;
}
 
uint8_t ecgQueueDrain(int* out, uint8_t maxOut) {
  uint8_t count = 0;
  while (ecgQRead != ecgQWrite && count < maxOut) {
    out[count++] = ecgQueue[ecgQRead];
    ecgQRead = (uint8_t)((ecgQRead + 1) % ECG_QUEUE_SIZE);
  }
  return count;
}
 
void resetEcgBpm() {
  ecgBpm = -1;
  ecgBaseline = 512;
  ecgSignalLevel = 0;
  ecgBeatArmed = true;
  lastRPeakMs = 0;
  ecgQueueClear();
}
 
void updateEcgBpm(int sample) {
  ecgBaseline = (ecgBaseline * 995 + sample * 5) / 1000;
  const int hp = abs(sample - (int)ecgBaseline);
 
  ecgSignalLevel = (ecgSignalLevel * 127 + hp) / 128;
  const int threshold = max(18, (ecgSignalLevel * 3) / 2);
 
  if (hp > threshold && ecgBeatArmed) {
    const unsigned long now = millis();
    if (lastRPeakMs > 0) {
      const unsigned long interval = now - lastRPeakMs;
      if (interval >= 300 && interval <= 2000) {
        const int bpm = (int)(60000UL / interval);
        ecgBpm = (ecgBpm < 0) ? bpm : ((ecgBpm * 3) + bpm) / 4;
      }
    }
    lastRPeakMs = now;
    ecgBeatArmed = false;
  } else if (hp < threshold / 3) {
    ecgBeatArmed = true;
  }
}
 
void updateEcgSample() {
  const unsigned long now = millis();
  if (now - lastSampleMs < SAMPLE_INTERVAL_MS) {
    return;
  }
  lastSampleMs = now;
 
  lastLeadsOff = leadsOff();
  if (lastLeadsOff) {
    resetEcgBpm();
    lastEcgValue = 512;
    ecgQueuePush(512);
  } else {
    lastEcgValue = readEcgValue();
    ecgQueuePush(lastEcgValue);
    updateEcgBpm(lastEcgValue);
  }
}
 
void shiftBuffers() {
  for (byte i = SPO2_SHIFT_SAMPLES; i < SPO2_BUFFER_LENGTH; i++) {
    redBuffer[i - SPO2_SHIFT_SAMPLES] = redBuffer[i];
    irBuffer[i - SPO2_SHIFT_SAMPLES] = irBuffer[i];
  }
  sampleIndex = SPO2_BUFFER_LENGTH - SPO2_SHIFT_SAMPLES;
}
 
void calculateSpO2() {
  maxim_heart_rate_and_oxygen_saturation(
    irBuffer, SPO2_BUFFER_LENGTH, redBuffer,
    &spo2, &validSPO2, &maximHeartRate, &validMaximHeartRate
  );
}
 
void updateSpO2Reading() {
  if (fingerDetected && validSPO2 && spo2 > 0 && spo2 <= 100) {
    spo2Pct = (int)spo2;
  } else {
    spo2Pct = -1;
  }
}
 
void updateMax30102() {
  if (!maxOk) {
    return;
  }
 
  particleSensor.check();
 
  while (particleSensor.available()) {
    const uint32_t irValue = particleSensor.getIR();
    const uint32_t redValue = particleSensor.getRed();
    particleSensor.nextSample();
 
    fingerDetected = (irValue >= FINGER_IR_THRESHOLD);
 
    if (!bufferFilled) {
      redBuffer[sampleIndex] = redValue;
      irBuffer[sampleIndex] = irValue;
      sampleIndex++;
      if (sampleIndex >= SPO2_BUFFER_LENGTH) {
        bufferFilled = true;
        calculateSpO2();
        sampleIndex = SPO2_BUFFER_LENGTH - SPO2_SHIFT_SAMPLES;
        updateSpO2Reading();
        server.handleClient();
      }
    } else {
      redBuffer[sampleIndex] = redValue;
      irBuffer[sampleIndex] = irValue;
      sampleIndex++;
      if (sampleIndex >= SPO2_BUFFER_LENGTH) {
        shiftBuffers();
        calculateSpO2();
        updateSpO2Reading();
        server.handleClient();
      }
    }
 
    yield();
    server.handleClient();
  }
}
 
void updateSlowSensors() {
  const unsigned long now = millis();
  if (now - lastSlowMs < SLOW_SENSOR_MS) {
    return;
  }
  lastSlowMs = now;
 
  if (bmeOk) {
    roomTempC = bme.readTemperature();
    roomHumidity = bme.readHumidity();
  }
 
  const float body = readBodyTemperatureC();
  bodyTempC = isnan(body) ? -999.0f : body;
 
  if (now - lastDebugMs >= 2000) {
    lastDebugMs = now;
    Serial.printf(
      "Room: %.1f C  Hum: %.1f%%  Body: %.1f C  SpO2: %d%% (valid=%d)  Finger: %s\n",
      roomTempC, roomHumidity, bodyTempC, spo2Pct, validSPO2, fingerDetected ? "yes" : "no"
    );
    Serial.printf(
      "ECG plot=%d  raw=%d  %.3fV  bpm=%d  leads=%s\n",
      lastEcgValue, lastRawAdc, lastVoltage, ecgBpm, lastLeadsOff ? "OFF" : "ON"
    );
  }
}
 
void handleRoot() {
  server.send_P(200, "text/html", DASHBOARD_PAGE);
}
 
void handleEcgApi() {
  int samples[ECG_QUEUE_SIZE];
  uint8_t count = ecgQueueDrain(samples, ECG_QUEUE_SIZE);
  if (count == 0) {
    samples[0] = lastEcgValue;
    count = 1;
  }
 
  char* p = jsonBuffer;
  int rem = (int)sizeof(jsonBuffer);
  int n = snprintf(p, rem, "{\"v\":[");
  p += n;
  rem -= n;
 
  for (uint8_t i = 0; i < count && rem > 12; i++) {
    if (i > 0) {
      *p++ = ',';
      rem--;
    }
    n = snprintf(p, rem, "%d", samples[i]);
    p += n;
    rem -= n;
  }
 
  snprintf(
    p, rem,
    "],\"lo\":%d,\"raw\":%d,\"mv\":%d,\"lp\":%d,\"lm\":%d,\"bpm\":%d}",
    lastLeadsOff ? 1 : 0,
    lastRawAdc,
    (int)(lastVoltage * 1000.0f),
    lastLoPlus,
    lastLoMinus,
    ecgBpm
  );
 
  server.sendHeader("Cache-Control", "no-cache");
  server.send(200, "application/json", jsonBuffer);
}
 
void handleVitalsApi() {
  snprintf(
    jsonBuffer, sizeof(jsonBuffer),
    "{\"roomT\":%.1f,\"hum\":%.1f,\"bodyT\":%.1f,\"spo2\":%d,\"spo2Valid\":%d,\"finger\":%d,\"bme\":%d}",
    roomTempC,
    roomHumidity,
    bodyTempC,
    spo2Pct,
    (validSPO2 && fingerDetected) ? 1 : 0,
    fingerDetected ? 1 : 0,
    bmeOk ? 1 : 0
  );
 
  server.sendHeader("Cache-Control", "no-cache");
  server.send(200, "application/json", jsonBuffer);
}
 
void setupWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
 
  Serial.print(F("Connecting to WiFi"));
  uint8_t attempts = 0;
  while (WiFi.status() != WL_CONNECTED && attempts < 40) {
    delay(500);
    Serial.print('.');
    attempts++;
  }
  Serial.println();
 
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println(F("WiFi failed."));
    return;
  }
 
  Serial.print(F("Open: http://"));
  Serial.println(WiFi.localIP());
}
 
void setup() {
  Serial.begin(115200);
  delay(500);
 
  pinMode(ECG_SDN_PIN, OUTPUT);
  digitalWrite(ECG_SDN_PIN, HIGH);
  pinMode(LO_PLUS_PIN, INPUT);
  pinMode(LO_MINUS_PIN, INPUT);
 
  Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN);
 
  if (!ads.begin(ADS1115_I2C_ADDR)) {
    Serial.println(F("ERROR: ADS1115 not found"));
    while (true) {
      delay(1000);
      yield();
    }
  }
  ads.setGain(GAIN_ONE);
  ads.setDataRate(RATE_ADS1115_128SPS);
  Serial.println(F("ADS1115 OK (ECG AIN0, NTC AIN1)"));
 
  bmeOk = bme.begin(BME280_I2C_ADDR);
  Serial.println(bmeOk ? F("BME280 OK") : F("BME280 not found"));
 
  maxOk = particleSensor.begin(Wire, I2C_SPEED_FAST);
  if (maxOk) {
    particleSensor.setup(60, 4, 2, 100, 411, 4096);
    particleSensor.setPulseAmplitudeGreen(0);
    Serial.println(F("MAX30102 OK (SparkFun SpO2 algorithm)"));
  } else {
    Serial.println(F("MAX30102 not found"));
  }
 
  setupWiFi();
 
  server.on("/", handleRoot);
  server.on("/api/ecg", handleEcgApi);
  server.on("/api/vitals", handleVitalsApi);
  server.begin();
 
  Serial.println(F("Patient Health Monitor ready"));
}
 
void loop() {
  server.handleClient();
 
  if (WiFi.status() == WL_CONNECTED) {
    updateEcgSample();
    updateMax30102();
    updateSlowSensors();
    server.handleClient();
  }
 
  yield();
}

dashboard_page.h

The dashboard is stored as a single HTML page inside dashboard_page.h using PROGMEM (DASHBOARD_PAGE string). The ESP32 serves it directly without needing external hosting or SD card storage. Create a file named dashboard_page.h in the same folder as the sketch and paste the following code:

#ifndef DASHBOARD_PAGE_H
#define DASHBOARD_PAGE_H
 
const char DASHBOARD_PAGE[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
  <title>Patient Health Monitor</title>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@500;600;700;800&display=swap" rel="stylesheet" />
  <style>
    :root {
      --bg-1: #eef4ff;
      --bg-2: #e8f0fe;
      --sidebar: #0f172a;
      --sidebar-hover: #1e293b;
      --sidebar-active: #2563eb;
      --card: rgba(255,255,255,0.94);
      --text: #0f172a;
      --muted: #64748b;
      --blue: #2563eb;
      --cyan: #06b6d4;
      --green: #16a34a;
      --red: #ef4444;
      --orange: #f59e0b;
      --green-soft: #dcfce7;
      --red-soft: #fee2e2;
      --orange-soft: #fef3c7;
      --blue-soft: #dbeafe;
      --shadow: 0 20px 50px rgba(15,23,42,0.14);
      --radius: 18px;
    }
    * { margin: 0; padding: 0; box-sizing: border-box; }
    html, body { height: 100%; width: 100%; overflow: hidden; }
    body {
      font-family: "Plus Jakarta Sans", "Segoe UI", system-ui, sans-serif;
      color: var(--text);
      background:
        radial-gradient(circle at 8% 10%, rgba(37,99,235,0.18), transparent 30%),
        radial-gradient(circle at 92% 8%, rgba(6,182,212,0.16), transparent 28%),
        linear-gradient(135deg, var(--bg-1), var(--bg-2));
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0;
    }
    .viewport-wrap {
      aspect-ratio: 15 / 9;
      width: min(100vw, calc(100vh * 15 / 9));
      height: min(100vh, calc(100vw * 9 / 15));
    }
    .app-shell {
      width: 100%;
      height: 100%;
      display: flex;
      border-radius: 0;
      overflow: hidden;
      box-shadow: none;
      border: none;
      background: var(--card);
    }
    .sidebar {
      width: 210px;
      flex-shrink: 0;
      background: linear-gradient(180deg, #0b1224 0%, #111827 55%, #0f172a 100%);
      color: #e2e8f0;
      display: flex;
      flex-direction: column;
      padding: 18px 12px;
      border-right: 1px solid rgba(255,255,255,0.06);
    }
    .sidebar-brand {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 8px 10px 20px;
      border-bottom: 1px solid rgba(255,255,255,0.08);
      margin-bottom: 14px;
    }
    .sidebar-logo {
      width: 42px; height: 42px; border-radius: 13px;
      background: linear-gradient(135deg, #f43f5e 0%, #e11d48 50%, #be123c 100%);
      display: grid; place-items: center;
      box-shadow: 0 6px 18px rgba(244,63,94,0.45);
      flex-shrink: 0;
    }
    .sidebar-logo svg {
      width: 24px; height: 24px;
      fill: none; stroke: #fff;
      stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round;
    }
    .sidebar-brand strong {
      display: block; font-size: 0.88rem; letter-spacing: -0.02em;
      background: linear-gradient(90deg, #fff, #fda4af);
      -webkit-background-clip: text; -webkit-text-fill-color: transparent;
      background-clip: text;
    }
    .sidebar-brand span {
      font-size: 0.68rem; color: #94a3b8;
    }
    .nav-label {
      font-size: 0.65rem; text-transform: uppercase;
      letter-spacing: 0.1em; color: #64748b;
      padding: 0 10px; margin-bottom: 8px;
    }
    .nav { flex: 1; display: flex; flex-direction: column; gap: 4px; }
    .nav-item {
      border: none; background: transparent; color: #cbd5e1;
      text-align: left; padding: 10px 12px;
      border-radius: 12px; font-size: 0.84rem; font-weight: 700;
      cursor: pointer; display: flex; align-items: center; gap: 10px;
      transition: background 0.15s, color 0.15s, transform 0.12s;
    }
    .nav-item:hover { background: var(--sidebar-hover); color: #fff; transform: translateX(2px); }
    .nav-item.active {
      background: linear-gradient(90deg, #2563eb, #3b82f6);
      color: #fff;
      box-shadow: 0 8px 22px rgba(37,99,235,0.4);
    }
    .nav-icon-wrap {
      width: 30px; height: 30px; border-radius: 9px;
      display: grid; place-items: center;
      font-size: 14px; flex-shrink: 0;
      background: rgba(255,255,255,0.08);
    }
    .nav-item.active .nav-icon-wrap { background: rgba(255,255,255,0.22); }
    .nav-item[data-page="dashboard"] .nav-icon-wrap { background: rgba(244,63,94,0.2); }
    .nav-item[data-page="patient"] .nav-icon-wrap { background: rgba(59,130,246,0.2); }
    .nav-item[data-page="logging"] .nav-icon-wrap { background: rgba(16,185,129,0.2); }
    .nav-item[data-page="alerts"] .nav-icon-wrap { background: rgba(245,158,11,0.2); }
    .nav-icon { width: auto; text-align: center; opacity: 1; }
    .sidebar-foot {
      padding: 12px 10px 4px;
      border-top: 1px solid rgba(255,255,255,0.08);
      font-size: 0.72rem; color: #94a3b8;
    }
    .live-pill {
      display: flex; align-items: center; gap: 7px;
      margin-bottom: 6px; font-weight: 800; color: #e2e8f0;
    }
    .live-dot {
      width: 8px; height: 8px; border-radius: 50%;
      background: var(--green);
      animation: pulse 1.5s infinite;
    }
    .live-dot.off { background: var(--red); animation: none; }
    @keyframes pulse {
      0% { box-shadow: 0 0 0 0 rgba(22,163,74,0.5); }
      75% { box-shadow: 0 0 0 8px rgba(22,163,74,0); }
      100% { box-shadow: 0 0 0 0 rgba(22,163,74,0); }
    }
    .main {
      flex: 1; min-width: 0;
      display: flex; flex-direction: column;
      background: linear-gradient(180deg, #fafbff, #f1f5f9);
    }
    .topbar {
      flex-shrink: 0;
      padding: 10px 16px;
      display: flex; justify-content: space-between; align-items: center;
      gap: 12px;
      border-bottom: 1px solid rgba(148,163,184,0.15);
      background: linear-gradient(90deg, rgba(255,255,255,0.98), rgba(239,246,255,0.98));
    }
    .topbar h1 {
      font-size: 1.12rem; letter-spacing: -0.03em; font-weight: 800;
    }
    .topbar p { font-size: 0.76rem; color: var(--muted); margin-top: 2px; font-weight: 600; }
    .topbar-actions {
      display: flex; align-items: center; gap: 12px;
      flex-shrink: 0;
    }
    .topbar-meta {
      text-align: right; font-size: 0.72rem; color: var(--muted); font-weight: 700;
    }
    .topbar-meta strong { display: block; color: var(--text); font-size: 0.86rem; font-weight: 800; }
    .sound-toggle {
      width: 36px; height: 36px;
      border-radius: 11px;
      border: 1.5px solid #e2e8f0;
      background: #fff;
      color: #64748b;
      font-size: 16px; line-height: 1;
      cursor: pointer;
      display: grid; place-items: center;
      transition: background 0.15s, border-color 0.15s, color 0.15s, transform 0.12s;
      flex-shrink: 0;
    }
    .sound-toggle:hover { background: #f8fafc; border-color: #cbd5e1; }
    .sound-toggle:active { transform: scale(0.94); }
    .sound-toggle.muted { opacity: 0.5; background: #f1f5f9; }
    .sound-toggle:not(.muted) {
      background: #eff6ff;
      border-color: #93c5fd;
      color: #2563eb;
    }
    .sound-toggle svg {
      width: 18px; height: 18px;
      stroke: currentColor; fill: none;
      stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;
    }
    .sound-toggle .sound-off { display: none; }
    .sound-toggle.muted .sound-on { display: none; }
    .sound-toggle.muted .sound-off { display: block; }
    .topbar-actions .sound-toggle + .topbar-meta {
      padding-left: 12px;
      border-left: 1px solid #e2e8f0;
    }
    .page-area {
      flex: 1; min-height: 0;
      overflow: hidden; position: relative;
    }
    .page {
      display: none;
      position: absolute;
      inset: 0;
      overflow-y: auto;
      overflow-x: hidden;
      padding: 14px 18px 16px;
      -webkit-overflow-scrolling: touch;
    }
    .page.active {
      display: block;
      z-index: 1;
    }
    #page-patient.page.active {
      display: flex;
      flex-direction: column;
      overflow: hidden;
      padding: 10px 14px 12px;
      background: linear-gradient(180deg, #f0f4fa 0%, #e8eef6 100%);
    }
    .record-page {
      flex: 1; min-height: 0;
      display: flex; flex-direction: column; gap: 10px;
      overflow: hidden;
    }
    .record-banner {
      flex-shrink: 0;
      position: relative; overflow: hidden;
      border-radius: 18px;
      padding: 0;
    }
    .record-banner-bg {
      position: absolute; inset: 0;
      background: linear-gradient(120deg, #1e3a8a 0%, #2563eb 45%, #0891b2 100%);
    }
    .record-banner-bg::after {
      content: "";
      position: absolute; inset: 0;
      background:
        radial-gradient(circle at 85% 20%, rgba(255,255,255,0.2), transparent 42%),
        radial-gradient(circle at 12% 88%, rgba(255,255,255,0.12), transparent 38%);
    }
    .record-profile {
      position: relative; z-index: 1;
      display: flex; align-items: center; gap: 14px;
      padding: 16px 18px;
      color: #fff;
    }
    .record-avatar-ring {
      padding: 3px;
      border-radius: 20px;
      background: linear-gradient(135deg, rgba(255,255,255,0.95), rgba(255,255,255,0.35));
      flex-shrink: 0;
    }
    .record-profile .patient-avatar {
      width: 68px; height: 68px;
      border-radius: 16px;
      font-size: 1.4rem;
      box-shadow: 0 8px 20px rgba(0,0,0,0.2);
    }
    .record-profile-main { flex: 1; min-width: 0; }
    .record-profile-main h2 {
      margin: 0 0 8px;
      font-size: 1.45rem; font-weight: 900;
      letter-spacing: -0.03em;
      line-height: 1.15;
      word-break: break-word;
    }
    .record-profile .patient-chips {
      display: flex; flex-wrap: wrap; gap: 6px;
    }
    .record-profile .patient-chip {
      font-size: 0.78rem; font-weight: 800;
      padding: 5px 11px;
      border-radius: 999px;
      background: rgba(255,255,255,0.18);
      border: 1px solid rgba(255,255,255,0.35);
      color: #fff;
    }
    .record-profile .patient-chip.loc {
      color: #e0f2fe;
    }
    .btn-glow {
      flex-shrink: 0;
      box-shadow: 0 6px 20px rgba(15,23,42,0.25);
      background: #fff !important;
      color: #1d4ed8 !important;
      font-weight: 900;
      padding: 10px 16px;
      font-size: 0.8rem;
      white-space: nowrap;
    }
    .record-scroll {
      flex: 1; min-height: 0;
      overflow-y: auto;
      overflow-x: hidden;
      -webkit-overflow-scrolling: touch;
      display: flex; flex-direction: column; gap: 10px;
      padding-bottom: 4px;
    }
    .record-section-title {
      font-size: 0.72rem; font-weight: 900;
      text-transform: uppercase; letter-spacing: 0.08em;
      color: var(--muted);
      margin: 0 0 8px 2px;
    }
    .record-stats-row {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 8px;
    }
    .record-stat {
      padding: 14px 10px;
      border-radius: 14px;
      text-align: center;
      display: flex; flex-direction: column; align-items: center; gap: 6px;
    }
    .record-stat-icon {
      width: 40px; height: 40px; border-radius: 12px;
      display: grid; place-items: center;
      font-size: 18px;
    }
    .record-stat.rc-age { background: linear-gradient(180deg, #eff6ff, #fff); border: 1px solid #bfdbfe; }
    .record-stat.rc-age .record-stat-icon { background: #dbeafe; }
    .record-stat.rc-gender { background: linear-gradient(180deg, #fdf2f8, #fff); border: 1px solid #fbcfe8; }
    .record-stat.rc-gender .record-stat-icon { background: #fce7f3; }
    .record-stat.rc-blood { background: linear-gradient(180deg, #fef2f2, #fff); border: 1px solid #fecaca; }
    .record-stat.rc-blood .record-stat-icon { background: #fee2e2; }
    .record-stat-label {
      font-size: 0.65rem; font-weight: 800;
      text-transform: uppercase; letter-spacing: 0.06em;
      color: var(--muted);
    }
    .record-stat-value {
      font-size: 1.05rem; font-weight: 900;
      color: var(--text); line-height: 1.2;
      word-break: break-word;
    }
    .record-contact-row {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 8px;
    }
    .record-detail-card {
      padding: 14px 16px;
      border-radius: 14px;
      display: flex; align-items: center; gap: 12px;
    }
    .record-detail-card.rc-phone {
      background: linear-gradient(135deg, #ecfdf5, #fff);
      border: 1px solid #bbf7d0;
    }
    .record-detail-card.rc-id {
      background: linear-gradient(135deg, #f5f3ff, #fff);
      border: 1px solid #ddd6fe;
    }
    .record-detail-card .field-icon {
      width: 38px; height: 38px; font-size: 16px; border-radius: 11px;
      flex-shrink: 0;
    }
    .record-detail-label {
      font-size: 0.65rem; font-weight: 800;
      text-transform: uppercase; letter-spacing: 0.05em;
      color: var(--muted);
    }
    .record-detail-value {
      font-size: 0.95rem; font-weight: 800;
      color: var(--text); margin-top: 2px;
      word-break: break-word;
    }
    .record-notes-card {
      padding: 14px 16px;
      border-radius: 14px;
      background: linear-gradient(180deg, #fffbeb, #ffffff);
      border: 1px solid #fde68a;
    }
    .record-notes-card .record-section-title { margin-bottom: 10px; }
    .record-notes-body {
      padding: 12px 14px;
      background: #fff;
      border-radius: 10px;
      border: 1px solid #fef3c7;
      font-size: 0.92rem; font-weight: 600;
      color: #475569; line-height: 1.55;
      min-height: 88px;
      word-break: break-word;
    }
    #page-logging.page.active,
    #page-alerts.page.active {
      display: flex;
      flex-direction: column;
      overflow: hidden;
      padding: 10px 14px 12px;
      gap: 10px;
      background: linear-gradient(180deg, #f0f4fa 0%, #e8eef6 100%);
    }
    .logging-page, .alerts-page {
      flex: 1; min-height: 0;
      display: flex; flex-direction: column; gap: 10px;
    }
    .logging-toolbar {
      flex-shrink: 0;
      padding: 14px 16px;
      display: flex; align-items: center; justify-content: space-between;
      gap: 12px; flex-wrap: wrap;
      border-radius: 16px;
    }
    .logging-controls {
      display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
    }
    .logging-controls label {
      font-size: 0.72rem; font-weight: 900;
      text-transform: uppercase; letter-spacing: 0.06em;
      color: var(--muted);
    }
    .logging-controls select {
      padding: 9px 12px; border-radius: 10px;
      border: 1px solid #e2e8f0; background: #fff;
      font-size: 0.85rem; font-weight: 700;
      font-family: inherit; color: var(--text);
    }
    .btn-log { padding: 9px 14px; font-size: 0.78rem; }
    .btn-log-start { background: #16a34a; color: #fff; }
    .btn-log-stop { background: #ef4444; color: #fff; }
    .btn-log-export { background: #2563eb; color: #fff; }
    .logging-stats {
      display: flex; align-items: center; gap: 14px;
      font-size: 0.78rem; font-weight: 800; color: var(--muted);
    }
    .log-status-pill {
      padding: 5px 12px; border-radius: 999px;
      font-size: 0.68rem; font-weight: 900;
      letter-spacing: 0.05em; text-transform: uppercase;
    }
    .log-status-pill.stopped { background: #f1f5f9; color: #64748b; }
    .log-status-pill.running { background: #dcfce7; color: #16a34a; }
    .logging-table-wrap {
      flex: 1; min-height: 0;
      overflow: hidden;
      border-radius: 16px;
      display: flex; flex-direction: column;
    }
    .logging-table-head {
      flex-shrink: 0;
      padding: 12px 16px;
      border-bottom: 1px solid #e2e8f0;
      display: flex; justify-content: space-between; align-items: center;
    }
    .logging-table-head h4 {
      font-size: 0.85rem; font-weight: 900;
      display: flex; align-items: center; gap: 8px;
    }
    .logging-table-scroll {
      flex: 1; min-height: 0; overflow: auto;
      -webkit-overflow-scrolling: touch;
    }
    .log-table {
      width: 100%; border-collapse: collapse;
      font-size: 0.78rem;
    }
    .log-table th {
      position: sticky; top: 0; z-index: 1;
      background: #f1f5f9;
      padding: 10px 12px;
      text-align: left; font-weight: 900;
      color: #475569; text-transform: uppercase;
      letter-spacing: 0.05em; font-size: 0.68rem;
      border-bottom: 2px solid #e2e8f0;
    }
    .log-table td {
      padding: 9px 12px;
      border-bottom: 1px solid #f1f5f9;
      font-weight: 600; color: var(--text);
    }
    .log-table tbody tr:nth-child(even) { background: #fafbfc; }
    .log-table tbody tr:hover { background: #eff6ff; }
    .log-empty {
      padding: 40px; text-align: center;
      color: var(--muted); font-weight: 700; font-size: 0.85rem;
    }
    .alerts-hero {
      flex-shrink: 0;
      padding: 14px 16px;
      display: flex; justify-content: space-between; align-items: center;
      gap: 12px;
      border-radius: 16px;
      background: linear-gradient(120deg, #7f1d1d 0%, #dc2626 40%, #ea580c 100%);
      color: #fff;
      box-shadow: 0 8px 28px rgba(220,38,38,0.25);
    }
    .alerts-hero h3 {
      font-size: 1.05rem; font-weight: 900;
      letter-spacing: -0.02em; margin: 0 0 3px;
      color: #fff;
    }
    .alerts-hero p {
      font-size: 0.72rem; color: rgba(255,255,255,0.85); margin: 0;
      font-weight: 600;
    }
    .alerts-status-badge {
      font-size: 0.68rem; font-weight: 900;
      padding: 8px 14px; border-radius: 999px;
      letter-spacing: 0.06em; text-transform: uppercase;
      flex-shrink: 0;
      background: rgba(255,255,255,0.95);
    }
    .alerts-status-badge.good { color: #16a34a; }
    .alerts-status-badge.watch { color: #b45309; }
    .alerts-status-badge.bad { color: #ef4444; }
    .alerts-summary {
      flex-shrink: 0;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 8px;
    }
    .alerts-summary-card {
      padding: 10px 12px;
      border-radius: 12px;
      text-align: center;
      font-size: 0.65rem; font-weight: 800;
      text-transform: uppercase; letter-spacing: 0.05em;
    }
    .alerts-summary-card span {
      display: block;
      font-size: 1.35rem; font-weight: 1000;
      letter-spacing: -0.04em;
      margin-bottom: 2px;
    }
    .alerts-summary-card.warn { background: #fff7ed; border: 1px solid #fdba74; color: #c2410c; }
    .alerts-summary-card.warn span { color: #ea580c; }
    .alerts-summary-card.ok { background: #f0fdf4; border: 1px solid #86efac; color: #15803d; }
    .alerts-summary-card.ok span { color: #16a34a; }
    .alerts-summary-card.info { background: #eff6ff; border: 1px solid #93c5fd; color: #1d4ed8; }
    .alerts-summary-card.info span { color: #2563eb; }
    .alerts-scroll {
      flex: 1; min-height: 0;
      overflow-y: auto;
      overflow-x: hidden;
      -webkit-overflow-scrolling: touch;
      display: flex; flex-direction: column; gap: 12px;
      padding-bottom: 4px;
    }
    .alerts-section-title {
      font-size: 0.7rem; font-weight: 900;
      text-transform: uppercase; letter-spacing: 0.08em;
      color: var(--muted);
      margin: 0 0 8px 2px;
      display: flex; align-items: center; gap: 6px;
    }
    .alert-row {
      display: flex; gap: 12px; align-items: flex-start;
      padding: 12px 14px;
      border-radius: 14px;
      margin-bottom: 8px;
      border: 1px solid #e8eef5;
      background: #fff;
      transition: box-shadow 0.15s;
    }
    .alert-row:last-child { margin-bottom: 0; }
    .alert-row.alert-ok { border-left: 4px solid #22c55e; background: linear-gradient(90deg, #f0fdf4, #fff); }
    .alert-row.alert-warn { border-left: 4px solid #f59e0b; background: linear-gradient(90deg, #fffbeb, #fff); }
    .alert-row.alert-bad { border-left: 4px solid #ef4444; background: linear-gradient(90deg, #fef2f2, #fff); }
    .alert-row.alert-info { border-left: 4px solid #3b82f6; background: linear-gradient(90deg, #eff6ff, #fff); }
    .alert-row-icon {
      width: 42px; height: 42px; flex-shrink: 0;
      border-radius: 12px;
      display: grid; place-items: center;
      font-size: 20px;
    }
    .alert-row.alert-ok .alert-row-icon { background: #dcfce7; }
    .alert-row.alert-warn .alert-row-icon { background: #fef3c7; }
    .alert-row.alert-bad .alert-row-icon { background: #fee2e2; }
    .alert-row.alert-info .alert-row-icon { background: #dbeafe; }
    .alert-row-body { flex: 1; min-width: 0; }
    .alert-row-top {
      display: flex; align-items: flex-start; justify-content: space-between;
      gap: 8px; margin-bottom: 4px;
    }
    .alert-row-top strong {
      font-size: 0.88rem; color: var(--text); line-height: 1.3;
    }
    .alert-pill {
      flex-shrink: 0;
      font-size: 0.58rem; font-weight: 900;
      padding: 3px 8px; border-radius: 999px;
      letter-spacing: 0.05em; text-transform: uppercase;
    }
    .alert-pill.ok { background: #dcfce7; color: #16a34a; }
    .alert-pill.warn { background: #fef3c7; color: #b45309; }
    .alert-pill.bad { background: #fee2e2; color: #ef4444; }
    .alert-pill.info { background: #dbeafe; color: #2563eb; }
    .alert-row-body > p {
      font-size: 0.78rem; color: #475569;
      line-height: 1.4; margin: 0 0 6px; font-weight: 600;
    }
    .alert-tip {
      font-size: 0.72rem; color: #64748b;
      line-height: 1.4; margin: 0;
      padding: 7px 10px;
      background: rgba(255,255,255,0.7);
      border-radius: 8px;
      border: 1px dashed #cbd5e1;
      font-weight: 600;
    }
    .alert-tip::before { content: "💡 "; }
    .alerts-suggestions {
      padding: 14px 16px;
      border-radius: 14px;
      background: linear-gradient(135deg, #eff6ff, #f0fdf4);
      border: 1px solid #bfdbfe;
    }
    .alerts-suggestions .alerts-section-title { color: #1d4ed8; }
    .alert-suggest-list {
      list-style: none; margin: 0; padding: 0;
      display: flex; flex-direction: column; gap: 8px;
    }
    .alert-suggest-list li {
      font-size: 0.78rem; font-weight: 600;
      color: #334155; line-height: 1.45;
      padding: 9px 12px 9px 32px;
      background: #fff;
      border-radius: 10px;
      border: 1px solid #e2e8f0;
      position: relative;
    }
    .alert-suggest-list li::before {
      content: "✓";
      position: absolute; left: 10px; top: 9px;
      width: 18px; height: 18px; border-radius: 50%;
      background: #dbeafe; color: #2563eb;
      font-size: 0.62rem; font-weight: 900;
      display: grid; place-items: center;
    }
    .patient-page {
      flex: 1; min-height: 0;
      display: flex; flex-direction: column;
    }
    .patient-panel {
      flex: 1; min-height: 0;
      display: flex; flex-direction: column;
      overflow: hidden;
      padding: 0;
    }
    .patient-hero {
      flex-shrink: 0;
      padding: 16px 20px;
      background: linear-gradient(120deg, #eff6ff 0%, #ecfeff 45%, #ffffff 100%);
      border-bottom: 1px solid rgba(148, 163, 184, 0.25);
      display: flex; align-items: center; gap: 18px;
    }
    .patient-avatar {
      width: 76px; height: 76px; flex-shrink: 0;
      border-radius: 18px;
      background: linear-gradient(145deg, var(--blue), var(--cyan));
      color: #fff; font-size: 1.55rem; font-weight: 900;
      display: grid; place-items: center;
      box-shadow: 0 10px 24px rgba(37, 99, 235, 0.28);
      letter-spacing: 0.02em;
    }
    .patient-hero-main { flex: 1; min-width: 0; }
    .patient-hero-main h2 {
      margin: 0 0 10px; font-size: 1.65rem; font-weight: 900;
      letter-spacing: -0.03em; line-height: 1.15;
      white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    }
    .patient-chips { display: flex; flex-wrap: wrap; gap: 8px; }
    .patient-chip {
      font-size: 0.88rem; font-weight: 800; padding: 7px 14px;
      border-radius: 999px; background: rgba(255,255,255,0.92);
      border: 1px solid #dbeafe; color: #1d4ed8;
    }
    .patient-chip.loc { border-color: #99f6e4; color: #0f766e; }
    .patient-hero .btn {
      flex-shrink: 0; padding: 12px 20px; font-size: 0.92rem;
    }
    .patient-body {
      flex: 1; min-height: 0;
      display: grid;
      grid-template-columns: 1fr 1fr 1.15fr;
      gap: 12px;
      padding: 12px 14px 14px;
      overflow: hidden;
      align-items: stretch;
    }
    .patient-section {
      background: #f8fafc;
      border: 1px solid #e8eef5;
      border-radius: 14px;
      padding: 16px 18px;
      display: flex; flex-direction: column;
      min-height: 0;
      justify-content: center;
    }
    .patient-section-title {
      font-size: 0.8rem; font-weight: 900; color: var(--muted);
      text-transform: uppercase; letter-spacing: 0.09em;
      margin: 0 0 12px; padding-bottom: 10px;
      border-bottom: 1px solid #e2e8f0;
      flex-shrink: 0;
    }
    .patient-section-rows {
      flex: 1; display: flex; flex-direction: column;
      justify-content: space-evenly; min-height: 0;
    }
    .detail-row {
      display: flex; align-items: center; justify-content: space-between;
      gap: 12px; padding: 11px 0;
      border-bottom: 1px solid rgba(226, 232, 240, 0.7);
    }
    .detail-row:last-child { border-bottom: none; }
    .detail-row .detail-label {
      display: flex; align-items: center; gap: 10px;
      font-size: 0.95rem; color: #64748b; font-weight: 700;
    }
    #page-patient .detail-row .field-icon {
      width: 32px; height: 32px; font-size: 16px; border-radius: 9px;
    }
    .detail-row .detail-value {
      font-size: 1.08rem; font-weight: 800; color: var(--text);
      text-align: right; word-break: break-word;
    }
    .notes-box {
      flex: 1; min-height: 0;
      margin-top: 6px; padding: 14px 16px;
      background: #fff; border-radius: 12px;
      border: 1px solid #e2e8f0;
      font-size: 1rem; font-weight: 600; color: #475569;
      line-height: 1.5; overflow-y: auto;
      display: flex; align-items: flex-start;
    }
    .patient-modal {
      display: none;
      position: fixed; inset: 0; z-index: 200;
      align-items: center; justify-content: center;
      padding: 16px;
    }
    .patient-modal.open { display: flex; }
    .patient-modal-backdrop {
      position: absolute; inset: 0;
      background: rgba(15, 23, 42, 0.5);
    }
    .patient-modal-card {
      position: relative; z-index: 1;
      width: min(580px, 100%);
      max-height: min(92vh, 640px);
      overflow-y: auto;
      padding: 18px 20px 20px;
    }
    .patient-modal-head {
      display: flex; justify-content: space-between; align-items: center;
      margin-bottom: 14px; padding-bottom: 10px;
      border-bottom: 1px solid #e2e8f0;
    }
    .patient-modal-head h3 {
      font-size: 0.98rem; margin: 0;
      display: flex; align-items: center; gap: 8px;
    }
    .btn-icon {
      width: 32px; height: 32px; border-radius: 10px;
      border: 1px solid #e2e8f0; background: #fff;
      color: var(--muted); font-size: 1.1rem; cursor: pointer;
      display: grid; place-items: center; line-height: 1;
    }
    #page-dashboard.page.active {
      display: flex;
      flex-direction: column;
      overflow: hidden;
      padding: 10px 14px 12px;
      gap: 10px;
      z-index: 2;
      background:
        radial-gradient(ellipse 70% 45% at 15% 0%, rgba(244,63,94,0.08), transparent),
        radial-gradient(ellipse 60% 40% at 85% 5%, rgba(37,99,235,0.1), transparent),
        radial-gradient(ellipse 50% 35% at 50% 100%, rgba(6,182,212,0.08), transparent),
        linear-gradient(180deg, #f8faff 0%, #eef2ff 100%);
    }
    .med-dash {
      flex: 1; min-height: 0;
      display: flex; flex-direction: column; gap: 10px;
    }
    .med-status-bar {
      flex-shrink: 0;
      display: flex; align-items: center;
      gap: 8px;
      padding: 8px 10px;
      border-radius: 14px;
      background: #0f172a;
      color: #e2e8f0;
      border: 1px solid #1e293b;
      overflow: hidden;
    }
    .med-status-pill {
      display: flex; align-items: center; gap: 7px;
      padding: 6px 11px;
      border-radius: 999px;
      font-size: 0.68rem; font-weight: 800;
      letter-spacing: 0.05em;
      text-transform: uppercase;
      white-space: nowrap;
      flex-shrink: 0;
    }
    .med-status-pill.live-pill-dash {
      background: rgba(34,197,94,0.15);
      border: 1px solid rgba(34,197,94,0.35);
      color: #86efac;
    }
    .med-status-pill.ward-pill-dash {
      background: rgba(59,130,246,0.12);
      border: 1px solid rgba(59,130,246,0.3);
      color: #93c5fd;
    }
    .med-status-pill.ward-pill-dash svg {
      width: 14px; height: 14px;
      stroke: currentColor; fill: none;
      stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;
    }
    .med-status-patient {
      flex: 1; min-width: 0;
      display: flex; align-items: center; gap: 8px;
      margin-left: auto;
      padding: 6px 12px 6px 8px;
      border-radius: 999px;
      background: rgba(255,255,255,0.1);
      border: 1px solid rgba(255,255,255,0.18);
    }
    .med-status-patient .med-chip-icon {
      background: #3b82f6;
      color: #fff;
      font-size: 12px;
    }
    #dashPatientName {
      font-size: 0.78rem; font-weight: 800;
      text-transform: none; letter-spacing: -0.01em;
      color: #fff;
      white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
      min-width: 0;
      flex: 1;
    }
    .med-status-dot {
      width: 8px; height: 8px; border-radius: 50%;
      background: #22c55e;
      animation: statusPulse 2s infinite;
      flex-shrink: 0;
    }
    @keyframes statusPulse {
      0%, 100% { opacity: 1; }
      50% { opacity: 0.5; }
    }
    .med-chip-icon {
      width: 28px; height: 28px; border-radius: 8px;
      background: rgba(255,255,255,0.14);
      display: grid; place-items: center; font-size: 13px;
      flex-shrink: 0;
    }
    .med-chip-icon svg {
      width: 15px; height: 15px;
      stroke: currentColor; fill: none;
      stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;
    }
    .med-vitals-grid {
      flex-shrink: 0;
      display: grid;
      grid-template-columns: 1.15fr 1.15fr 0.85fr;
      gap: 10px;
      min-height: 0;
    }
    .med-vital {
      display: flex; align-items: center; gap: 14px;
      padding: 16px 18px;
      border-radius: 16px;
      position: relative;
      min-height: 112px;
      box-shadow: none !important;
      transition: border-color 0.25s ease;
    }
    .med-vital-heart {
      background: #fff1f2;
      border: 1.5px solid #fecdd3;
    }
    .med-vital-spo2 {
      background: #eff6ff;
      border: 1.5px solid #bfdbfe;
    }
    .med-vital-icon-wrap {
      flex-shrink: 0;
      width: 56px;
      display: flex; align-items: center; justify-content: center;
    }
    .vital-icon-box {
      width: 52px; height: 52px;
      border-radius: 14px;
      display: grid; place-items: center;
      transform-origin: center;
      box-shadow: none;
    }
    .vital-icon-heart {
      background: #e11d48;
      color: #fff;
    }
    .vital-icon-heart.beating {
      animation: heartbeat var(--beat-dur, 0.85s) ease-in-out infinite;
      will-change: transform;
    }
    @keyframes heartbeat {
      0%, 100% { transform: scale(1); }
      14% { transform: scale(1.07); }
      28% { transform: scale(1); }
      42% { transform: scale(1.04); }
      56% { transform: scale(1); }
    }
    .vital-icon-heart svg {
      width: 26px; height: 26px;
      fill: currentColor;
    }
    .vital-icon-spo2 {
      background: #2563eb;
      color: #fff;
      animation: o2Breathe 3s ease-in-out infinite;
    }
    @keyframes o2Breathe {
      0%, 100% { transform: scale(1); }
      50% { transform: scale(1.06); }
    }
    .vital-icon-spo2 .spo2-symbol {
      font-size: 1rem; font-weight: 800;
      letter-spacing: -0.03em;
      text-shadow: none;
    }
    .med-vital-body { flex: 1; min-width: 0; }
    .med-vital-top {
      display: flex; justify-content: space-between; align-items: center;
      margin-bottom: 6px; gap: 6px;
    }
    .med-vital-title {
      font-size: 0.7rem; font-weight: 700;
      text-transform: uppercase; letter-spacing: 0.08em;
      color: #64748b;
      display: flex; align-items: center; gap: 6px;
    }
    .vt-ico {
      width: 18px; height: 18px; border-radius: 5px;
      display: grid; place-items: center;
      flex-shrink: 0;
    }
    .vt-ico svg {
      width: 11px; height: 11px;
      stroke: currentColor; fill: none;
      stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round;
    }
    .med-vital-heart .vt-ico { background: #ffe4e6; color: #e11d48; }
    .med-vital-spo2 .vt-ico { background: #dbeafe; color: #2563eb; }
    .dash-section-label {
      font-size: 0.68rem; font-weight: 800;
      text-transform: uppercase; letter-spacing: 0.1em;
      color: #94a3b8;
      padding: 0 2px;
      display: flex; align-items: center; gap: 6px;
    }
    .dash-section-label::before {
      content: "";
      width: 8px; height: 8px; border-radius: 50%;
      background: #22c55e;
      animation: statusPulse 2s infinite;
    }
    .med-vital-value {
      font-size: 2rem; font-weight: 800;
      letter-spacing: -0.04em; line-height: 1;
      margin-bottom: 4px;
      font-variant-numeric: tabular-nums;
      transition: color 0.3s ease;
    }
    #bpm.bpm-pulse {
      animation: bpmGlow 0.55s ease;
    }
    @keyframes bpmGlow {
      0%, 100% { opacity: 1; filter: none; }
      40% { opacity: 0.82; filter: brightness(1.15); }
    }
    .med-vital-value.vital-flash { animation: vitalSoft 0.45s ease; }
    .med-vital-heart .med-vital-value { color: #9f1239; }
    .med-vital-spo2 .med-vital-value { color: #1e40af; }
    .med-unit {
      font-size: 0.75rem; font-weight: 700;
      color: #94a3b8; margin-left: 3px;
      letter-spacing: 0.02em;
    }
    .med-range {
      font-size: 0.65rem; font-weight: 600;
      color: #94a3b8; margin-bottom: 8px;
    }
    .med-bar {
      height: 5px; border-radius: 999px;
      background: rgba(15,23,42,0.06); overflow: hidden;
    }
    .med-vital .bar-fill {
      height: 100%; border-radius: inherit;
      transition: width 0.55s cubic-bezier(0.4, 0, 0.2, 1);
      position: relative;
    }
    .med-vital-heart .bar-fill { background: #f43f5e; }
    .med-vital-spo2 .bar-fill { background: #3b82f6; }
    .med-vitals-side {
      display: flex; flex-direction: column; gap: 8px;
    }
    .med-vital-compact {
      flex: 1;
      display: flex; align-items: center; gap: 12px;
      padding: 12px 14px;
      border-radius: 14px;
      min-height: 0;
      box-shadow: none !important;
      transition: border-color 0.25s ease;
    }
    .med-vital-compact.temp {
      background: #fff7ed;
      border: 1.5px solid #fed7aa;
    }
    .med-vital-compact.room {
      background: #f0fdf4;
      border: 1.5px solid #bbf7d0;
    }
    .med-vital-compact.hum {
      background: #ecfeff;
      border: 1.5px solid #a5f3fc;
    }
    .med-compact-icon {
      width: 38px; height: 38px; flex-shrink: 0;
      border-radius: 11px;
      display: grid; place-items: center;
      box-shadow: none;
    }
    .med-vital-compact.temp .med-compact-icon { background: #ea580c; color: #fff; }
    .med-vital-compact.room .med-compact-icon { background: #16a34a; color: #fff; }
    .med-vital-compact.hum .med-compact-icon { background: #0891b2; color: #fff; }
    .med-compact-icon svg {
      width: 20px; height: 20px;
      stroke: currentColor; fill: none;
      stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;
    }
    .med-compact-body { flex: 1; min-width: 0; }
    .med-compact-body .med-vital-title { margin-bottom: 3px; font-size: 0.65rem; }
    .med-compact-value {
      font-size: 1.3rem; font-weight: 800;
      letter-spacing: -0.03em; line-height: 1.1;
      font-variant-numeric: tabular-nums;
    }
    .med-compact-value.vital-flash { animation: vitalSoft 0.45s ease; }
    @keyframes vitalSoft {
      0%, 100% { opacity: 1; }
      50% { opacity: 0.75; }
    }
    .med-vital-compact.temp .med-compact-value { color: #c2410c; }
    .med-vital-compact.room .med-compact-value { color: #15803d; }
    .med-vital-compact.hum .med-compact-value { color: #0e7490; }
    .med-compact-body .med-unit { font-size: 0.65rem; }
    .med-compact-body .med-bar { height: 4px; margin-top: 6px; }
    .med-vital-compact.temp .bar-fill { background: #f97316; }
    .med-vital-compact.room .bar-fill { background: #22c55e; }
    .med-vital-compact.hum .bar-fill { background: #06b6d4; }
    .med-vital .badge, .med-vital-compact .badge {
      position: static;
      font-size: 0.55rem;
      font-weight: 800;
      padding: 3px 8px;
      letter-spacing: 0.04em;
      border-radius: 6px;
    }
    .med-ecg {
      flex: 1 1 auto; min-height: 0;
      padding: 12px 14px 14px;
      background: #f0fdf4;
      border: 1.5px solid #bbf7d0;
      box-shadow: none !important;
    }
    .ecg-icon-wrap {
      width: 36px; height: 36px; border-radius: 10px;
      background: #16a34a;
      display: grid; place-items: center;
      color: #fff;
      box-shadow: none;
    }
    .ecg-icon-wrap svg {
      width: 18px; height: 18px;
      stroke: currentColor; fill: none;
      stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round;
    }
    .ecg-title-block {
      display: flex; align-items: center; gap: 10px;
    }
    .ecg-title-block h3 {
      font-size: 0.92rem; letter-spacing: -0.02em;
      margin: 0;
    }
    .ecg-sub {
      font-size: 0.68rem; color: var(--muted); font-weight: 600;
    }
    .ecg-overlay-labels {
      position: absolute; top: 8px; left: 10px; z-index: 2;
      display: flex; gap: 12px;
      font-size: 0.62rem; font-weight: 800;
      color: rgba(103,232,249,0.55);
      letter-spacing: 0.06em;
      text-transform: uppercase;
      pointer-events: none;
    }
    .glass {
      background: var(--card);
      border: 1px solid rgba(226,232,240,0.9);
      border-radius: var(--radius);
      box-shadow: 0 8px 24px rgba(15,23,42,0.06);
    }
    .vitals-row {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 10px;
      margin-bottom: 10px;
    }
    .vital-card { padding: 12px 14px; position: relative; overflow: hidden; }
    .vital-card .label {
      font-size: 0.68rem; font-weight: 900; color: var(--muted);
      text-transform: uppercase; letter-spacing: 0.06em;
      margin-bottom: 6px;
    }
    .vital-card .value {
      font-size: 1.85rem; font-weight: 1000;
      letter-spacing: -0.06em; line-height: 1;
      margin-bottom: 8px;
    }
    .vital-card .unit { font-size: 0.8rem; color: var(--muted); font-weight: 800; }
    .vital-card .bar {
      height: 6px; border-radius: 999px; background: #e8eef7; overflow: hidden;
    }
    .vital-card .bar-fill {
      height: 100%; border-radius: inherit;
      background: linear-gradient(90deg, var(--blue), var(--cyan));
      transition: width 0.4s ease;
    }
    .badge {
      position: absolute; top: 10px; right: 10px;
      font-size: 0.62rem; font-weight: 900; padding: 4px 8px;
      border-radius: 999px; letter-spacing: 0.05em;
    }
    .badge.good { background: var(--green-soft); color: var(--green); }
    .badge.watch { background: var(--orange-soft); color: #b45309; }
    .badge.live { background: var(--blue-soft); color: var(--blue); }
    .badge.bad { background: var(--red-soft); color: var(--red); }
    #page-dashboard .ecg-wrap {
      flex: 1 1 auto;
      min-height: 0;
      display: flex;
      flex-direction: column;
    }
    .ecg-wrap {
      flex: 1;
      min-height: 0;
      display: flex;
      flex-direction: column;
    }
    #page-dashboard .ecg-head {
      margin-bottom: 8px;
      flex-shrink: 0;
    }
    #page-dashboard .ecg-stage {
      flex: 1 1 auto;
      min-height: 0;
    }
    .ecg-head {
      display: flex; justify-content: space-between; align-items: center;
      margin-bottom: 8px; gap: 10px;
      position: relative;
    }
    .ecg-head .ecg-badge-pill {
      position: static;
      flex-shrink: 0;
      font-size: 0.62rem; font-weight: 900;
      padding: 5px 12px; border-radius: 999px;
      letter-spacing: 0.06em; text-transform: uppercase;
      background: var(--blue-soft); color: var(--blue);
    }
    .ecg-head .ecg-badge-pill.good { background: var(--green-soft); color: var(--green); }
    .ecg-head .ecg-badge-pill.watch { background: var(--orange-soft); color: #b45309; }
    .ecg-head .ecg-badge-pill.bad { background: var(--red-soft); color: var(--red); }
    .ecg-head .ecg-badge-pill.live { background: #dbeafe; color: #2563eb; }
    .ecg-head h3 { font-size: 0.92rem; letter-spacing: -0.02em; }
    .ecg-head span { font-size: 0.72rem; color: var(--muted); }
    .ecg-stage {
      flex: 1;
      min-height: 0;
      border-radius: 14px;
      overflow: hidden;
      position: relative;
      background:
        linear-gradient(rgba(103,232,249,0.06) 1px, transparent 1px),
        linear-gradient(90deg, rgba(103,232,249,0.06) 1px, transparent 1px),
        linear-gradient(180deg, #06101d, #0f172a 62%, #08111f);
      background-size: 24px 24px;
      border: 1px solid rgba(15,23,42,0.1);
    }
    .ecg-stage canvas {
      position: absolute;
      inset: 0;
      width: 100%;
      height: 100%;
      display: block;
    }
    .info-grid {
      display: grid; grid-template-columns: 1fr 1fr;
      gap: 12px;
    }
    .info-card { padding: 16px; }
    .info-card h3 {
      font-size: 0.95rem; margin-bottom: 12px;
      padding-bottom: 8px; border-bottom: 1px solid #e2e8f0;
    }
    .info-row {
      display: flex; justify-content: space-between; gap: 10px;
      padding: 8px 0; border-bottom: 1px solid #f1f5f9;
      font-size: 0.82rem;
    }
    .info-row span:first-child { color: var(--muted); font-weight: 700; }
    .info-row span:last-child { font-weight: 800; text-align: right; }
    .alert-card {
      padding: 14px; margin-bottom: 10px;
      display: grid; grid-template-columns: 36px 1fr; gap: 12px;
      align-items: start;
    }
    .alert-icon {
      width: 36px; height: 36px; border-radius: 12px;
      background: #fff; display: grid; place-items: center;
      border: 1px solid #e2e8f0; font-size: 16px;
    }
    .alert-card strong { display: block; font-size: 0.88rem; margin-bottom: 4px; }
    .alert-card p { font-size: 0.78rem; color: var(--muted); line-height: 1.4; }
    .form-grid {
      display: grid; grid-template-columns: 1fr 1fr; gap: 9px;
    }
    .form-field {
      display: flex; flex-direction: column; gap: 4px;
    }
    .form-field.full { grid-column: span 2; }
    .form-field label {
      display: flex; align-items: center; gap: 6px;
      font-size: 0.68rem; color: var(--muted); font-weight: 800;
      text-transform: uppercase; letter-spacing: 0.06em;
    }
    .field-icon {
      width: 22px; height: 22px; border-radius: 7px;
      display: grid; place-items: center;
      font-size: 12px; line-height: 1; flex-shrink: 0;
    }
    .field-icon.ic-name { background: #dbeafe; color: #2563eb; }
    .field-icon.ic-id { background: #ede9fe; color: #7c3aed; }
    .field-icon.ic-bed { background: #ccfbf1; color: #0d9488; }
    .field-icon.ic-ward { background: #ffedd5; color: #ea580c; }
    .field-icon.ic-age { background: #cffafe; color: #0891b2; }
    .field-icon.ic-blood { background: #fee2e2; color: #dc2626; }
    .field-icon.ic-gender { background: #fce7f3; color: #db2777; }
    .field-icon.ic-contact { background: #dcfce7; color: #16a34a; }
    .field-icon.ic-notes { background: #fef3c7; color: #d97706; }
    .info-label {
      display: flex; align-items: center; gap: 8px;
      color: var(--muted); font-weight: 700;
    }
    .info-label .field-icon { width: 20px; height: 20px; font-size: 11px; border-radius: 6px; }
    #page-patient .info-card h3 {
      display: flex; align-items: center; gap: 8px;
    }
    #page-patient .info-card h3 .field-icon { width: 24px; height: 24px; font-size: 13px; }
    .form-field input, .form-field select, .form-field textarea {
      padding: 9px 11px; border-radius: 10px;
      border: 1px solid #e2e8f0; background: #fff;
      font-size: 0.88rem; font-weight: 600; color: var(--text);
      font-family: inherit;
    }
    .form-field textarea { min-height: 72px; resize: vertical; }
    .form-field input:focus, .form-field select:focus, .form-field textarea:focus {
      outline: none; border-color: var(--blue);
      box-shadow: 0 0 0 3px rgba(37,99,235,0.12);
    }
    .form-actions {
      display: flex; gap: 8px; margin-top: 14px; flex-wrap: wrap;
    }
    .btn {
      padding: 10px 16px; border-radius: 10px; border: none;
      font-size: 0.82rem; font-weight: 800; cursor: pointer;
    }
    .btn-primary { background: var(--blue); color: #fff; }
    .btn-secondary { background: #e2e8f0; color: var(--text); }
    .btn-danger { background: var(--red-soft); color: var(--red); }
    .save-msg {
      font-size: 0.78rem; color: var(--green); font-weight: 800;
      margin-top: 8px; min-height: 1em;
    }
    .patient-head {
      display: flex; justify-content: space-between; align-items: center;
      margin-bottom: 12px;
    }
    .nav-text-short { display: none; }
    .patient-head h3 { font-size: 0.95rem; border: none; padding: 0; margin: 0; }
 
    /* Tablet */
    @media (max-width: 1024px) {
      .med-vitals-grid { grid-template-columns: 1fr 1fr; }
      .med-vitals-side { grid-column: span 2; flex-direction: row; }
      .med-vital-compact { flex: 1; min-width: 0; }
    }
 
    /* Mobile */
    @media (max-width: 768px) {
      body {
        align-items: stretch;
        justify-content: stretch;
      }
      .viewport-wrap {
        width: 100vw;
        width: 100dvw;
        height: 100vh;
        height: 100dvh;
        max-width: none;
        max-height: none;
        aspect-ratio: auto;
      }
      .app-shell {
        flex-direction: column;
      }
      .main {
        flex: 1;
        min-height: 0;
        order: 1;
      }
      .sidebar {
        order: 2;
        width: 100%;
        flex-shrink: 0;
        flex-direction: column;
        padding: 0;
        border-right: none;
        border-top: 1px solid rgba(255,255,255,0.1);
      }
      .sidebar-brand,
      .nav-label { display: none; }
      .sidebar-foot {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 6px 14px;
        border-top: none;
        border-bottom: 1px solid rgba(255,255,255,0.08);
        margin: 0;
      }
      .nav {
        flex-direction: row;
        flex: none;
        gap: 2px;
        padding: 4px 6px;
        padding-bottom: max(6px, env(safe-area-inset-bottom));
      }
      .nav-item {
        flex: 1;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 3px;
        padding: 8px 2px;
        min-height: 54px;
        font-size: 0.58rem;
        text-align: center;
        transform: none;
        border-radius: 10px;
      }
      .nav-item:hover { transform: none; }
      .nav-text-long { display: none; }
      .nav-text-short { display: inline; }
      .nav-icon-wrap {
        width: 32px;
        height: 32px;
        font-size: 15px;
      }
      .topbar {
        padding: 8px 12px;
        gap: 8px;
      }
      .topbar h1 { font-size: 1rem; }
      .topbar p { font-size: 0.7rem; display: none; }
      .topbar-meta { font-size: 0.68rem; }
      .topbar-meta strong { font-size: 0.78rem; }
      .page {
        padding: 10px 10px 12px;
      }
      .page.active {
        overflow-y: auto;
        overflow-x: hidden;
        -webkit-overflow-scrolling: touch;
      }
      #page-dashboard.page.active,
      #page-patient.page.active,
      #page-logging.page.active,
      #page-alerts.page.active {
        overflow-y: auto;
        padding: 8px 10px 10px;
      }
      .med-dash {
        gap: 8px;
        min-height: min-content;
      }
      .med-status-bar {
        flex-wrap: wrap;
        gap: 6px;
        padding: 8px 10px;
      }
      .med-status-patient {
        flex: 1 1 100%;
        max-width: 100%;
        width: 100%;
        justify-content: flex-start;
      }
      .ward-pill-dash { display: none; }
      .topbar-actions { gap: 8px; }
      .sound-toggle { width: 32px; height: 32px; font-size: 14px; }
      .med-vitals-grid {
        grid-template-columns: 1fr;
        gap: 8px;
      }
      .med-vitals-side {
        grid-column: auto;
        flex-direction: column;
        gap: 8px;
      }
      .med-vital {
        min-height: auto;
        padding: 12px 14px;
      }
      .med-vital-value { font-size: 2rem; }
      .med-vital-compact { min-height: auto; }
      #page-dashboard .ecg-wrap {
        flex: none;
        min-height: 0;
      }
      #page-dashboard .ecg-stage {
        flex: none;
        min-height: 200px;
        height: 42vw;
        max-height: 280px;
      }
      .record-stats-row { grid-template-columns: 1fr; }
      .record-stat {
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
        text-align: left;
        padding: 12px 14px;
        gap: 12px;
      }
      .record-stat-label { flex: 1; margin: 0; }
      .record-stat-value { font-size: 1rem; flex-shrink: 0; }
      .record-contact-row { grid-template-columns: 1fr; }
      .record-profile {
        flex-wrap: wrap;
        padding: 14px;
        gap: 12px;
      }
      .record-profile-main { width: calc(100% - 82px); }
      .record-profile-main h2 { font-size: 1.25rem; }
      .record-profile .btn-glow {
        width: 100%;
        margin-top: 2px;
      }
      .record-page { overflow: hidden; }
      #page-patient.page.active { overflow: hidden; }
      #page-alerts.page.active { overflow: hidden; }
      .alerts-summary { grid-template-columns: repeat(3, 1fr); gap: 6px; }
      .alerts-summary-card { padding: 8px 6px; font-size: 0.58rem; }
      .alerts-summary-card span { font-size: 1.15rem; }
      .alerts-hero { flex-wrap: wrap; padding: 12px 14px; }
      .alerts-hero h3 { font-size: 0.95rem; }
      .alert-row { padding: 11px 12px; gap: 10px; }
      .alert-row-icon { width: 38px; height: 38px; font-size: 17px; }
      .alert-row-top strong { font-size: 0.82rem; }
      .alert-tip { font-size: 0.68rem; padding: 6px 8px; }
      .logging-toolbar {
        flex-direction: column;
        align-items: stretch;
        gap: 10px;
      }
      .logging-controls {
        flex-direction: column;
        align-items: stretch;
      }
      .logging-controls select,
      .logging-controls .btn-log {
        width: 100%;
      }
      .logging-stats {
        justify-content: space-between;
        width: 100%;
      }
      .logging-table-scroll {
        overflow-x: auto;
        overflow-y: auto;
      }
      .log-table { min-width: 520px; font-size: 0.72rem; }
      .log-table th, .log-table td { padding: 8px 8px; }
      .form-grid { grid-template-columns: 1fr; }
      .form-field.full { grid-column: span 1; }
      .patient-modal { padding: 10px; align-items: flex-end; }
      .patient-modal-card {
        max-height: 92dvh;
        border-radius: 18px 18px 0 0;
        width: 100%;
      }
      .info-grid { grid-template-columns: 1fr; }
      .vitals-row { grid-template-columns: 1fr; }
    }
 
    /* Small phones */
    @media (max-width: 400px) {
      .med-vital-icon-wrap { width: 52px; }
      .vital-icon-box { width: 46px; height: 46px; }
      .vital-icon-heart svg { width: 22px; height: 22px; }
      .med-vital-value { font-size: 1.75rem; }
      .med-compact-value { font-size: 1.15rem; }
      .nav-item { font-size: 0.52rem; min-height: 50px; }
      .ecg-overlay-labels { font-size: 0.55rem; gap: 8px; }
      #page-dashboard .ecg-stage {
        min-height: 160px;
        height: 38vw;
      }
    }
  </style>
</head>
<body>
  <div class="viewport-wrap">
    <div class="app-shell">
      <aside class="sidebar">
        <div class="sidebar-brand">
          <div class="sidebar-logo">
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <path d="M4 12h2l2-4 3 8 2-5 2 5 3-8 2 4h2"/>
            </svg>
          </div>
          <div>
            <strong>MedMonitor</strong>
            <span>Patient Care IoT</span>
          </div>
        </div>
        <div class="nav-label">Clinical</div>
        <nav class="nav">
          <button class="nav-item active" data-page="dashboard"><span class="nav-icon-wrap"><span class="nav-icon"></span></span><span class="nav-text"><span class="nav-text-long">Vitals Monitor</span><span class="nav-text-short">Vitals</span></span></button>
          <button class="nav-item" data-page="patient"><span class="nav-icon-wrap"><span class="nav-icon"></span></span><span class="nav-text"><span class="nav-text-long">Patient Record</span><span class="nav-text-short">Patient</span></span></button>
          <button class="nav-item" data-page="logging"><span class="nav-icon-wrap"><span class="nav-icon"></span></span><span class="nav-text"><span class="nav-text-long">Data Logging</span><span class="nav-text-short">Logging</span></span></button>
          <button class="nav-item" data-page="alerts"><span class="nav-icon-wrap"><span class="nav-icon"></span></span><span class="nav-text"><span class="nav-text-long">Alerts</span><span class="nav-text-short">Alerts</span></span></button>
        </nav>
        <div class="sidebar-foot">
          <div class="live-pill"><span class="live-dot" id="liveDot"></span><span id="connText">Connecting</span></div>
          <span id="clock">--:--:--</span>
        </div>
      </aside>
 
      <div class="main">
        <header class="topbar">
          <div>
            <h1 id="pageTitle">Dashboard</h1>
            <p id="pageSubtitle">Live vitals and ECG waveform</p>
          </div>
          <div class="topbar-actions">
            <button type="button" class="sound-toggle" id="btnSoundToggle" title="Toggle heartbeat sound" aria-label="Toggle heartbeat sound">
              <svg class="sound-on" viewBox="0 0 24 24" aria-hidden="true"><path d="M11 5L6 9H2v6h4l5 4V5z"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></svg>
              <svg class="sound-off" viewBox="0 0 24 24" aria-hidden="true"><path d="M11 5L6 9H2v6h4l5 4V5z"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/></svg>
            </button>
            <div class="topbar-meta">
              <span>Last update</span>
              <strong id="lastUpdate">--</strong>
            </div>
          </div>
        </header>
 
        <div class="page-area">
          <!-- DASHBOARD -->
          <section class="page active" id="page-dashboard">
            <div class="med-dash">
              <div class="med-status-bar">
                <div class="med-status-pill live-pill-dash">
                  <span class="med-status-dot"></span>
                  <span>Live</span>
                </div>
                <div class="med-status-pill ward-pill-dash">
                  <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 21h18M5 21V7l7-4 7 4v14M9 21v-6h6v6"/></svg>
                  <span>ICU Monitor</span>
                </div>
                <div class="med-status-patient">
                  <span class="med-chip-icon">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                  </span>
                  <span id="dashPatientName">Patient Monitor</span>
                </div>
              </div>
 
              <div class="dash-section-label">Live Vitals</div>
 
              <div class="med-vitals-grid">
                <div class="med-vital med-vital-heart glass">
                  <div class="med-vital-icon-wrap">
                    <div class="vital-icon-box vital-icon-heart" id="heartIcon">
                      <svg viewBox="0 0 24 24" aria-hidden="true">
                        <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                      </svg>
                    </div>
                  </div>
                  <div class="med-vital-body">
                    <div class="med-vital-top">
                      <span class="med-vital-title"><span class="vt-ico"><svg viewBox="0 0 24 24"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" fill="currentColor" stroke="none"/></svg></span>Heart Rate</span>
                      <span class="badge watch" id="bpmBadge">WAIT</span>
                    </div>
                    <div class="med-vital-value" id="bpmWrap"><span id="bpm">--</span><span class="med-unit">BPM</span></div>
                    <div class="med-range">Normal range: 60 – 100 BPM</div>
                    <div class="bar med-bar"><div class="bar-fill" id="bpmBar" style="width:6%"></div></div>
                  </div>
                </div>
 
                <div class="med-vital med-vital-spo2 glass">
                  <div class="med-vital-icon-wrap">
                    <div class="vital-icon-box vital-icon-spo2">
                      <span class="spo2-symbol">O₂</span>
                    </div>
                  </div>
                  <div class="med-vital-body">
                    <div class="med-vital-top">
                      <span class="med-vital-title"><span class="vt-ico"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M8 12h8M10 9v6M14 9v6"/></svg></span>Blood Oxygen</span>
                      <span class="badge watch" id="spo2Badge">WAIT</span>
                    </div>
                    <div class="med-vital-value" id="spo2Wrap"><span id="spo2">--</span><span class="med-unit">% SpO₂</span></div>
                    <div class="med-range">Normal range: 95 – 100%</div>
                    <div class="bar med-bar"><div class="bar-fill" id="spo2Bar" style="width:6%"></div></div>
                  </div>
                </div>
 
                <div class="med-vitals-side">
                  <div class="med-vital-compact glass temp">
                    <div class="med-compact-icon">
                      <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M14 14.76V3.5a2.5 2.5 0 0 0-5 0v11.26a4.5 4.5 0 1 0 5 0z"/></svg>
                    </div>
                    <div class="med-compact-body">
                      <div class="med-vital-top">
                        <span class="med-vital-title"><span class="vt-ico" style="background:#ffedd5;color:#ea580c"><svg viewBox="0 0 24 24"><path d="M14 14.76V3.5a2.5 2.5 0 0 0-5 0v11.26a4.5 4.5 0 1 0 5 0z" fill="currentColor" stroke="none"/></svg></span>Body Temp</span>
                        <span class="badge watch" id="tempBadge">WAIT</span>
                      </div>
                      <div class="med-compact-value" id="bodyTempWrap"><span id="bodyTemp">--</span><span class="med-unit">°C</span></div>
                      <div class="bar med-bar"><div class="bar-fill" id="bodyTempBar" style="width:6%"></div></div>
                    </div>
                  </div>
                  <div class="med-vital-compact glass room">
                    <div class="med-compact-icon">
                      <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 10.5L12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1v-9.5z"/></svg>
                    </div>
                    <div class="med-compact-body">
                      <div class="med-vital-top">
                        <span class="med-vital-title"><span class="vt-ico" style="background:#dcfce7;color:#16a34a"><svg viewBox="0 0 24 24"><path d="M3 10.5L12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z" fill="currentColor" stroke="none"/></svg></span>Room Temp</span>
                        <span class="badge watch" id="roomBadge">WAIT</span>
                      </div>
                      <div class="med-compact-value" id="roomTempWrap"><span id="roomTemp">--</span><span class="med-unit">°C</span></div>
                      <div class="bar med-bar"><div class="bar-fill" id="roomTempBar" style="width:6%"></div></div>
                    </div>
                  </div>
                  <div class="med-vital-compact glass hum">
                    <div class="med-compact-icon">
                      <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"/></svg>
                    </div>
                    <div class="med-compact-body">
                      <div class="med-vital-top">
                        <span class="med-vital-title"><span class="vt-ico" style="background:#cffafe;color:#0891b2"><svg viewBox="0 0 24 24"><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z" fill="currentColor" stroke="none"/></svg></span>Humidity</span>
                        <span class="badge watch" id="humBadge">WAIT</span>
                      </div>
                      <div class="med-compact-value" id="humidityWrap"><span id="humidity">--</span><span class="med-unit">% RH</span></div>
                      <div class="bar med-bar"><div class="bar-fill" id="humBar" style="width:6%"></div></div>
                    </div>
                  </div>
                </div>
              </div>
 
              <div class="dash-section-label" style="margin-top:2px">ECG Waveform</div>
 
              <div class="ecg-wrap glass med-ecg">
                <div class="ecg-head">
                  <div class="ecg-title-block">
                    <div class="ecg-icon-wrap">
                      <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 12h2l2-4 3 8 2-5 2 5 3-8 2 4h2"/></svg>
                    </div>
                    <div>
                      <h3>Electrocardiogram · Lead I</h3>
                    </div>
                  </div>
                  <span class="ecg-badge-pill live" id="ecgBadge">STREAMING</span>
                </div>
                <div class="ecg-stage">
                  <div class="ecg-overlay-labels">
                    <span>1 mV/div</span>
                    <span>25 mm/s</span>
                  </div>
                  <canvas id="ecgCanvas"></canvas>
                </div>
              </div>
            </div>
          </section>
 
          <!-- PATIENT RECORD -->
          <section class="page" id="page-patient">
            <div class="record-page">
              <div class="record-banner glass">
                <div class="record-banner-bg"></div>
                <div class="record-profile">
                  <div class="record-avatar-ring">
                    <div class="patient-avatar" id="viewAvatar">?</div>
                  </div>
                  <div class="record-profile-main">
                    <h2 id="viewName">No patient saved</h2>
                    <div class="patient-chips">
                      <span class="patient-chip" id="viewId">No ID</span>
                      <span class="patient-chip loc">Bed <span id="viewBed">--</span> · Ward <span id="viewWard">--</span></span>
                    </div>
                  </div>
                  <button type="button" class="btn btn-primary btn-glow" id="btnEditPatient">✎ Edit</button>
                </div>
              </div>
 
              <div class="record-scroll">
                <div>
                  <h4 class="record-section-title">Personal Information</h4>
                  <div class="record-stats-row">
                    <div class="record-stat glass rc-age">
                      <span class="record-stat-icon"></span>
                      <span class="record-stat-label">Age</span>
                      <span class="record-stat-value" id="viewAge">--</span>
                    </div>
                    <div class="record-stat glass rc-gender">
                      <span class="record-stat-icon">⚧</span>
                      <span class="record-stat-label">Gender</span>
                      <span class="record-stat-value" id="viewGender">--</span>
                    </div>
                    <div class="record-stat glass rc-blood">
                      <span class="record-stat-icon"></span>
                      <span class="record-stat-label">Blood</span>
                      <span class="record-stat-value" id="viewBlood">--</span>
                    </div>
                  </div>
                </div>
 
                <div>
                  <h4 class="record-section-title">Contact & ID</h4>
                  <div class="record-contact-row">
                    <div class="record-detail-card glass rc-phone">
                      <span class="field-icon ic-contact"></span>
                      <div>
                        <div class="record-detail-label">Phone</div>
                        <div class="record-detail-value" id="viewContact">--</div>
                      </div>
                    </div>
                    <div class="record-detail-card glass rc-id">
                      <span class="field-icon ic-id"></span>
                      <div>
                        <div class="record-detail-label">Patient ID</div>
                        <div class="record-detail-value" id="viewIdDetail">--</div>
                      </div>
                    </div>
                  </div>
                </div>
 
                <div class="record-notes-card glass">
                  <h4 class="record-section-title"> Clinical Notes</h4>
                  <div class="record-notes-body" id="viewNotes">No notes added.</div>
                </div>
              </div>
            </div>
          </section>
 
          <div class="patient-modal" id="patientModal">
            <div class="patient-modal-backdrop" id="patientModalBackdrop"></div>
            <div class="patient-modal-card glass">
              <div class="patient-modal-head">
                <h3><span class="field-icon ic-name"></span>Edit Patient Details</h3>
                <button type="button" class="btn-icon" id="btnClosePatientModal" title="Close">×</button>
              </div>
              <form id="patientForm" class="form-grid">
                <div class="form-field">
                  <label for="inpName"><span class="field-icon ic-name"></span>Full Name</label>
                  <input type="text" id="inpName" name="name" placeholder="Enter patient name" />
                </div>
                <div class="form-field">
                  <label for="inpId"><span class="field-icon ic-id"></span>Patient ID</label>
                  <input type="text" id="inpId" name="patientId" placeholder="e.g. PT-2048" />
                </div>
                <div class="form-field">
                  <label for="inpBed"><span class="field-icon ic-bed"></span>Bed</label>
                  <input type="text" id="inpBed" name="bed" placeholder="e.g. 03" />
                </div>
                <div class="form-field">
                  <label for="inpWard"><span class="field-icon ic-ward"></span>Ward</label>
                  <input type="text" id="inpWard" name="ward" placeholder="e.g. ICU" />
                </div>
                <div class="form-field">
                  <label for="inpAge"><span class="field-icon ic-age"></span>Age</label>
                  <input type="number" id="inpAge" name="age" min="0" max="130" placeholder="Years" />
                </div>
                <div class="form-field">
                  <label for="inpBlood"><span class="field-icon ic-blood"></span>Blood Group</label>
                  <select id="inpBlood" name="bloodGroup">
                    <option value="">Select</option>
                    <option value="A+">A+</option>
                    <option value="A-">A-</option>
                    <option value="B+">B+</option>
                    <option value="B-">B-</option>
                    <option value="AB+">AB+</option>
                    <option value="AB-">AB-</option>
                    <option value="O+">O+</option>
                    <option value="O-">O-</option>
                  </select>
                </div>
                <div class="form-field">
                  <label for="inpGender"><span class="field-icon ic-gender">⚧</span>Gender</label>
                  <select id="inpGender" name="gender">
                    <option value="">Select</option>
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                    <option value="Other">Other</option>
                  </select>
                </div>
                <div class="form-field">
                  <label for="inpContact"><span class="field-icon ic-contact"></span>Contact</label>
                  <input type="text" id="inpContact" name="contact" placeholder="Phone or email" />
                </div>
                <div class="form-field full">
                  <label for="inpNotes"><span class="field-icon ic-notes"></span>Notes</label>
                  <textarea id="inpNotes" name="notes" placeholder="Medical notes, allergies, etc."></textarea>
                </div>
              </form>
              <div class="form-actions">
                <button type="button" class="btn btn-primary" id="btnSavePatient">Save Changes</button>
                <button type="button" class="btn btn-secondary" id="btnCancelPatient">Cancel</button>
                <button type="button" class="btn btn-danger" id="btnClearPatient">Clear All</button>
              </div>
              <div class="save-msg" id="saveMsg"></div>
            </div>
          </div>
 
          <!-- DATA LOGGING -->
          <section class="page" id="page-logging">
            <div class="logging-page">
              <div class="logging-toolbar glass">
                <div class="logging-controls">
                  <label for="logInterval">Interval</label>
                  <select id="logInterval">
                    <option value="2000">2 seconds</option>
                    <option value="3000">3 seconds</option>
                    <option value="5000" selected>5 seconds</option>
                    <option value="10000">10 seconds</option>
                    <option value="15000">15 seconds</option>
                    <option value="30000">30 seconds</option>
                    <option value="60000">60 seconds</option>
                  </select>
                  <button type="button" class="btn btn-log btn-log-start" id="btnLogStart">▶ Start</button>
                  <button type="button" class="btn btn-log btn-log-stop" id="btnLogStop">■ Stop</button>
                  <button type="button" class="btn btn-log btn-secondary" id="btnLogClear">Clear</button>
                  <button type="button" class="btn btn-log btn-log-export" id="btnLogExport"> Export Excel</button>
                </div>
                <div class="logging-stats">
                  <span id="logCount">0 records</span>
                  <span class="log-status-pill stopped" id="logStatus">Stopped</span>
                </div>
              </div>
              <div class="logging-table-wrap glass">
                <div class="logging-table-head">
                  <h4> Vitals Data Log</h4>
                  <span style="font-size:0.72rem;color:var(--muted);font-weight:700" id="logIntervalLabel">Every 5s</span>
                </div>
                <div class="logging-table-scroll">
                  <table class="log-table">
                    <thead>
                      <tr>
                        <th>#</th>
                        <th>Timestamp</th>
                        <th>BPM</th>
                        <th>SpO₂ (%)</th>
                        <th>Body Temp (°C)</th>
                        <th>Room Temp (°C)</th>
                        <th>Humidity (%)</th>
                      </tr>
                    </thead>
                    <tbody id="logTableBody">
                      <tr><td colspan="7" class="log-empty">No data logged yet. Press Start to begin recording.</td></tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </section>
 
          <!-- ALERTS -->
          <section class="page" id="page-alerts">
            <div class="alerts-page">
              <div class="alerts-hero glass">
                <div>
                  <h3> Clinical Alert Center</h3>
                  <p>Live sensor status, warnings & care suggestions</p>
                </div>
                <span class="alerts-status-badge good" id="alertBadge">SAFE</span>
              </div>
 
              <div class="alerts-summary">
                <div class="alerts-summary-card warn glass">
                  <span id="alertWarnCount">0</span>Warnings
                </div>
                <div class="alerts-summary-card ok glass">
                  <span id="alertOkCount">0</span>Normal
                </div>
                <div class="alerts-summary-card info glass">
                  <span id="alertInfoCount">0</span>Info
                </div>
              </div>
 
              <div class="alerts-scroll">
                <div class="alerts-section">
                  <h4 class="alerts-section-title">❤ Cardiac Monitoring</h4>
                  <div class="alert-row alert-info glass" id="alertRow1">
                    <div class="alert-row-icon" id="alertIcon1">❤</div>
                    <div class="alert-row-body">
                      <div class="alert-row-top">
                        <strong id="alertTitle1">Heart Rate</strong>
                        <span class="alert-pill info" id="alertPill1">INFO</span>
                      </div>
                      <p id="alertMsg1">Waiting for sensor data...</p>
                      <p class="alert-tip" id="alertTip1">Normal resting range: 60–100 BPM.</p>
                    </div>
                  </div>
                  <div class="alert-row alert-info glass" id="alertRow2">
                    <div class="alert-row-icon" id="alertIcon2">⚡</div>
                    <div class="alert-row-body">
                      <div class="alert-row-top">
                        <strong id="alertTitle2">ECG Waveform</strong>
                        <span class="alert-pill info" id="alertPill2">INFO</span>
                      </div>
                      <p id="alertMsg2">Checking ECG signal...</p>
                      <p class="alert-tip" id="alertTip2">Ensure RA, LA, and RL electrodes are firmly attached.</p>
                    </div>
                  </div>
                </div>
 
                <div class="alerts-section">
                  <h4 class="alerts-section-title"> Oxygen & Respiratory</h4>
                  <div class="alert-row alert-info glass" id="alertRow3">
                    <div class="alert-row-icon" id="alertIcon3">O₂</div>
                    <div class="alert-row-body">
                      <div class="alert-row-top">
                        <strong id="alertTitle3">Blood Oxygen (SpO₂)</strong>
                        <span class="alert-pill info" id="alertPill3">INFO</span>
                      </div>
                      <p id="alertMsg3">Place finger on pulse oximeter sensor.</p>
                      <p class="alert-tip" id="alertTip3">Keep hand still; normal SpO₂ is 95–100%.</p>
                    </div>
                  </div>
                </div>
 
                <div class="alerts-section">
                  <h4 class="alerts-section-title"> Temperature & Environment</h4>
                  <div class="alert-row alert-info glass" id="alertRow4">
                    <div class="alert-row-icon" id="alertIcon4"></div>
                    <div class="alert-row-body">
                      <div class="alert-row-top">
                        <strong id="alertTitle4">Body Temperature</strong>
                        <span class="alert-pill info" id="alertPill4">INFO</span>
                      </div>
                      <p id="alertMsg4">Monitoring body temperature...</p>
                      <p class="alert-tip" id="alertTip4">Normal body temp: 36.1–37.2 °C.</p>
                    </div>
                  </div>
                  <div class="alert-row alert-info glass" id="alertRow5">
                    <div class="alert-row-icon" id="alertIcon5"></div>
                    <div class="alert-row-body">
                      <div class="alert-row-top">
                        <strong id="alertTitle5">Room Environment</strong>
                        <span class="alert-pill info" id="alertPill5">INFO</span>
                      </div>
                      <p id="alertMsg5">Checking room temp and humidity...</p>
                      <p class="alert-tip" id="alertTip5">Ideal room: 20–24 °C, humidity 40–60%.</p>
                    </div>
                  </div>
                </div>
 
                <div class="alerts-section">
                  <h4 class="alerts-section-title"> System Status</h4>
                  <div class="alert-row alert-info glass" id="alertRow6">
                    <div class="alert-row-icon" id="alertIcon6"></div>
                    <div class="alert-row-body">
                      <div class="alert-row-top">
                        <strong id="alertTitle6">Device Connection</strong>
                        <span class="alert-pill info" id="alertPill6">INFO</span>
                      </div>
                      <p id="alertMsg6">Connecting to ESP32 monitor...</p>
                      <p class="alert-tip" id="alertTip6">Ensure ESP32 is powered and on the same WiFi network.</p>
                    </div>
                  </div>
                </div>
 
                <div class="alerts-suggestions glass">
                  <h4 class="alerts-section-title"> Clinical Suggestions</h4>
                  <ul class="alert-suggest-list" id="alertSuggestions">
                    <li>All systems initializing — suggestions will appear as data arrives.</li>
                  </ul>
                </div>
              </div>
            </div>
          </section>
        </div>
      </div>
    </div>
  </div>
 
  <script>
    const $ = (id) => document.getElementById(id);
    const pages = {
      dashboard: { title: "Vitals Monitor", sub: "Real-time cardiac and physiological monitoring" },
      patient: { title: "Patient Record", sub: "View and edit patient information" },
      logging: { title: "Data Logging", sub: "Record vitals at selected intervals and export" },
      alerts: { title: "Clinical Alerts", sub: "System warnings and sensor status" }
    };
    const ui = {
      clock: $("clock"), lastUpdate: $("lastUpdate"), pageTitle: $("pageTitle"), pageSubtitle: $("pageSubtitle"),
      bpm: $("bpm"), spo2: $("spo2"), bodyTemp: $("bodyTemp"),
      roomTemp: $("roomTemp"), humidity: $("humidity"),
      bpmBar: $("bpmBar"), spo2Bar: $("spo2Bar"), bodyTempBar: $("bodyTempBar"),
      roomTempBar: $("roomTempBar"), humBar: $("humBar"),
      bpmBadge: $("bpmBadge"), spo2Badge: $("spo2Badge"), tempBadge: $("tempBadge"),
      roomBadge: $("roomBadge"), humBadge: $("humBadge"),
      ecgBadge: $("ecgBadge"),
      alertBadge: $("alertBadge"),
      alertWarnCount: $("alertWarnCount"), alertOkCount: $("alertOkCount"), alertInfoCount: $("alertInfoCount"),
      alertSuggestions: $("alertSuggestions"),
      connText: $("connText"), liveDot: $("liveDot"),
      alertTitle1: $("alertTitle1"), alertMsg1: $("alertMsg1"), alertTip1: $("alertTip1"),
      alertIcon1: $("alertIcon1"), alertPill1: $("alertPill1"), alertRow1: $("alertRow1"),
      alertTitle2: $("alertTitle2"), alertMsg2: $("alertMsg2"), alertTip2: $("alertTip2"),
      alertIcon2: $("alertIcon2"), alertPill2: $("alertPill2"), alertRow2: $("alertRow2"),
      alertTitle3: $("alertTitle3"), alertMsg3: $("alertMsg3"), alertTip3: $("alertTip3"),
      alertIcon3: $("alertIcon3"), alertPill3: $("alertPill3"), alertRow3: $("alertRow3"),
      alertTitle4: $("alertTitle4"), alertMsg4: $("alertMsg4"), alertTip4: $("alertTip4"),
      alertIcon4: $("alertIcon4"), alertPill4: $("alertPill4"), alertRow4: $("alertRow4"),
      alertTitle5: $("alertTitle5"), alertMsg5: $("alertMsg5"), alertTip5: $("alertTip5"),
      alertIcon5: $("alertIcon5"), alertPill5: $("alertPill5"), alertRow5: $("alertRow5"),
      alertTitle6: $("alertTitle6"), alertMsg6: $("alertMsg6"), alertTip6: $("alertTip6"),
      alertIcon6: $("alertIcon6"), alertPill6: $("alertPill6"), alertRow6: $("alertRow6"),
      patientForm: $("patientForm"), saveMsg: $("saveMsg"),
      patientModal: $("patientModal"),
      viewAvatar: $("viewAvatar"),
      viewName: $("viewName"), viewId: $("viewId"), viewIdDetail: $("viewIdDetail"),
      viewBed: $("viewBed"), viewWard: $("viewWard"),
      viewAge: $("viewAge"), viewGender: $("viewGender"),
      viewBlood: $("viewBlood"),
      viewContact: $("viewContact"), viewNotes: $("viewNotes"),
      heartIcon: $("heartIcon"), dashPatientName: $("dashPatientName")
    };
 
    const PATIENT_KEY = "phm_patient_v1";
    const defaultPatient = {
      name: "", patientId: "", bed: "", ward: "",
      age: "", bloodGroup: "", gender: "", contact: "", notes: ""
    };
 
    const PLOT_MAX = 1023;
    const ECG_POLL_MS = 25;
    const BPM_UI_MS = 1000;
    const ECG_Y_MARGIN = 24;
    const SCROLL_STEP = 1;
    let ecgFail = 0, vitalsFail = 0;
    let connOnline = false;
    let connFailStreak = 0;
    const CONN_FAIL_LIMIT = 12;
    let canvasW = 0, canvasH = 0;
    let heightOld = 0;
    let traceReady = false;
    let ecgPollBusy = false;
    let leadsOffState = true;
    let lastVitals = { spo2: -1, finger: false, spo2Valid: false, bodyT: -999, roomT: 0, hum: 0, bme: false };
    let heartAudioCtx = null;
    let heartSoundOn = true;
    let heartSoundTimer = null;
    let lastSoundBpm = 0;
    let audioUnlocked = false;
    let latestBpm = 0;
    let displayedBpm = -1;
    let lastBpmUiTick = 0;
    let lastBeatAnimBpm = 0;
    let bpmUiReady = false;
    let prevLeadsOff = true;
    let logData = [];
    let logTimer = null;
    let logRunning = false;
    const LOG_KEY = "phm_log_v1";
    const MAX_LOG_ROWS = 500;
 
    const canvas = $("ecgCanvas");
    const ctx = canvas.getContext("2d");
 
    document.querySelectorAll(".nav-item").forEach((btn) => {
      btn.addEventListener("click", () => {
        const id = btn.dataset.page;
        document.querySelectorAll(".nav-item").forEach((b) => b.classList.remove("active"));
        document.querySelectorAll(".page").forEach((p) => p.classList.remove("active"));
        btn.classList.add("active");
        $("page-" + id).classList.add("active");
        ui.pageTitle.textContent = pages[id].title;
        ui.pageSubtitle.textContent = pages[id].sub;
        const soundBtn = $("btnSoundToggle");
        if (soundBtn) soundBtn.style.display = id === "dashboard" ? "" : "none";
        if (id === "dashboard") requestAnimationFrame(resizeCanvas);
        window.scrollTo(0, 0);
        const activePage = $("page-" + id);
        if (activePage) activePage.scrollTop = 0;
      });
    });
 
    const ecgStage = () => canvas.parentElement;
 
    function resizeCanvas() {
      const stage = ecgStage();
      if (!stage) return;
      const w = stage.clientWidth;
      const h = stage.clientHeight;
      if (w < 10 || h < 10) return;
      if (w === canvasW && h === canvasH) return;
      canvasW = w;
      canvasH = h;
      canvas.width = w;
      canvas.height = h;
      ctx.setTransform(1, 0, 0, 1, 0, 0);
      ctx.clearRect(0, 0, w, h);
      heightOld = h * 0.54;
      traceReady = false;
    }
 
    if (window.ResizeObserver && ecgStage()) {
      const ro = new ResizeObserver(() => resizeCanvas());
      ro.observe(ecgStage());
    }
    window.addEventListener("resize", resizeCanvas);
    window.addEventListener("orientationchange", () => {
      setTimeout(() => {
        resizeCanvas();
      }, 200);
    });
    requestAnimationFrame(() => requestAnimationFrame(resizeCanvas));
 
    function setBar(el, pct) { el.style.width = Math.max(6, Math.min(pct, 100)) + "%"; }
    function flashVital(el) {
      if (!el) return;
      el.classList.remove("vital-flash");
      void el.offsetWidth;
      el.classList.add("vital-flash");
    }
    function pulseBpmValue() {
      const el = ui.bpm;
      if (!el) return;
      el.classList.remove("bpm-pulse");
      void el.offsetWidth;
      el.classList.add("bpm-pulse");
    }
    function setBadge(el, text, kind) {
      el.textContent = text;
      if (el.id === "alertBadge") {
        el.className = "alerts-status-badge " + kind;
      } else if (el.id === "ecgBadge") {
        el.className = "ecg-badge-pill " + kind;
      } else {
        el.className = "badge " + kind;
      }
    }
    function fmtTime() {
      return new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
    }
    function touchUpdate() { ui.lastUpdate.textContent = "Just now"; ui.clock.textContent = fmtTime(); }
 
    function setConn(ok) {
      if (connOnline === ok) return;
      connOnline = ok;
      ui.connText.textContent = ok ? "Live" : "Offline";
      ui.liveDot.className = ok ? "live-dot" : "live-dot off";
    }
 
    function markConnSuccess() {
      connFailStreak = 0;
      ecgFail = 0;
      setConn(true);
    }
 
    function markConnFailure() {
      connFailStreak++;
      if (connFailStreak >= CONN_FAIL_LIMIT) {
        setConn(false);
      }
    }
 
    function loadPatientForm(data) {
      $("inpName").value = data.name || "";
      $("inpId").value = data.patientId || "";
      $("inpBed").value = data.bed || "";
      $("inpWard").value = data.ward || "";
      $("inpAge").value = data.age || "";
      $("inpBlood").value = data.bloodGroup || "";
      $("inpGender").value = data.gender || "";
      $("inpContact").value = data.contact || "";
      $("inpNotes").value = data.notes || "";
      updatePatientPreview(data);
    }
 
    function readPatientForm() {
      return {
        name: $("inpName").value.trim(),
        patientId: $("inpId").value.trim(),
        bed: $("inpBed").value.trim(),
        ward: $("inpWard").value.trim(),
        age: $("inpAge").value.trim(),
        bloodGroup: $("inpBlood").value,
        gender: $("inpGender").value,
        contact: $("inpContact").value.trim(),
        notes: $("inpNotes").value.trim()
      };
    }
 
    function patientInitials(name) {
      const parts = (name || "").trim().split(/\s+/).filter(Boolean);
      if (!parts.length) return "?";
      if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
      return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
    }
 
    function updatePatientPreview(data) {
      const hasPatient = !!(data.name || data.patientId);
      ui.viewName.textContent = data.name || "No patient saved";
      ui.viewAvatar.textContent = patientInitials(data.name);
      ui.viewId.textContent = data.patientId || "No ID";
      ui.viewIdDetail.textContent = data.patientId || "--";
      ui.viewBed.textContent = data.bed || "--";
      ui.viewWard.textContent = data.ward || "--";
      ui.viewAge.textContent = data.age ? data.age + " yrs" : "--";
      ui.viewGender.textContent = data.gender || "--";
      ui.viewBlood.textContent = data.bloodGroup || "--";
      ui.viewContact.textContent = data.contact || "--";
      ui.viewNotes.textContent = data.notes || (hasPatient ? "No notes added." : "No notes added.");
      updateDashPatient();
    }
 
    function openPatientModal() {
      let data = defaultPatient;
      try {
        const saved = localStorage.getItem(PATIENT_KEY);
        if (saved) data = { ...defaultPatient, ...JSON.parse(saved) };
      } catch (e) {}
      loadPatientForm(data);
      ui.saveMsg.textContent = "";
      ui.patientModal.classList.add("open");
    }
 
    function closePatientModal() {
      ui.patientModal.classList.remove("open");
      ui.saveMsg.textContent = "";
    }
 
    function savePatient() {
      const data = readPatientForm();
      if (!data.name && !data.patientId) {
        ui.saveMsg.textContent = "Enter at least a name or patient ID.";
        ui.saveMsg.style.color = "#ef4444";
        return;
      }
      try {
        localStorage.setItem(PATIENT_KEY, JSON.stringify(data));
        updatePatientPreview(data);
        ui.saveMsg.textContent = "Patient details saved.";
        ui.saveMsg.style.color = "#16a34a";
        setTimeout(closePatientModal, 400);
      } catch (e) {
        ui.saveMsg.textContent = "Could not save. Browser storage may be full.";
        ui.saveMsg.style.color = "#ef4444";
      }
    }
 
    function clearPatientForm() {
      loadPatientForm(defaultPatient);
      try { localStorage.removeItem(PATIENT_KEY); } catch (e) {}
      ui.saveMsg.textContent = "All patient data cleared.";
      ui.saveMsg.style.color = "#64748b";
      setTimeout(closePatientModal, 500);
    }
 
    function initPatientForm() {
      let data = defaultPatient;
      try {
        const saved = localStorage.getItem(PATIENT_KEY);
        if (saved) data = { ...defaultPatient, ...JSON.parse(saved) };
      } catch (e) {}
      updatePatientPreview(data);
      $("btnEditPatient").addEventListener("click", openPatientModal);
      $("btnClosePatientModal").addEventListener("click", closePatientModal);
      $("btnCancelPatient").addEventListener("click", closePatientModal);
      $("patientModalBackdrop").addEventListener("click", closePatientModal);
      $("btnSavePatient").addEventListener("click", savePatient);
      $("btnClearPatient").addEventListener("click", clearPatientForm);
      ui.patientForm.addEventListener("submit", (e) => { e.preventDefault(); savePatient(); });
    }
    initPatientForm();
 
    function loadPatientData() {
      try {
        const saved = localStorage.getItem(PATIENT_KEY);
        if (saved) return { ...defaultPatient, ...JSON.parse(saved) };
      } catch (e) {}
      return { ...defaultPatient };
    }
 
    function fmtLogTime(d) {
      return d.toLocaleString([], {
        year: "numeric", month: "2-digit", day: "2-digit",
        hour: "2-digit", minute: "2-digit", second: "2-digit"
      });
    }
 
    function captureLogRow() {
      const bpmVal = parseInt(ui.bpm.textContent, 10);
      return {
        ts: fmtLogTime(new Date()),
        bpm: (!isNaN(bpmVal) && ui.bpm.textContent !== "--") ? bpmVal : "",
        spo2: (lastVitals.spo2Valid && lastVitals.spo2 > 0) ? lastVitals.spo2 : "",
        bodyT: (lastVitals.bodyT > -100) ? lastVitals.bodyT.toFixed(1) : "",
        roomT: lastVitals.bme ? lastVitals.roomT.toFixed(1) : "",
        hum: lastVitals.bme ? lastVitals.hum.toFixed(1) : ""
      };
    }
 
    function updateLogTable() {
      const tbody = $("logTableBody");
      if (!logData.length) {
        tbody.innerHTML = '<tr><td colspan="7" class="log-empty">No data logged yet. Press Start to begin recording.</td></tr>';
        $("logCount").textContent = "0 records";
        return;
      }
      $("logCount").textContent = logData.length + " record" + (logData.length === 1 ? "" : "s");
      let html = "";
      const start = Math.max(0, logData.length - 200);
      for (let i = start; i < logData.length; i++) {
        const r = logData[i];
        html += "<tr><td>" + (i + 1) + "</td><td>" + r.ts + "</td><td>" + (r.bpm !== "" ? r.bpm : "--") +
          "</td><td>" + (r.spo2 !== "" ? r.spo2 : "--") + "</td><td>" + (r.bodyT !== "" ? r.bodyT : "--") +
          "</td><td>" + (r.roomT !== "" ? r.roomT : "--") + "</td><td>" + (r.hum !== "" ? r.hum : "--") + "</td></tr>";
      }
      tbody.innerHTML = html;
      const scroll = tbody.closest(".logging-table-scroll");
      if (scroll) scroll.scrollTop = scroll.scrollHeight;
    }
 
    function saveLogData() {
      try { localStorage.setItem(LOG_KEY, JSON.stringify(logData)); } catch (e) {}
    }
 
    function loadLogData() {
      try {
        const saved = localStorage.getItem(LOG_KEY);
        if (saved) logData = JSON.parse(saved);
      } catch (e) { logData = []; }
      updateLogTable();
    }
 
    function addLogEntry() {
      logData.push(captureLogRow());
      if (logData.length > MAX_LOG_ROWS) logData.shift();
      updateLogTable();
      saveLogData();
    }
 
    function getLogIntervalMs() {
      return parseInt($("logInterval").value, 10) || 5000;
    }
 
    function updateLogIntervalLabel() {
      const ms = getLogIntervalMs();
      const sec = ms / 1000;
      $("logIntervalLabel").textContent = "Every " + sec + "s";
    }
 
    function startLogging() {
      if (logRunning) return;
      logRunning = true;
      $("logStatus").textContent = "Recording";
      $("logStatus").className = "log-status-pill running";
      addLogEntry();
      logTimer = setInterval(addLogEntry, getLogIntervalMs());
    }
 
    function stopLogging() {
      logRunning = false;
      if (logTimer) { clearInterval(logTimer); logTimer = null; }
      $("logStatus").textContent = "Stopped";
      $("logStatus").className = "log-status-pill stopped";
    }
 
    function restartLoggingIfActive() {
      if (!logRunning) return;
      stopLogging();
      startLogging();
    }
 
    function clearLogging() {
      stopLogging();
      logData = [];
      try { localStorage.removeItem(LOG_KEY); } catch (e) {}
      updateLogTable();
    }
 
    function csvCell(v) {
      return '"' + String(v == null ? "" : v).replace(/"/g, '""') + '"';
    }
 
    function exportLogExcel() {
      if (!logData.length) {
        alert("No data to export. Start logging first.");
        return;
      }
      const p = loadPatientData();
      const rows = [];
      rows.push(["Patient Health Monitor - Vitals Data Log"]);
      rows.push([]);
      rows.push(["Patient Name", p.name || "N/A"]);
      rows.push(["Patient ID", p.patientId || "N/A"]);
      rows.push(["Bed", p.bed || "N/A"]);
      rows.push(["Ward", p.ward || "N/A"]);
      rows.push(["Age", p.age ? p.age + " years" : "N/A"]);
      rows.push(["Gender", p.gender || "N/A"]);
      rows.push(["Blood Group", p.bloodGroup || "N/A"]);
      rows.push(["Contact", p.contact || "N/A"]);
      rows.push(["Clinical Notes", p.notes || "N/A"]);
      rows.push(["Export Date", fmtLogTime(new Date())]);
      rows.push(["Logging Interval", (getLogIntervalMs() / 1000) + " seconds"]);
      rows.push(["Total Records", logData.length]);
      rows.push([]);
      rows.push(["#", "Timestamp", "BPM", "SpO2 (%)", "Body Temp (C)", "Room Temp (C)", "Humidity (%)"]);
      logData.forEach((r, i) => {
        rows.push([i + 1, r.ts, r.bpm, r.spo2, r.bodyT, r.roomT, r.hum]);
      });
      const csv = rows.map((row) => row.map(csvCell).join(",")).join("\r\n");
      const blob = new Blob(["\ufeff" + csv], { type: "application/vnd.ms-excel;charset=utf-8;" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      const date = new Date().toISOString().slice(0, 10);
      const pname = (p.name || "Patient").replace(/[^a-z0-9]/gi, "_");
      a.href = url;
      a.download = "PHM_Vitals_" + pname + "_" + date + ".xls";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
 
    function initLogging() {
      loadLogData();
      updateLogIntervalLabel();
      $("logInterval").addEventListener("change", () => {
        updateLogIntervalLabel();
        restartLoggingIfActive();
      });
      $("btnLogStart").addEventListener("click", startLogging);
      $("btnLogStop").addEventListener("click", stopLogging);
      $("btnLogClear").addEventListener("click", () => {
        if (!logData.length || confirm("Clear all logged data?")) clearLogging();
      });
      $("btnLogExport").addEventListener("click", exportLogExcel);
    }
    initLogging();
 
    function updateRoomUi(roomT, hum, bmeOk) {
      if (bmeOk) {
        ui.roomTemp.textContent = roomT.toFixed(1);
        ui.humidity.textContent = hum.toFixed(1);
        flashVital($("roomTempWrap"));
        flashVital($("humidityWrap"));
        setBar(ui.roomTempBar, Math.min(roomT * 3, 100));
        setBar(ui.humBar, hum);
        setBadge(ui.roomBadge, "NORMAL", "good");
        setBadge(ui.humBadge, "NORMAL", "good");
      } else {
        ui.roomTemp.textContent = "--";
        ui.humidity.textContent = "--";
        setBar(ui.roomTempBar, 6);
        setBar(ui.humBar, 6);
        setBadge(ui.roomBadge, "WAIT", "watch");
        setBadge(ui.humBadge, "WAIT", "watch");
      }
    }
 
    function getHeartAudioCtx() {
      if (!heartAudioCtx) {
        heartAudioCtx = new (window.AudioContext || window.webkitAudioContext)();
      }
      return heartAudioCtx;
    }
 
    async function unlockHeartAudio() {
      try {
        const ctx = getHeartAudioCtx();
        if (ctx.state === "suspended") await ctx.resume();
        const buffer = ctx.createBuffer(1, 1, 22050);
        const source = ctx.createBufferSource();
        source.buffer = buffer;
        source.connect(ctx.destination);
        source.start(0);
        audioUnlocked = true;
        if (heartSoundOn && latestBpm > 0 && !leadsOffState) startHeartSound(latestBpm);
      } catch (e) {}
    }
 
    function playMonitorBeep() {
      if (!heartSoundOn || !audioUnlocked) return;
      try {
        const ctx = getHeartAudioCtx();
        const t = ctx.currentTime;
        const master = ctx.createGain();
        master.gain.setValueAtTime(0.14, t);
        master.connect(ctx.destination);
 
        const osc1 = ctx.createOscillator();
        const g1 = ctx.createGain();
        osc1.type = "sine";
        osc1.frequency.setValueAtTime(920, t);
        osc1.frequency.exponentialRampToValueAtTime(720, t + 0.05);
        g1.gain.setValueAtTime(0, t);
        g1.gain.linearRampToValueAtTime(1, t + 0.006);
        g1.gain.exponentialRampToValueAtTime(0.001, t + 0.065);
        osc1.connect(g1);
        g1.connect(master);
        osc1.start(t);
        osc1.stop(t + 0.07);
 
        const osc2 = ctx.createOscillator();
        const g2 = ctx.createGain();
        osc2.type = "sine";
        osc2.frequency.setValueAtTime(580, t + 0.09);
        g2.gain.setValueAtTime(0, t + 0.09);
        g2.gain.linearRampToValueAtTime(0.55, t + 0.1);
        g2.gain.exponentialRampToValueAtTime(0.001, t + 0.17);
        osc2.connect(g2);
        g2.connect(master);
        osc2.start(t + 0.09);
        osc2.stop(t + 0.18);
      } catch (e) {}
    }
 
    function stopHeartSound() {
      if (heartSoundTimer) {
        clearInterval(heartSoundTimer);
        heartSoundTimer = null;
      }
      lastSoundBpm = 0;
    }
 
    function startHeartSound(bpm) {
      if (!bpm || bpm <= 0 || leadsOffState) {
        stopHeartSound();
        return;
      }
      if (!heartSoundOn) {
        stopHeartSound();
        return;
      }
      if (heartSoundTimer && lastSoundBpm === bpm) return;
      stopHeartSound();
      lastSoundBpm = bpm;
      const interval = 60000 / bpm;
      if (audioUnlocked) playMonitorBeep();
      heartSoundTimer = setInterval(() => {
        if (audioUnlocked) playMonitorBeep();
      }, interval);
    }
 
    function syncSoundToggleBtn() {
      const btn = $("btnSoundToggle");
      if (!btn) return;
      btn.classList.toggle("muted", !heartSoundOn);
      btn.title = heartSoundOn ? "Mute heartbeat sound" : "Enable heartbeat sound";
      btn.setAttribute("aria-label", btn.title);
    }
 
    function initHeartSound() {
      syncSoundToggleBtn();
      const unlockOnce = () => { unlockHeartAudio(); };
      document.addEventListener("click", unlockOnce, { once: true, passive: true, capture: true });
      document.addEventListener("touchstart", unlockOnce, { once: true, passive: true, capture: true });
      $("btnSoundToggle").addEventListener("click", async (e) => {
        e.stopPropagation();
        await unlockHeartAudio();
        heartSoundOn = !heartSoundOn;
        syncSoundToggleBtn();
        if (heartSoundOn) {
          if (latestBpm > 0 && !leadsOffState) startHeartSound(latestBpm);
        } else {
          stopHeartSound();
        }
      });
    }
    initHeartSound();
 
    function updateDashPatient() {
      try {
        const saved = localStorage.getItem(PATIENT_KEY);
        if (saved) {
          const p = JSON.parse(saved);
          if (p.name) {
            ui.dashPatientName.textContent = p.name;
            return;
          }
        }
      } catch (e) {}
      ui.dashPatientName.textContent = "Patient Monitor";
    }
 
    function setHeartBeatAnim(bpm) {
      const el = ui.heartIcon;
      if (!el) return;
      const active = bpm > 0 && !leadsOffState;
      if (!active) {
        el.classList.remove("beating");
        lastBeatAnimBpm = 0;
        stopHeartSound();
        return;
      }
      if (!el.classList.contains("beating")) el.classList.add("beating");
      if (lastBeatAnimBpm !== bpm) {
        lastBeatAnimBpm = bpm;
        el.style.setProperty("--beat-dur", (60 / bpm) + "s");
      }
      startHeartSound(bpm);
    }
 
    function applyBpmUi(bpm) {
      displayedBpm = bpm;
      if (bpm > 0) {
        const changed = ui.bpm.textContent !== String(bpm);
        ui.bpm.textContent = bpm;
        if (changed) pulseBpmValue();
        setBar(ui.bpmBar, bpm);
        setBadge(ui.bpmBadge, bpm >= 60 && bpm <= 100 ? "NORMAL" : "CHECK", bpm >= 60 && bpm <= 100 ? "good" : "watch");
        setHeartBeatAnim(bpm);
      } else {
        ui.bpm.textContent = "--";
        setBar(ui.bpmBar, 6);
        setBadge(ui.bpmBadge, "WAIT", "watch");
        setHeartBeatAnim(0);
      }
    }
 
    function maybeUpdateBpmUi(bpm) {
      latestBpm = bpm;
      const now = Date.now();
      const leadsChanged = prevLeadsOff !== leadsOffState;
      prevLeadsOff = leadsOffState;
      const urgent = bpm <= 0 || leadsOffState || leadsChanged;
      if (urgent) {
        lastBpmUiTick = now;
        bpmUiReady = false;
        applyBpmUi(bpm);
        return;
      }
      if (!bpmUiReady || now - lastBpmUiTick >= BPM_UI_MS) {
        lastBpmUiTick = now;
        bpmUiReady = true;
        applyBpmUi(bpm);
      }
    }
 
    function updateSpo2Ui(spo2, finger, spo2Valid) {
      if (finger && spo2Valid && spo2 > 0) {
        ui.spo2.textContent = spo2;
        flashVital($("spo2Wrap"));
        setBar(ui.spo2Bar, spo2);
        setBadge(ui.spo2Badge, spo2 >= 95 ? "NORMAL" : "LOW", spo2 >= 95 ? "good" : "watch");
      } else {
        ui.spo2.textContent = "--";
        setBar(ui.spo2Bar, 6);
        setBadge(ui.spo2Badge, finger ? "WAIT" : "WAIT", "watch");
      }
    }
 
    function updateBodyUi(temp) {
      if (temp > -100) {
        ui.bodyTemp.textContent = temp.toFixed(1);
        flashVital($("bodyTempWrap"));
        setBar(ui.bodyTempBar, temp * 2);
        const ok = temp >= 36.1 && temp <= 37.2;
        setBadge(ui.tempBadge, ok ? "NORMAL" : "CHECK", ok ? "good" : "watch");
      } else {
        ui.bodyTemp.textContent = "--";
        setBar(ui.bodyTempBar, 6);
        setBadge(ui.tempBadge, "WAIT", "watch");
      }
    }
 
    function setAlertRow(n, cfg) {
      const row = ui["alertRow" + n];
      const pill = ui["alertPill" + n];
      ui["alertTitle" + n].textContent = cfg.title;
      ui["alertMsg" + n].textContent = cfg.msg;
      if (ui["alertTip" + n]) ui["alertTip" + n].textContent = cfg.tip;
      if (ui["alertIcon" + n]) ui["alertIcon" + n].textContent = cfg.icon;
      pill.textContent = cfg.pill;
      pill.className = "alert-pill " + cfg.state;
      row.className = "alert-row alert-" + cfg.state + " glass";
      return cfg.state;
    }
 
    function updateAlerts(leadsOff, bpm, spo2, finger, bodyT) {
      const v = lastVitals;
      let warnN = 0, okN = 0, infoN = 0;
      const suggestions = [];
 
      function countState(s) {
        if (s === "ok") okN++;
        else if (s === "warn" || s === "bad") warnN++;
        else infoN++;
      }
 
      // 1 — Heart rate
      if (leadsOff) {
        countState(setAlertRow(1, {
          title: "Heart Rate — Leads Off",
          msg: "Cannot measure BPM without ECG electrodes.",
          tip: "Attach RA, LA, and RL pads. Clean skin with alcohol wipe first.",
          icon: "\u26A0", pill: "ALERT", state: "bad"
        }));
        suggestions.push("Re-attach all three ECG electrodes and verify cable connections.");
      } else if (bpm > 100) {
        countState(setAlertRow(1, {
          title: "Elevated Heart Rate",
          msg: bpm + " BPM detected — above normal resting range.",
          tip: "Ensure patient is at rest. Recheck in 5 minutes.",
          icon: "\u2764", pill: "CHECK", state: "warn"
        }));
        suggestions.push("Heart rate is elevated — confirm patient is resting and hydrated.");
      } else if (bpm > 0 && bpm < 60) {
        countState(setAlertRow(1, {
          title: "Low Heart Rate",
          msg: bpm + " BPM detected — below normal resting range.",
          tip: "Verify electrode placement. Consult clinician if persistent.",
          icon: "\u2764", pill: "CHECK", state: "warn"
        }));
        suggestions.push("Bradycardia detected — verify sensor contact and patient status.");
      } else if (bpm > 0) {
        countState(setAlertRow(1, {
          title: "Heart Rate Normal",
          msg: bpm + " BPM — within healthy resting range.",
          tip: "Continue routine monitoring every few minutes.",
          icon: "\u2705", pill: "NORMAL", state: "ok"
        }));
      } else {
        countState(setAlertRow(1, {
          title: "Detecting Heartbeat",
          msg: "Leads connected. Waiting for stable BPM reading.",
          tip: "Keep patient still for accurate heart rate detection.",
          icon: "\u23F3", pill: "WAIT", state: "info"
        }));
      }
 
      // 2 — ECG waveform
      if (leadsOff) {
        countState(setAlertRow(2, {
          title: "No ECG Signal",
          msg: "Waveform unavailable — leads disconnected.",
          tip: "Press electrodes firmly. Check LO+ and LO- indicator wires.",
          icon: "\u26A1", pill: "ALERT", state: "bad"
        }));
      } else {
        countState(setAlertRow(2, {
          title: "ECG Streaming Live",
          msg: "PQRST waveform updating in real time on dashboard.",
          tip: "Trace should stay centered. Report unusual spikes to clinician.",
          icon: "\u26A1", pill: "LIVE", state: "ok"
        }));
      }
 
      // 3 — SpO2
      if (!finger) {
        countState(setAlertRow(3, {
          title: "SpO\u2082 — No Finger Detected",
          msg: "Place index finger on the MAX30102 sensor.",
          tip: "Remove nail polish. Warm cold fingers before measuring.",
          icon: "O\u2082", pill: "WAIT", state: "info"
        }));
        suggestions.push("Place finger on SpO\u2082 sensor with light, steady pressure.");
      } else if (spo2 > 0 && spo2 < 90 && v.spo2Valid) {
        countState(setAlertRow(3, {
          title: "Critical Low SpO\u2082",
          msg: spo2 + "% — critically low oxygen saturation.",
          tip: "Seek immediate clinical attention. Check airway and breathing.",
          icon: "\u26A0", pill: "CRITICAL", state: "bad"
        }));
        suggestions.push("URGENT: SpO\u2082 critically low — notify clinical staff immediately.");
      } else if (spo2 > 0 && spo2 < 95 && v.spo2Valid) {
        countState(setAlertRow(3, {
          title: "Low SpO\u2082",
          msg: spo2 + "% — below normal range (95–100%).",
          tip: "Reposition finger. Ensure sensor is clean and finger is warm.",
          icon: "O\u2082", pill: "CHECK", state: "warn"
        }));
        suggestions.push("Reposition finger on oximeter — reading below 95%.");
      } else if (spo2 > 0 && v.spo2Valid) {
        countState(setAlertRow(3, {
          title: "SpO\u2082 Normal",
          msg: "Blood oxygen at " + spo2 + "% — within healthy range.",
          tip: "Maintain steady finger contact for continuous monitoring.",
          icon: "\u2705", pill: "NORMAL", state: "ok"
        }));
      } else {
        countState(setAlertRow(3, {
          title: "Calculating SpO\u2082",
          msg: "Finger detected. Algorithm stabilizing reading...",
          tip: "Hold perfectly still for 10–15 seconds.",
          icon: "O\u2082", pill: "WAIT", state: "info"
        }));
      }
 
      // 4 — Body temperature
      if (bodyT > 37.5) {
        countState(setAlertRow(4, {
          title: "Elevated Body Temperature",
          msg: bodyT.toFixed(1) + " \u00B0C — above normal (fever range).",
          tip: "Monitor for other symptoms. Notify clinician if rising.",
          icon: "\uD83C\uDF21", pill: "CHECK", state: "warn"
        }));
        suggestions.push("Body temperature elevated — monitor closely and log readings.");
      } else if (bodyT > 0 && bodyT < 35.5) {
        countState(setAlertRow(4, {
          title: "Low Body Temperature",
          msg: bodyT.toFixed(1) + " \u00B0C — below normal range.",
          tip: "Check sensor placement on skin. Keep patient warm.",
          icon: "\uD83C\uDF21", pill: "CHECK", state: "warn"
        }));
        suggestions.push("Hypothermia range detected — verify probe contact and warm patient.");
      } else if (bodyT > -100) {
        countState(setAlertRow(4, {
          title: "Body Temperature Normal",
          msg: bodyT.toFixed(1) + " \u00B0C — within normal range.",
          tip: "NTC thermistor reading stable.",
          icon: "\u2705", pill: "NORMAL", state: "ok"
        }));
      } else {
        countState(setAlertRow(4, {
          title: "Body Temp — Waiting",
          msg: "NTC thermistor sensor initializing...",
          tip: "Ensure thermistor has firm skin contact.",
          icon: "\uD83C\uDF21", pill: "WAIT", state: "info"
        }));
      }
 
      // 5 — Room environment
      if (v.bme) {
        let envState = "ok";
        let envPill = "NORMAL";
        let envTitle = "Room Environment Normal";
        let envMsg = "Room " + v.roomT.toFixed(1) + " \u00B0C \u00B7 Humidity " + v.hum.toFixed(1) + "%";
        let envTip = "Conditions within comfortable clinical range.";
        if (v.roomT > 28 || v.roomT < 18) {
          envState = "warn"; envPill = "CHECK";
          envTitle = "Room Temperature Alert";
          envMsg = "Room temp " + v.roomT.toFixed(1) + " \u00B0C — outside ideal 18–28 \u00B0C.";
          envTip = "Adjust HVAC or ventilation for patient comfort.";
          suggestions.push("Room temperature out of range — check ventilation.");
        }
        if (v.hum > 70 || v.hum < 30) {
          envState = "warn"; envPill = "CHECK";
          envTitle = "Humidity Alert";
          envMsg = "Humidity " + v.hum.toFixed(1) + "% — outside ideal 30–70%.";
          envTip = "Use dehumidifier or humidifier as needed.";
          suggestions.push("Room humidity out of range — adjust environmental controls.");
        }
        countState(setAlertRow(5, {
          title: envTitle, msg: envMsg, tip: envTip,
          icon: "\uD83C\uDFE0", pill: envPill, state: envState
        }));
      } else {
        countState(setAlertRow(5, {
          title: "BME280 Sensor Waiting",
          msg: "Room temperature and humidity sensor not ready.",
          tip: "Check BME280 I2C wiring (SDA=21, SCL=22).",
          icon: "\uD83C\uDFE0", pill: "WAIT", state: "info"
        }));
      }
 
      // 6 — Connection
      if (connOnline) {
        countState(setAlertRow(6, {
          title: "Monitor Connected",
          msg: "ESP32 live link active. Data streaming normally.",
          tip: "If readings freeze, refresh browser or check WiFi signal.",
          icon: "\uD83D\uDCF6", pill: "LIVE", state: "ok"
        }));
      } else {
        countState(setAlertRow(6, {
          title: "Monitor Offline",
          msg: "Lost connection to ESP32 health monitor.",
          tip: "Verify ESP32 power, WiFi credentials, and router range.",
          icon: "\u274C", pill: "OFFLINE", state: "bad"
        }));
        suggestions.push("Device offline — check ESP32 power and WiFi connection.");
      }
 
      ui.alertWarnCount.textContent = warnN;
      ui.alertOkCount.textContent = okN;
      ui.alertInfoCount.textContent = infoN;
 
      if (!suggestions.length) {
        suggestions.push("All vitals within normal limits. Continue routine monitoring.");
      }
      ui.alertSuggestions.innerHTML = suggestions.map((s) => "<li>" + s + "</li>").join("");
 
      const overall = warnN > 0 ? "watch" : (okN > 0 ? "good" : "watch");
      setBadge(ui.alertBadge, warnN > 0 ? "CHECK" : "SAFE", overall);
    }
 
    function valueToY(v, h, leadsOff) {
      if (leadsOff) return h * 0.54;
      const plotH = h - ECG_Y_MARGIN * 2;
      const c = Math.max(0, Math.min(PLOT_MAX, v));
      return ECG_Y_MARGIN + plotH * (1 - c / PLOT_MAX);
    }
 
    function drawEcgPoint(v, leadsOff) {
      const w = canvasW;
      const h = canvasH;
      if (w < 8 || h < 8) return;
 
      const y = valueToY(v, h, leadsOff);
 
      if (traceReady) {
        const imageData = ctx.getImageData(SCROLL_STEP, 0, w - SCROLL_STEP, h);
        ctx.putImageData(imageData, 0, 0);
        ctx.clearRect(w - SCROLL_STEP, 0, SCROLL_STEP, h);
      } else {
        traceReady = true;
        heightOld = y;
      }
 
      const x0 = Math.max(0, w - SCROLL_STEP - 1);
      const x1 = w - 1;
      ctx.beginPath();
      ctx.moveTo(x0, heightOld);
      ctx.lineTo(x1, y);
      ctx.strokeStyle = leadsOff ? "#67e8f9" : "#16a34a";
      ctx.lineWidth = 2.2;
      ctx.lineJoin = "round";
      ctx.lineCap = "round";
      ctx.stroke();
      heightOld = y;
    }
 
    function drawEcgSamples(samples, leadsOff) {
      if (!samples || !samples.length) return;
      for (let i = 0; i < samples.length; i++) {
        drawEcgPoint(samples[i], leadsOff);
      }
    }
 
    async function pollEcg() {
      if (ecgPollBusy) return;
      ecgPollBusy = true;
      try {
        const r = await fetch("/api/ecg", { cache: "no-store" });
        if (!r.ok) throw new Error("ecg");
        const d = await r.json();
        markConnSuccess();
        touchUpdate();
        leadsOffState = !!d.lo;
        maybeUpdateBpmUi(d.bpm);
        setBadge(ui.ecgBadge, d.lo ? "LEADS OFF" : "LIVE", d.lo ? "watch" : "live");
        const samples = Array.isArray(d.v) ? d.v : [d.v];
        drawEcgSamples(samples, d.lo);
        updateAlerts(leadsOffState, displayedBpm > 0 ? displayedBpm : d.bpm, lastVitals.spo2, lastVitals.finger, lastVitals.bodyT);
      } catch (e) {
        ecgFail++;
        markConnFailure();
        if (!connOnline) setBadge(ui.ecgBadge, "ERROR", "bad");
      } finally {
        ecgPollBusy = false;
      }
    }
 
    async function pollVitals() {
      try {
        const r = await fetch("/api/vitals", { cache: "no-store" });
        if (!r.ok) throw new Error("vitals");
        const d = await r.json();
        vitalsFail = 0;
        markConnSuccess();
        touchUpdate();
        lastVitals = { spo2: d.spo2, finger: d.finger, bodyT: d.bodyT, roomT: d.roomT, hum: d.hum, bme: d.bme, spo2Valid: !!d.spo2Valid };
        updateSpo2Ui(d.spo2, d.finger, d.spo2Valid);
        updateBodyUi(d.bodyT);
        updateRoomUi(d.roomT, d.hum, d.bme);
        const bpm = displayedBpm > 0 ? displayedBpm : latestBpm;
        updateAlerts(leadsOffState, bpm > 0 ? bpm : -1, d.spo2, d.finger, d.bodyT);
      } catch (e) {
        vitalsFail++;
        markConnFailure();
      }
    }
 
    setInterval(() => { ui.clock.textContent = fmtTime(); }, 1000);
    setInterval(pollEcg, ECG_POLL_MS);
    setInterval(pollVitals, 1500);
    pollEcg();
    pollVitals();
  </script>
</body>
</html>
)rawliteral";
 
#endif

Testing & Demo of ESP32 Patient Health Monitor

After completing the hardware connection and uploading the code, the ESP32 patient health monitor is ready for testing.

When the device is powered on, open the Serial Monitor at 115200 baud. The ESP32 connects to Wi-Fi and prints the local IP address. You should see sensor initialization messages such as ADS1115 OK, BME280 OK, and MAX30102 OK.

The Serial Monitor also prints debug data every 2 seconds: room temperature, humidity, body temperature, SpO₂, ECG plot value, raw ADC, voltage, BPM, and lead status.


Accessing the Dashboard

After the ESP32 connects to the Wi-Fi network, note the IP address from the Serial Monitor. Enter this IP in a web browser on any device connected to the same Wi-Fi network to open the MedMonitor live health dashboard.

ESP32 Patient Health Monitor Dashboard

Fig: ESP32 Patient Health Monitor Dashboard

The Vitals Monitor page shows live heart rate, SpO₂, body temperature, room temperature, humidity, and a scrolling ECG waveform panel. A speaker icon in the top bar toggles synchronized heartbeat monitor sound.

From the left-side menu, we can open Vitals Monitor, Patient Record, Data Logging, and Alerts.


ECG Waveform & Heart Rate

Attach the ECG electrodes (RA, LA, RL) with good skin contact. The dashboard ECG panel shows a live scrolling trace with PQRST-style cardiac complexes when leads are connected.

AD8232 Electrode Placement on Body
Fig: AD8232 Electrode Placement on Body

If electrodes are removed, the LO+ / LO− pins detect lead-off and the dashboard shows “LEADS OFF” with a flat cyan trace. BPM calculation pauses until valid ECG signal returns.


SpO₂ and Temperature Monitoring

Place a finger on the MAX30102 sensor to measure blood oxygen. You may wrap the sensor around the finger. Do not wrap too tightly.

Finger placement on MAX30102
Fig: Finger placement on MAX30102

Body temperature is read from the NTC thermistor probe on ADS1115 AIN1. Attach the thermistor on any part of the body. You may use something to wrap the sensor and fix properly on body.

Temperature Sensor Placement on Body
Fig: Temperature Sensor Placement on Body

Room temperature and humidity are displayed from the BME280.


Patient Record & Data Logging

The Patient Record page stores patient details.


You may click on Edit details to enter the patient details on this section.


The Data Logging page records vitals at selectable intervals and exports to Excel with patient information at the top.


Clinical Alerts

The Alerts page monitors cardiac rhythm, SpO₂, body temperature, room environment, and Wi-Fi connection with clinical suggestion tips and summary counters.



Applications

  • Remote patient vitals monitoring prototype
  • IoT healthcare and biomedical engineering education
  • Home wellness tracking and fitness experiments
  • Hospital ward environmental + vitals dashboard demo
  • Research projects on ECG signal acquisition and web visualization
Note: This project is intended for educational and prototyping purposes only. It is not a certified medical device and should not be used for clinical diagnosis or treatment decisions.

Video Tutorial & Guide

Post a Comment