In this Detailed tutorial we are going to explain how you can interface ECG sensor module (AD8232) with Arduino development board or ESP 32 Bluetooth and WiFi board to get the ECG(Electro Cardio Gram) of a person on the serial Plotter, or over the internet and Bluetooth connection with the help of ESP 32 and add few more sensors to build an IoT health monitoring system project .
Before getting started lets learn and clear the basic questions like
Table of Contents
What is ECG and How the ECG sensor works?
What is ECG and how to check?
The EKG or ECG (Electrocardiogram) is a non-invasive diagnostic test that assesses heart rhythm and function through a recording of the electrical activity of the heart that occurs with each heartbeat. This electrical activity is recorded from the patient’s body surface and is drawn on a paper using a graphical representation or tracing, where different waves are observed that represent the electrical stimuli of the atria and ventricles. The device with which the electrocardiogram is obtained is called an electrocardiograph.
Also Read: Build Digital Thermometer using LM35 and Arduino
Features of AD8232 ECG sensor and its working principle
The AD8232 module allows recording the electrical activity of the heart, by obtaining an electrocardiogram or ECG.
ECG sensor obtain signals from heart beats because electrical signals are transmitted through specific pathways within the heart, causing the heartbeat. This electrical activity can be collected through electrodes placed on the skin, specifically on the front of the chest, on the arms and legs.
The AD8232 sensor module is integrated with specially calibrated signal amplifiers and noise filters for ECG signals. The module suppresses the 60Hz noise generated by household electricity. As the output of the module is analog type, it is necessary to solder the header pins and connect the module to a microcontroller which has analog input pins like Arduino, ESP32, ESP8266 NodeMCU, or others. Within the program we must perform the analog to digital conversion, So we can observe the ECG on the Arduino IDE plotter.
It is recommended for patient safety to power the module using a battery and not from a source connected to the household power supply.
Note: This is not a medically certified device, so it should be used for experiments only and not for clinical use.
Related article: DIY Pulse Oximeter by interfacing MAX30100 sensor with Arduino
How to Read an ECG:
The normal rhythm of an ECG is formed by a P wave, a QRS complex and a T wave. To interpret an electrocardiogram, the presence of these waves, their shape and duration, as well as the ST segment (time that elapses between the end of depolarization and the beginning of repolarization of the ventricles, measures less than 1 mm, if it is greater than 1 mm it indicates infarction or ischemia).
The P waves allow us to know the time between the heartbeats, it is represented as a straight line between the lowest and the highest point. The T wave represents the small perceptible beat after the first and marks the end of the heartbeat. The time elapsed between one and the other must be fairly regular throughout the entire test, if on the contrary, during the test we see that the elapsed time is variable, this indicates an irregularity in the heartbeat.
Required Components(Bill of Materials):
Now lets take a look at what are the components required for this project.
Product Name | Quantity | ![]() | ![]() |
---|---|---|---|
AD8232 ECG sensor Module Kit | 1 | https://amzn.to/3gVeezY | https://amzn.to/37ieCqX |
Arduino Uno development Board (Method 1) | 1 | https://amzn.to/3BuYFbY | https://amzn.to/3638aTS |
ESP 32 WiFi and Bluetooth Board (Method 2 only)(IOT) | 1 | https://amzn.to/3s0Sut6 | https://amzn.to/3Kw2np2 |
Few Connecting Wires | https://amzn.to/3H2BV4e | https://amzn.to/3J0WVu2 |
AD8232 Pinout Diagram:
For more details about this sensor, refer to the detailed Datasheet here. AD8232 Datasheet
Technical Specifications of ECG sensor
- Analog type output
- Operating voltage: 3.3V DC
- Low current consumption: 170 uA
- Noise rejection at 60Hz: 80dB
- High gain (G = 100), with DC current blocking
- Integrated Right Leg Amplifier (RLD)
- RFI filtering
- Shutdown pin
- Electrode input: Mini Plug 3.5mm
- Configurations: 2 or 3 electrodes
We are interfacing the components in 3 methods to show the ECG graph on
- Serial Plotter,
- Over Bluetooth and
- Over the internet.
So you can choose the development board according to the requirement.
Method 1: Interfacing AD8232 ECG sensor with Arduino to show the graph on Serial plotter
In this method we are connecting ECG sensor to Arduino with the help of few connecting wire as shown in the below Schematic diagram.
As per the above connection diagram the sensor just has the hole pads, so we need to solder wires to it. The best practice is to solder headers on the board. so, you can use it bread board or with female jumper wires.
Here we connected the 3.3v & GND for sensor to 3.3v &GND of Arduino respectively, OUTPUT pin of sensor to A0 of Arduino and Finally LO- & LO+ are connected to 11 & 10 respectively.
Sensor electrode plate placement on human body
Here it is mandatory to place the sensor adhesive electrode pads as shown in the above image, the colored cables will help you to identify where to place. How closer the pads are to the heart that better the measurements we get.
Next step is to upload the code to the Arduino to make it work. Below are the two codes where one is to display the raw Analog input from sensor, and another one uses Processing IDE.
Source Code for Arduino Serial Plotter:
/****************************************************************************** Heart_Rate_Display.ino Publisher: https://www.circuitschools.com ******************************************************************************/ void setup() { // initialize the serial communication: Serial.begin(9600); pinMode(10, INPUT); // Setup for leads off detection LO + pinMode(11, INPUT); // Setup for leads off detection LO - } void loop() { if((digitalRead(10) == 1)||(digitalRead(11) == 1)){ Serial.println('!'); } else{ // send the value of analog input 0: Serial.println(analogRead(A0)); } //Wait for a bit to keep serial data from saturating delay(1); }
After uploading the code to Arduino, Open serial plotter at baud rate 9600 to view the ECG as shown below.
Source code for Processing IDE.
Code for ECG graph for Arduino on Processing IDEIf you get an error using the above code edit the below line at line 50. where [2] is COM port number replace it with the port number of the Arduino connected to your PC.
myPort = new Serial(this, Serial.list()[2], 9600);
After Uploading the code the output will be shown as below image.
Method 2: Interfacing AD8232 ECG sensor with ESP32 to show the graph over Bluetooth on a Android Mobile.
In this method we are connecting the AD8232 Sensor with ESP32 Wi-Fi and Bluetooth development board to get the ECG graph over Bluetooth with the help of Bluetooth Terminal/Graphics android application found in GooglePlay store.
ESP32 Pinout:
Now Connect the ESP32 with sensor as shown in the below Schematic diagram.
Circuit diagram for interfacing ESP 32 and AD8232 Sensor for Bluetooth connection
As per the above connection diagram, we connected 3.3v & GND of sensor to 3.3v &GND of ESP32 respectively, OUTPUT pin of sensor to VP(A0)(pin5) of ESP32 and Finally LO- & LO+ are connected to pin40(RX0) & pin41(TX0) respectively.
After connecting upload the below code:
Source Code for Graph over Bluetooth:
/****************************************************************************** Heart_Rate_Display over Bluetooth Publisher: https://www.circuitschools.com ******************************************************************************/ #include "BluetoothSerial.h" #define LED_BUILTIN 2 //pin with LED to turn on when BT connected BluetoothSerial ESP_BT; // Object for Bluetooth // global vars boolean BT_cnx = false; void callback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param){ if(event == ESP_SPP_SRV_OPEN_EVT){ Serial.println("Client Connected"); digitalWrite(LED_BUILTIN, HIGH); BT_cnx = true; } if(event == ESP_SPP_CLOSE_EVT ){ Serial.println("Client disconnected"); digitalWrite(LED_BUILTIN, LOW); BT_cnx = false; ESP.restart(); } } void setup() { // initialize digital pin 2 as an output. pinMode(LED_BUILTIN, OUTPUT); // initialize the serial communication: Serial.begin(9600); Serial.println(); // blank line in serial ... pinMode(41, INPUT); // Setup for leads off detection LO + pinMode(40, INPUT); // Setup for leads off detection LO - // initialize the serial BT communication: ESP_BT.register_callback(callback); if(!ESP_BT.begin("ESP32_ECG")){ Serial.println("An error occurred initializing Bluetooth"); }else{ Serial.println("Bluetooth initialized... Bluetooth Device is Ready to Pair..."); } } void loop() { if((digitalRead(40) == 1)||(digitalRead(41) == 1)){ Serial.println('!'); ESP_BT.println('!'); } else{ // send the value of analog input 0 to serial: Serial.println(analogRead(A0)); //Do the same for blutooth if(BT_cnx){ ESP_BT.print('E'); //make the app Blutooth Graphics (https://play.google.com/store/apps/details?id=com.emrctn.BluetoothGraphics&hl=en_US) work (as specified by the app) ESP_BT.println(analogRead(A0)); } } //Wait a little to keep serial data from saturating delay(1); }
After uploading download the Bluetooth Terminal/Graphics android application found in GooglePlay store.
Download: link
After downloading open the application and click on side menu and choose connect to device and select “ESP32_ECG”. As you select the device will be connect to application and the ECG graph is shown as the below image.
Method 3: Interfacing AD8232 ECG sensor with ESP32 to show the graph over Internet.
In this method, learn how to connect the ESP32 with ECG sensor and display the data i.e, ECG graph over internet and can be seen live from anywhere around the world. Here you can use any IOT cloud platforms like Blynk, Thingsboard, Ubidots, AWS, Google cloud. the only technique is to send the data to them using there respective syntax codes.
Before using these you need to keep in mind that as this is over internet there would be small latency delays from device to the cloud to display the data on the graph.
Now connect the Boards ESP32 and ECG sensor as shown in the below Schematic diagram.
Circuit Diagram for data over internet.
In this example we are going to use UbiDots cloud platform to display data over internet.
Now upload the below code and edit few lines of code to change few parameters listed below
Source Code:
If you get any error regarding PubSubClient update the library from this download link.
/**************************************** * Include Libraries ****************************************/ #include <WiFi.h> #include <PubSubClient.h> #define WIFISSID "your WIFI SSID name" // Put your Wifi SSID here #define PASSWORD "your WIFI password" // Put your WIFI password here #define TOKEN "your token" // Put your Ubidots' TOKEN #define MQTT_CLIENT_NAME "1234a5d6798" // MQTT client Name, please enter your own 8-12 alphanumeric character ASCII string; //it should be a random and unique ascii string and different from all other devices /**************************************** * Define Constants ****************************************/ #define VARIABLE_LABEL "sensor" // Assign the variable label #define DEVICE_LABEL "esp32" // Assig the device label #define SENSOR A0 // Set the A0 as SENSOR char mqttBroker[] = "industrial.api.ubidots.com"; char payload[100]; char topic[150]; // Space to store values to send char str_sensor[10]; /**************************************** * Auxiliar Functions ****************************************/ WiFiClient ubidots; PubSubClient client(ubidots); void callback(char* topic, byte* payload, unsigned int length) { char p[length + 1]; memcpy(p, payload, length); p[length] = NULL; Serial.write(payload, length); Serial.println(topic); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.println("Attempting MQTT connection..."); // Attemp to connect if (client.connect(MQTT_CLIENT_NAME, TOKEN, "")) { Serial.println("Connected"); } else { Serial.print("Failed, rc="); Serial.print(client.state()); Serial.println(" try again in 2 seconds"); // Wait 2 seconds before retrying delay(2000); } } } /**************************************** * Main Functions ****************************************/ void setup() { Serial.begin(115200); WiFi.begin(WIFISSID, PASSWORD); // Assign the pin as INPUT pinMode(SENSOR, INPUT); Serial.println(); Serial.print("Waiting for WiFi..."); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(""); Serial.println("WiFi Connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); client.setServer(mqttBroker, 1883); client.setCallback(callback); } void loop() { if (!client.connected()) { reconnect(); } sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL); sprintf(payload, "%s", ""); // Cleans the payload sprintf(payload, "{\"%s\":", VARIABLE_LABEL); // Adds the variable label float sensor = analogRead(SENSOR); /* 4 is minimum width, 2 is precision; float value is copied onto str_sensor*/ dtostrf(sensor, 4, 2, str_sensor); sprintf(payload, "%s {\"value\": %s}}", payload, str_sensor); // Adds the value Serial.println("Publishing data to Ubidots Cloud"); client.publish(topic, payload); client.loop(); delay(500); }
After uploading the above code to ESP32 Open UbiDots and login or create a new account to open the dashboard.
after opening
- click on the “+” sign located at the top right screen to create a new widget.
- Select line chart from the widgets
- Select the variable desired to display the data. Ubidots allows you to customize name, color, period of data to be displayed and much more.
- After choosing click the green tick mark
- Select the device and sensor. that’s it
After all the setup the line chart will show the ECG graph like below image.
When running your ECG code over Bluetooth with ESP32 and Android phone with Bluetooth Graphics, I find that the Serial Plotter hangs or freezes every few seconds. Otherwise, the code works well. I would like to try your code on Xiao ESP32C3, but that would require BLE rather than standard Bluetooth. Would you expect BLE to work well for this project? Have you tried it and do you have code available that you would like to share?
Does anyone know of an alternative to the Bluetooth Terminal/Graphics android application? It will only work on earlier versions of Android, according to my phone.
Your method of describing all in this piece of writing is genuinely
nice, every one be able to without difficulty be aware of it, Thanks a lot
I can’t connect my esp32 to the broker Ubidots. I have an account, i put the correct token but i have the error -2 (Failed, rc=-2) i don’t know why
i have this problem too. pleas help me if u figured out.
Thank you, helped me for my assignment.
With serial plotter on PC, in the version with esp32 and bluetooth, the time base is too small, so only 3 pulses appear on the screen. How can I make more pulses appear on the serial plotter?
Thanks !
Reduce baud rate.
Hi I need to get ECG recordings from 3 electrodes using Arduino and AD8232 .I need to compare the output with the original ECG signals to calculate HR,HRV etc., Can u share with me the coding to do so and the procedure how to take the scale readings of the signals obtained.
I have added LO+ and L0- of AD8232 is connected to D14 & D12 of ESP32. Is that okay?
I am trying to do Method 1 but with ESP 32 with 30 pins. But can’t get a decent ECG signal. Can you please help?
I’m trying to get ECG signal to thinkspeak from esp32. I did the code on arduino IDE. Did you find anything about your problem? Because I try to solve the same thing!
I have used the AD8232 quite a bit and have a couple of suggestions that might help improve the quality of your recording and make the process easier. First, I do not bother with the leads check and remove that part of the code. Therefore, I only have to connect the signal-out, ground and 3.3 pins of the AD8232 module. Second, I attach the leads to the chest, not the extremities. It is helpful to clean the areas where you will attach the electrodes with soap and water and rub a bit to lower resistance of the skin. I put the ground electrode on the right lateral chest over the bottom (12th) rib. I put the right electrode on the LEFT in the V4 position. (To see the V4 position, you can go to a website showing ECG lead placement. V4 is at the left 5th intercostal space in the mid-clavicular line. I put the left electrode just below the RIGHT mid clavicle. With this electrode placement, I generally get a clean recording with upgoing waveforms. You should use a portable computer on battery and turn off all powered equipment, even unplug it from the mains, to help eliminate 60 Hz artifact. Also, you can reduce the amplitude of the 60 Hz artifact in the serial plotter by using your cursor to reduce the height of the display on the since you really don’t need to fill the serial monitor from top to bottom to get an adequate view of the ECG. Also, I have found that there is variation in the quality of leads provided with AD8232. Short, well insulated leads are preferrable. Hope this helps.
hi can i connect bme280, max30100, ds18b20 and ad8232 all together and display in blutooth app if possible make a video or website with code and app. thank you.
Sure we will come up with it soon.
Are you working on it…it will helpful for my project if you do it soon
Hi, I was able to use your excellent BT sketch for AD8232 ECG module on ESP32 with Bluetooth. My only problem is that the Bluetooth graphics app –the one you recommended in tutorial–on my recent-model Galaxy hangs every few seconds. This happens even when I increase the delay in the sketch from 1 to 10 to avoid overwhelming the serial monitor. Do you have any suggestions for avoiding this problem? I haven’t tried the wifi version of the ECG sketch yet.
Thanks for any help you might be able to offer.