Project Overview
ESP32 + AD8232 Live ECG in Your Browser: Sample an AD8232 heart monitor at a steady 250 Hz on an ESP32, detect each heartbeat on the board, and stream the ECG trace to any phone or laptop browser over a WebSocket. A canvas plot shows the last five seconds of your ECG with the heart rate in large digits and a warning when an electrode comes loose.
- Time: about 1.5 hours
- Skill level: Intermediate
- What you will build: A wireless ECG viewer with a timed sampling task, a slope-energy beat detector with an adaptive threshold, leads-off detection, and a self-contained web page served by the ESP32.
Parts List
From ShillehTek
- AD8232 ECG module kit - provides the analog ECG output and leads-off signals.
- 3-lead ECG/EKG/EMG electrode cable - a spare cable, or for a second station.
- Electrode pads, 5-pack - adhesive electrodes for reliable skin contact.
- ESP32 Dev Board 4MB CP2102 USB-C (38-pin) - samples the ECG and serves the web viewer.
- ADuM3160 USB isolator module - isolates USB when you must connect a computer while wearing electrodes.
- 830-point breadboard - makes the wiring quick and stable.
- Dupont jumper wires - connects the AD8232 pins to the ESP32 GPIO.
External
- A USB power bank to run the ESP32 while you wear the electrodes
- A phone, tablet or laptop on the same Wi-Fi network
Note: this is an educational project, not a medical device, and it must not be used for diagnosis. While the electrodes are on your body, power the ESP32 from a power bank, or put the ADuM3160 between the ESP32 and the computer if you need the USB connection.
Step-by-Step Guide
Step 1 - Decide how the board is powered
Goal: Keep your body away from mains-referenced equipment.
What to do: A laptop on its charger, a desktop PC and a USB wall adapter are all ways for a fault on the mains side to reach the electrodes. The safest setup is a USB power bank: the ESP32 streams over Wi-Fi, so it needs no cable to the computer at all.
If you need uploading and debugging while you are connected, plug the ADuM3160 into the computer and the ESP32 into the isolator. Its isolated DC-DC converter powers the ESP32 side, and USB data crosses the barrier at full speed.
Expected result: A plan: power bank while wearing the electrodes, isolator whenever USB is unavoidable.
Step 2 - Wire the AD8232 to the ESP32
Goal: Connect the analog output and the leads-off signals.
What to do:
- AD8232 3.3V → ESP32 3V3, GND → GND
- OUTPUT → GPIO36 (an ADC1 input, which keeps working while Wi-Fi is on)
- LO+ → GPIO32, LO- → GPIO33
- SDN → leave unconnected or tie to 3V3 (pulling it low shuts the AD8232 down)
Expected result: Five wires between the boards; with no electrodes attached the LO pins read high.
Step 3 - Place the electrodes
Goal: A clean single-lead ECG.
What to do: Clean the skin and snap the pads on before sticking them down. Put the red lead (RA) just below the right collarbone, the yellow lead (LA) below the left collarbone, and the green lead (RL) on the lower right side of the abdomen.
Plug the cable into the AD8232's jack, sit still and breathe normally: movement and muscle tension show up as noise.
Expected result: On most AD8232 boards the on-board LED starts pulsing with your heartbeat.
Step 4 - Upload the sketch
Goal: Sample, detect beats and serve the viewer.
What to do: Install the ESP32 board package (core 3.x) and the WebSockets library by Markus Sattler. Set your Wi-Fi details and upload.
Code:
// ESP32 + AD8232: 250 Hz ECG streamed to a browser over WebSocket, with on-board heart-rate detection.
// Libraries: "WebSockets" by Markus Sattler (WebSocketsServer.h). Not a medical device.
#include <WiFi.h>
#include <WebServer.h>
#include <WebSocketsServer.h>
const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASS = "YOUR_PASSWORD";
const int PIN_ECG = 36; // AD8232 OUTPUT -> GPIO36 (ADC1, safe to use with Wi-Fi)
const int PIN_LO_P = 32; // AD8232 LO+
const int PIN_LO_N = 33; // AD8232 LO-
const int FS = 250; // samples per second
WebServer server(80);
WebSocketsServer ws(81);
// ---- sample ring buffer shared between the sampler task and loop() ----
const int RB = 512;
volatile uint16_t ring[RB];
volatile int head = 0;
int tail = 0;
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
volatile bool leadsOff = true;
volatile int bpmShared = 0;
// ---- heart-rate detector (slope energy + adaptive threshold) ----
float baseline = 2048, lpBuf[5], sqBuf[38], mwi = 0, env = 0;
float lpHist[3];
int lpPos = 0, sqPos = 0, samplesSinceBeat = 10000;
bool above = false;
int rr[5], rrCount = 0;
void resetDetector() {
memset(lpBuf, 0, sizeof lpBuf); memset(sqBuf, 0, sizeof sqBuf); memset(lpHist, 0, sizeof lpHist);
mwi = env = 0; samplesSinceBeat = 10000; above = false; rrCount = 0; bpmShared = 0;
}
int medianRR() {
int n = rrCount < 5 ? rrCount : 5, t[5];
for (int i = 0; i < n; i++) t[i] = rr[i];
for (int i = 1; i < n; i++) for (int j = i; j > 0 && t[j] < t[j - 1]; j--) { int x = t[j]; t[j] = t[j - 1]; t[j - 1] = x; }
return t[n / 2];
}
void detect(float x) {
baseline += (x - baseline) * 0.008f; // follows breathing and electrode drift
float hp = x - baseline;
lpBuf[lpPos] = hp; lpPos = (lpPos + 1) % 5; // 5-point average: a notch at 50 Hz when FS = 250
float lp = (lpBuf[0] + lpBuf[1] + lpBuf[2] + lpBuf[3] + lpBuf[4]) / 5.0f;
float d = lp - lpHist[1]; // slope over two samples
lpHist[1] = lpHist[0]; lpHist[0] = lp;
float sq = d * d; // squaring favours the steep QRS edges
mwi += (sq - sqBuf[sqPos]) / 38.0f; // 150 ms moving-window integration
sqBuf[sqPos] = sq; sqPos = (sqPos + 1) % 38;
env = mwi > env ? mwi : env * 0.998f; // peak envelope, about 2 s decay
samplesSinceBeat++;
float th = 0.35f * env;
if (!above && mwi > th && samplesSinceBeat > FS / 4) { // 250 ms refractory period
above = true;
int interval = samplesSinceBeat;
samplesSinceBeat = 0;
if (interval >= FS * 60 / 220 && interval <= FS * 60 / 30) { // 30 to 220 BPM
for (int i = 4; i > 0; i--) rr[i] = rr[i - 1];
rr[0] = interval;
if (rrCount < 5) rrCount++;
if (rrCount >= 3) bpmShared = (int)lroundf(60.0f * FS / medianRR());
}
} else if (above && mwi < 0.5f * th) {
above = false;
}
if (samplesSinceBeat > FS * 3) bpmShared = 0; // no beat for 3 s
}
void sampleOnce() {
bool off = digitalRead(PIN_LO_P) == HIGH || digitalRead(PIN_LO_N) == HIGH;
uint16_t v = off ? 0 : (uint16_t)analogRead(PIN_ECG);
if (off && !leadsOff) resetDetector();
leadsOff = off;
if (!off) detect(v);
portENTER_CRITICAL(&mux);
ring[head] = v;
head = (head + 1) % RB;
portEXIT_CRITICAL(&mux);
}
void samplerTask(void*) {
TickType_t last = xTaskGetTickCount();
for (;;) {
vTaskDelayUntil(&last, pdMS_TO_TICKS(1000 / FS)); // exactly every 4 ms
sampleOnce();
}
}
const char PAGE[] PROGMEM = R"HTML(<!DOCTYPE html>
<html><head><meta name='viewport' content='width=device-width,initial-scale=1'>
<title>ESP32 ECG</title>
<style>body{font-family:sans-serif;background:#111;color:#eee;margin:12px}
canvas{width:100%;height:300px;background:#000;border:1px solid #333}
#bpm{font-size:42px;color:#4f4}#st{color:#fa0}</style></head>
<body><h2>ESP32 + AD8232 ECG</h2>
<div><span id='bpm'>--</span> BPM <span id='st'></span></div>
<canvas id='c' width='1000' height='300'></canvas>
<p>Educational demo only, not for diagnosis.</p>
<script>
const N=1250, data=new Array(N).fill(2048); let pos=0;
const c=document.getElementById('c'), g=c.getContext('2d');
const ws=new WebSocket('ws://'+location.hostname+':81/');
ws.onmessage=e=>{const m=JSON.parse(e.data);
for(const v of m.s){data[pos]=v;pos=(pos+1)%N;}
document.getElementById('bpm').textContent=m.bpm>0?m.bpm:'--';
document.getElementById('st').textContent=m.off?'leads off: check the electrodes':'';};
function draw(){let lo=4095,hi=0;for(const v of data){if(v<lo)lo=v;if(v>hi)hi=v;}
const span=Math.max(hi-lo,50);g.fillStyle='#000';g.fillRect(0,0,c.width,c.height);
g.strokeStyle='#4f4';g.beginPath();
for(let i=0;i<N;i++){const v=data[(pos+i)%N];const x=i*c.width/N;
const y=c.height-10-(v-lo)/span*(c.height-20);if(i)g.lineTo(x,y);else g.moveTo(x,y);}
g.stroke();requestAnimationFrame(draw);}
draw();
</script></body></html>)HTML";
void setup() {
Serial.begin(115200);
pinMode(PIN_LO_P, INPUT);
pinMode(PIN_LO_N, INPUT);
analogReadResolution(12);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) delay(250);
Serial.print("Open http://");
Serial.println(WiFi.localIP().toString());
server.on("/", []() { server.send(200, "text/html", PAGE); });
server.begin();
ws.begin();
xTaskCreatePinnedToCore(samplerTask, "ecg", 4096, NULL, 3, NULL, 1);
}
void loop() {
server.handleClient();
ws.loop();
static unsigned long lastSend = 0;
if (millis() - lastSend < 40) return; // 25 messages per second, 10 samples each
lastSend = millis();
String msg = "{\"s\":[";
int n = 0;
while (true) {
portENTER_CRITICAL(&mux);
bool empty = (tail == head);
uint16_t v = empty ? 0 : ring[tail];
portEXIT_CRITICAL(&mux);
if (empty) break;
tail = (tail + 1) % RB;
if (n++) msg += ',';
msg += v;
}
msg += "],\"bpm\":";
msg += (int)bpmShared;
msg += ",\"off\":";
msg += leadsOff ? 1 : 0;
msg += "}";
if (n) ws.broadcastTXT(msg);
}
A FreeRTOS task wakes exactly every 4 ms with vTaskDelayUntil(), so the web server never disturbs the sample rate. The beat detector follows the classic recipe: remove the baseline drift, smooth with a 5-point average (which also cancels 50 Hz mains at 250 samples per second), take the slope, square it so the steep QRS edges stand out, and integrate over 150 ms. A beat is declared when that energy crosses 35 percent of its recent peak, with a 250 ms refractory period, and the heart rate is the median of the last five beat intervals. The page uses only single quotes inside the HTML, which keeps the C++ string readable.
Expected result: The Serial Monitor prints the address to open, such as http://192.168.1.50.
Step 5 - Open the viewer
Goal: Watch your ECG live.
What to do: Open the address in a browser on the same network. The page connects to the WebSocket on port 81 and receives 25 messages a second, each carrying ten new samples, the current heart rate and the leads-off flag. The trace auto-scales, and if an electrode comes loose the page says so and the heart rate resets until the signal is back.
Expected result: A scrolling ECG trace with a heart rate that settles within a few seconds.
Step 6 - Fix a noisy trace
Goal: Get the cleanest signal you can.
What to do: Most noise comes from the electrodes and the body, not the code. Use fresh pads, keep the cable away from power cords, and stay still. The 5-point average nulls 50 Hz exactly; in 60 Hz countries the AD8232 board's own filtering and good contact do most of the work. If the heart rate jumps around during movement, that is muscle noise: wait for it to settle.
Expected result: Clear P, QRS and T waves and a steady heart rate while you sit still.
Conclusion
You built a wireless ECG viewer: an AD8232 sampled at a steady 250 Hz by a FreeRTOS task, an on-board beat detector, and a browser page fed over a WebSocket, powered in a way that keeps your body isolated from mains equipment.
Want the exact parts used in this build? Grab them from ShillehTek.com. If you want help customizing this project or building something for your product, check out our IoT consulting services.
Credit: This tutorial is based on Andrewf1 on Hackster.io. The original Cardiograph project served as the reference for this ShillehTek version. The product photos are from the ShillehTek store.
Credits
This tutorial is based on Andrewf1 on Hackster.io. The original Cardiograph project by Andrewf1, which samples an ECG signal on an ESP32 and plots it on a web page, served as the reference for this ShillehTek version. The product photos are from the ShillehTek store. We thank them for their excellent work in the maker community.









