Twitter icon
Facebook icon
LinkedIn icon
Google icon
Reddit icon
StumbleUpon icon icon

ECG Analyzer Powered by Edge Impulse

Added to IoTplaybook or last updated on: 04/26/2021
ECG Analyzer Powered by Edge Impulse


Sudden heart attack and increase in fatality : Growing Concern

In a past decade, the sudden heart attack deaths were increased tremendously.

Particularly in a developing nations like India, apart from genetic and life styles, lack of medical resources in rural areas causes most of the fatality in heart attack.

I have done a short survey on reasons for fatality on heart attack in a different countries. Some of the points are still common across the global level, which I have listed below.

survey on fatality in rural areas

survey on fatality in rural areas

Things used in this project

Hardware components

Nano 33 BLE Sense
Arduino Nano 33 BLE Sense
× 1
SparkFun Single Lead Heart Rate Monitor - AD8232
SparkFun Single Lead Heart Rate Monitor - AD8232
× 1


0.96" OLED 64x128 Display Module
ElectroPeak 0.96" OLED 64x128 Display Module
× 1


Software apps and online services

Edge Impulse Studio
Edge Impulse Studio

Edge Impulse



Arduino IDE
Arduino IDE
Visual Studio 2017
Microsoft Visual Studio 2017


Hand tools and fabrication machines

Soldering iron (generic)
Soldering iron (generic)
Solder Wire, Lead Free
Solder Wire, Lead Free


10 Pc. Jumper Wire Kit, 5 cm Long
10 Pc. Jumper Wire Kit, 5 cm Long


Technology contribution to solve this global problem:

I worked on a TinyML application powered by Edge Impulse to develop a mini-Diagnosis ECG analyzer device which can fit in a pocket and it can diagnose heart diseases independently without a cloud connectivity.

Before the detailed documentation, I have attached the demo video of my project in below YouTube link, Kindly watch it.

Present ECG Analyzer machines in market and its features

•Present IoT Medical device sends bulk ECG data to the mobile/server and analysis is done in high processor / mobile App

•Computer based application which receives signals from ECG device and analyze the ECG patterns

•All the ECG analyzing device has dependency on Internet or high processing computers/ Mobile application.

So this can be summarized in below chart;

Key Solution

•ECG Analyzer powered by Edge Impulse will analyze the ECG data with no dependency on the Internet.

•Latency is lowest compared to IoT devices

•A 15Kb Rom - ECG Analyzing TinyML model can run on any TinyML supported microcontrollers.

•The device will analyze ECG patterns and classify into Normal, Atrial Fibrillation and First-Degree heart block.


The ECG analyzer involves

1. ECG reading using AD8232

2. Simulating different heart disease ECG patterns

3.Novel approach to produce quality datasets

4.Training the Model

5.Model test accuracy andIntegratingapplication code with deployedlibrary



Know about ECG graph

Before proceeding with the technical work, first will go through some basics of ECG graph.

The ECG graph was split into 5 Waves - P, Q, R, S and T waves.

ECG graph

ECG graph

Atrial Fibrillation

Atrial Fibrillation



Atrial Fibrillation condition: Irregular heart rhythm [The difference between present R-R interval and previous R-R interval is 200ms]

First-Degree Heart Block

First Degree Heart Block

First Degree Heart Block


If the P-R interval exceeds 200ms, then it can indicated as First Degree Heart Block

Lets build the ECG Analyzer

1. ECG reading using AD8232

Connect the ECG sensor AD8232 to the Arduino Nano 33 BLE sense as per the below connection diagram.

Flash the below code and then press "Ctrl+Shift+L" to visualize the graphical streaming data.

void setup() {
// initialize the serial communication:
pinMode(2, INPUT); // Setup for leads off detection LO +
pinMode(3, INPUT); // Setup for leads off detection LO -
void loop() {
 if((digitalRead(2) == 1)||(digitalRead(3) == 1)){

// send the value of analog input 0:
//Wait for a bit to keep serial data from saturating

1.1 Placement of ECG electrodes

The ECG electrodes are placed in RA, LA and LL as mentioned in above diagram and connect the jack to the AD8232 sensor on the ECG Analyzer.

Info: To get best results – Place electrodes on the chest wall equidistant from the heart (rather than the specific limbs)

2.Simulating different ECG patterns using Matlab-signal builder

Step2.1 : Save the normal ECG data in Excel

First copy and save the serial monitor data into the excel file as below template. The ECG value should be in second column under 'Y'. The first column is time series. it should be incremented as ( * 0.005) 5ms.

Normal ECG data into the Excel sheet

Normal ECG data into the Excel sheet

Step2.2 : Signal builder in Matlab

Create a new Simulink model in Matlab

Then type 'signal builder' in workspace and select it. Also insert the 'scope' to connect it to the signal builder. Please refer to the below screenshot.

1 / 2

2 / 2

To load the saved excel data, open the signal builder and select 'import from file' option.

Please select the mentioned options to import the data.

Then confirm the selection and import without saving the model. since we need to some more steps.

2.3 : ECG Data visualization in signal builder

A 60 second ECG data will be look like this in signal builder view, For manual editing, Please zoom it for 5 seconds data and the do 'drag' to edit the ECG wave.

ECG data

ECG data


Zoom option

Zoom option

After Zooming, when you place the mouse pointer close to the ECG wave, you can able to select any points in the ECG and drag it as per your application requirement.

2.4 : Editing P-R interval data in Signal builder for AV Block 1 Case

I have manually drag down the P wave and shift the P wave much before the R wave, so that the P-R interval exceeds 200ms.

Repeat this step in different timeline in signal builder data.

AV Block 1 data in signal builder

AV Block 1 data in signal builder

After editing, Export the data into the mat file. you can find this option in signal builder. Once the mat file is saved, Kindly follow the below steps.

Steps to follow --> Double click mat file first and double click the 1x1 Dataset--> you can see the modified data under Data:1.

Copy and paste the data in a new excel file.

Step2.5 : Export the excel data into Array

I have written a.m script which can convert the excel data into an array.

Run this script in Matlab, before running replace the ExcelFilename with your local saved file name and ExcelSheetName into a corresponding sheet name.


ECGExtract=(data(1:end,1)); %%Column A data 

fid=fopen('test.txt','wt');%opening with the t flag auto-converts \n to \r\n on Windows
FormatSpec=[repmat('%i ',1,size(ECGExtract,2)) ','];%or should that have been \r\n instead?
fprintf(fid,FormatSpec, ECGExtract);

The text file will be generated in the current directory location.

Copy the array content and paste it in the ECGAnalyzer.c code for simulating Atrial fibrillation and First-Degree heart block.

I have a developed a ECGAnalyzer library (added in github ) which can be integrated into any microcontrollers

3. Novel approach to produce quality datasets

In a machine learning, the accuracy and performance of a model is determined by the quality and divergence of adatasets

If you look at ECG data, its really hard to distinguish the different heart conditions ECG data with normal ECG data in a lesser window time(example: 3 secs)

Normal ECG Data

Normal ECG Data

When I train a model with Filtered ECG Data alone for atrial fibrillation, Normal and First-Degree Heart block, The accuracy was less than 23%. The reason was in the shorter window the model can't differentiate the difference.

If I go for longer window time, the processing time and peak RAM usage was increased quite a lot. Even There was no accuracy.

Background of Novel approach:

When a doctor or Trained person try to analyze the ECG graph, They will be counting the small boxes between R to R wave, P to R interval and write it down the counts in the graph or memories it for calculation.

ECG Graph reading

ECG Graph reading


I decided to convert a human observations into datasets, That's how I have increased the accuracy of ECG Analyzer model.

I created a separate waveforms from filtered ECG data.

New waveforms:

  • R-R Interval
  • PR Interval

Comparison between Quality Datasets with human observation

Comparison between Quality Datasets with human observation


ECGAnalyzer Algorithm

ECGAnalyzer Algorithm

Generated Datasets for Normal ECGdata :

Normal ECG data

Normal ECG data

The decoded R-R interval and PR interval data is always 100 and 50 for normal ECG Data.

Generated Datasets for Atrial Fibrillation- ECG Data:

Atrial Fibrillation ECG Data

Atrial Fibrillation ECG Data

Whenever there is a deviation between previous R-R interval and present R-R interval, R-R interval data will be dropped to -100 for one cycle.

Generated Datasets for First-Degree Heart Block-ECG Data:

First - Degree Heart Block ECG Data

First - Degree Heart Block ECG Data

Whenever the P to R interval exceeds 200ms, then PR Interval data will be dropped to -50 for one cycle.

This approach improved my model accuracy to greater than 90%.

4. Training the Model in Edge Impulse

Before getting into Edge Impulse training ML, we need to configure some parameters in library file for simulation and real time ECG sensor reading.

step4.1 : configure the SIMULATION to 0, If the data acquisition was from real time ECG sensor reading


Configure the SIMULATION to 1, If the data acquisition was from simulated ECG data for Atrial fibrillation and First-Degree Heart Block( followed Matlab sessions).



Step4.2 : Comment/uncomment the required databuffer for simulation

Step4.3 : Data acquisition

Collect the ECG data under three different labels : Normal, Atrial fibrillation and First-Degree Heart Block

Follow the steps in the below link for connecting the Arduino Nano BLE 33 Sense to the Edge Impulse

and select the frequency as 202

$ edge-impulse-daemon --frequency 202

Step4.4 : Create Impulse

In a create impulse section, window size is 3000ms and window increase is 2999ms, select the k-means anomaly detection

Step 4.5: Spectral features

In a spectral features, select the filter type as None.

Step 4.6 : NN Classifier:

I have set 40 number of training cycles and learning rate as 0.005. I have got 92.9 accuracy.

and for Anomaly detection, I have selected PR interval RMS and RR interval RMS.

5. Model test accuracy & Integration

In a model test accuracy, it came around 97% accurate.


select Arduino as deployment ;

Add the downloaded EI deployed file to the Arduino library

adding library

adding library

Note: Add the ECG_Analyzer library from GitHub link to the Arduino library too

This helps to integrate my ECG decoding algorithm code to integrate with EI generated model.

5.2 Integrating Application code to the core generated EI code

I have merged the application code into EI deployed "nano_ble33_sense_accelerometer_continuous" and saved it as ECGAnalyzer.ino.

It is available in attached GitHub link. Flash the code with SIMULATION as 0 in ECG_Analyzer.c in device.


Connect as per the fritzing diagram:

connection diagram in fritzing

connection diagram in fritzing


connection diagram

connection diagram

Assembling :

Final Product:

Here the final product and the accuracy level in test data!!!

Credits: ECG :


Schematics  Connect as per the diagram

Connection Diagram



unzip the Code to Flash: EI_Deployed_Library\examples\ECGAnalyzer\ECGAnalyzer.ino Library to Edit simulation : ECGAnalyzer_lib\ecg_analyzer.c Matlab script and signalbuilder model: script to run in matlab --> Matlab_Simulation\Excel2Arrayconverter.m Signal builder --> Matlab_Simulation\signalbuilder.slx

Manivannan-maker / ECGAnalyzer

I worked on a TinyML application powered by Edge Impulse to develop a mini-Diagnosis ECG analyzer device which can fit on a pocket and it can diagnose heart diseases independently without an Internet. — Read More

Latest commit to the master branch on 3-13-2021

Download as zip





7 projects • 23 followers

Engineer by profession. Solving Real world problems by Passion.

This content is provided by our content partner, an Avnet developer community for learning, programming, and building hardware. Visit them online for more great content like this.

This article was originally published at It was added to IoTplaybook or last modified on 04/26/2021.