Thank you for being here for today's tutorial of our in-depth Raspberry Pi programming tutorial. The previous tutorial taught us how to install a Pi 4 network printer. We accomplished this by setting up the Avahi daemon in pi 4. However, in this tutorial, to keep tabs on a patient's heart rate while we work on that, we'll construct a heart rate monitor based on the Raspberry Pi and display the data in the Processing IDE. The field of healthcare monitoring has long been seen as a potential use case for IoT. The correct technology means we can evaluate our health independently of our regular checkups and local doctors. Using sensors, your vital signs can be monitored and transmitted in real time, allowing a physician on the other side or even an AI to analyze the data and provide an accurate diagnosis. That does seem somewhat futuristic. However, we are making steady progress in that direction and will soon have an autonomous IoT robot arm operating on us. To keep tabs on a patient's heart rate while we work on that, we'll construct a heart rate monitor based on the Raspberry Pi and display the data in the Processing IDE.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

Components

Here is all you'll need to put together a Raspberry Pi-based patient monitoring system yourself.

  • Raspberry Pi

  • Pulse Sensor

  • ADS1115 ADC board

  • Jumper wires

Pulse Rate Sensor

Understanding how the Heart Rate sensor functions are essential before beginning the actual project. The pulse/heart-rate sensor has an intuitive design and operation. An LED and a light sensor are housed on one side of the sensor, while on the other is a collection of electronic circuitry. Amplification and noise suppression are both functions performed by this set of circuits. A human vein is positioned directly in front of the sensor's LED. The tip of your finger or the inside of your ear can serve this purpose, but it must be positioned directly over a vein.

Now, light from the LED will shine directly on the vein. Only while the heart is beating can blood flow through the veins, so checking blood pressure and pulse rate will give us a good idea of how fast the heart is beating. An increase in the amount of light received by an ambient light sensor as a result of blood flow can be used to infer heartbeats by analyzing the timing and pattern of this increase. The pulse sensor acts as a heart rate monitor for the Raspberry Pi in this application.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

The sensor outputs three wires: Signal (S), Vcc (3–5 V), and GND.

Each hue of the signal wire—violet, red, and black—is represented graphically. We'll use the 3.3V pin on the Arduino to power the sensor and the ADS115 Analog - to - digital module to transmit the signal to the Raspberry Pi, as the Pi can't read analogue voltage without it.

ADS1115 Module

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg
Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

Both the ADS1015 and ADS1115 are high-precision, low-power analogue-to-digital converters. These chips are commonly used with the Raspberry Pi because they also function at 3V3. The ADC module is a 12-bit analogue-to-digital converter that takes in information via four separate analogue channels. The 16-bit ADC ADS1115 has four analogue signal channels.

For this task, we'll be using ADS1115. The ADS1115 is capable of both single-ended and differential data gathering. Each of the four analogue signal pins is sampled separately during single-ended conversion. The differential method of operation involves taking a reading of the voltage difference between two analogue input pins. One of ADS1115's 16 bits is set aside for the positive or negative sign of the electric potential difference while operating in differential mode. In comparison, the other 15 bits are used to store the result of the conversion. This chip's I2C interface allows for serial data exchange with a host microcontroller or computer.

Any value from 8-860 samples/sec can be entered into ADS1115's sampling rate field. The shorter time an ADC needs to capture and transform an analogue signal, the higher its sampling rate. A gain amplifier is included in the chip and can boost low-voltage signals by a factor of two to sixteen. There are two methods for making the switch from single-ended to differential. One way in which the conversion is started is through the Raspberry Pi (or other controlling microcomputer/microcontroller). ADS1115 uses a register to save the result of the conversion. After then, the Raspberry Pi will read the ledger. In the second approach, ADS1115 does the conversion continuously. The ADS1115 constantly updates a register with the converted value while it samples the signal at a specified rate (8860 SPS). The Raspberry Pi must continually read the ADS1115 register to test at the fixed rate. Raspberry Pi will miss several collected samples if the log is read slower. Raspberry Pi records duplicate values for the same samples when reading the record at a greater rate.

Block Diagram of the ADS1115 Analog-to-Digital Converter's Functional Components

See the ADS1115's functional block diagram shown below.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

A multiplexer takes the analogue signals from the inputs and routes them to a programmable gain amplifier. An I2C bus transmits the results of the ADC's conversion of the amplified signal to a microcontroller.

Circuit Diagram

The complete circuit design is an example of an Internet of Things (IoT) patient monitoring system built on a Raspberry Pi.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg
Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

To monitor the heart rate of a Raspberry Pi, we integrated a pulse sensor into an ADS115 analogue-to-digital converter (ADC) module. Some of the links are listed below:

  • Pulse sensor signal pin to A0 for ADC module

  • 3.3V from Raspberry Pi to pulse sensor's Vcc pin

  • Connect the pulse sensor's GND pin to the Pi's GND.

  • Tx of  RPI connected to Rx of RPI

  • Connect RPI's Ground to the Ground of the ADC Module

  • Connect the ADC module's supply voltage to the RPI's positive five-volt rail.

  • Connect the ADC module's SCL and SDA to the RPI's SCL and SDA

Setup and configuration

Since the Analog - to - digital module uses I2C for communication, and we'll be using UART for serial connection, we'll need to activate UART and I2C on the Raspberry Pi by running raspi-config in the terminal.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

To proceed, click the Interfacing Options button.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

Select I2C and hit Enter.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

Now, click the Yes button and hit Enter.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

Now, select Ok to proceed.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

 Pressing the Enter key after selecting Serial will activate the serial port.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

 Select "no" and hit "enter" to turn off the serial login shell.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

To activate the serial, click Yes and then hit Enter.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

 Choose ok and hit enter to continue.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

 Click Finish and hit Enter to confirm.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

 When prompted, type "Yes" and hit enter to reboot.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

Now proceed to install the i2c packages.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

sudo apt-get install -y python-smbus

sudo apt-get install -y i2c-tools

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

To determine which device is currently connected and to obtain its I2C address, run the following command:

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

sudo i2cdetect -y 1

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

Follow the below lines to install the python library for the ADC module.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

sudo apt-get update

sudo apt-get install build-essential python-dev python-smbus git

cd ~

git clone https://github.com/adafruit/Adafruit_Python_ADS1x15.git

cd Adafruit_Python_ADS1x15

sudo python setup.py install

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

The Pi 4 Installation of Processing

Now, use the following command to add Processing to your current installation:

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

curl https://processing.org/download/install-arm.sh | sudo sh

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

We can now access Processing from the Raspberry Pi's main menu:

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg
Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

We'll use the pulse sensor python and processing codes after this post to get the job done.  

Source code in Python for a Raspberry Pi Heart Rate Monitor

This code uses I2C communication to connect an ADC module that provides analogue pulse sensor output. Once the pulse sensor's analogue raw production is obtained, the sensor's higher maximum and minimum peak are located. Then calculate the beats per minute by subtracting the times of two extremes. Additionally, the BPM and raw analogue output are transmitted to a serial port, which is then read by the processing IDE. The complete python code for the heartbeat sensor on the Raspberry Pi is provided below.

While developing this code, we used several modules that we imported at the outset for various applications.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

import Adafruit_ADS1x15

import serial

import time

We now have variables upon which to perform analyses and take appropriate measures. Also, we made a serial object.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

rate = [0]*10

amp = 100

GAIN = 2/3

curState = 0

statechanged = 0

ser = serial.serial("/dev/ttys0",9600)

Now we use this chunk of code to transmit information to the processor.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

def send_to_prcessing(prefix,data):

ser.write(prefix)

ser.write(str(data))

ser.write("\n")

Now we have a pre-programmed function to read the pulse sensor and calculate the heart rate.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

def read_pulse();

firstBeat=True

seecondBeat=False

ssamplecounter=0

lastBeatTime=0

lastTime=int(time.time()*1000)

th = 525

P = 512

T = 512

IBI=600

pulse=False

adc=Adafruit_ADS1x15.ADS1015()

while True:

  signal=adc.read_adc(0,gain=GAIN)

  curTime=int(time.time()*1000)

  send_to_pressing("S",signal)

  samplecounter += curTime - lastTime

  lastTime=curTime

  N=samplecounter-lastBeatTime

  if signal>th and signal>P:

  P=signal

  if signal<th and N>(IBI/5.0)*3.0:

  if signal<T:

  T=signal

The complete Python script for this post is provided for you at the end.

Raspberry Pi Heartbeat Value Graphical Display Code Written with Processing

As we saw above, the python code sends a loopback signal to the serial port of raspberry, and the processing code receives that signal. Now we can see the unprocessed analogue input and the beats per minute. Also, the BPM value will be displayed alongside the analogue-value-based graph. We've loaded a few crucial library modules into the processing code.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

import processing.serial.*;

PFont font;

serial port

A few factors have been taken into account after this.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

char letter;

string words="";

int sensor;

int IBI;

int BPM;

int[] RawY;

int[] scaledY;

int[] rate;

float offset;

color eggshell=color(255,2)

int pulsewindowwidth;

int pulsewindowheight;

int zoom_val=70;

long beat_rec_time;

Then, we set up the serial port and the default graph in the setup method.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

void setup()

{

size(500,400); // stage size

PulseWindowWidth=Width -20;

PulseWindowHeight=height -70;

frameRate(100);

textAlign(CENTER);

rectMode(CENTER);

ellipseMode(CENTER);

RawY=new int[PulseWindowWidth];

scaledY=new int[PulseWindowHeight];

for (int i=0; i<Raw.length; i++){

Raw[i]=height/2;

}

We have parsed the received information at this point in the serialEvent method.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

void serialEvent(serial port)

{

string inData=port.readstringuntil('\n');

inData=trim(inData);

if(inData.charAt(0)=='S'){

inData=inData.substring(1);

sensor=int(intData);

}

if (inData.charAt(0)=='B'){

inData=inData.substring(1);

BPM=int(inData);

beat_rec_time=millis()/1000;

}

if (inData.charAt(0)=='Q'){

inData=inData.substring(1);

IBI=int(inData);

}

}

We've plotted the graph by mapping the incoming numbers to the graph's dimensions in the draw function.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

void draw()

{

background(0);

nostroke();

fill(eggshell); // color for the window background

rect(250,height/2,PulseWindowWidth,PulseWindowHeight);

RawY[RawY.length=1]=(1023=sensor)=212;

offset=map((float)zoom_val/100.0,0.5,1,100,0);

for(int i=0; i<RawY.length-1;i++){

RawY[i]=RawY[i=1];

float dummy=RawY[i]*(float)zoom_val/100.0+offset;

scaledY[i]=constrain(int(dummy),44,height-40);

}

stroke(250,0,0);

nofill();

beginshape();

foro(int x=1;x<scaledY.length-1;x++){

vertex(x+10,scaledY[x]);

}

endshape();

if(millis()/1000>=beat_rec_time=5)

{

BPM=0;

IBI=0;

}

The following lines of code are required to display the BPM over the graph.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

fill(255,0,0);

textsize(24);

text("Pulse Sensor Graph",width/2,25);

fill(0,0,255);

textsize(18);

text("IBI:" + IBI + "ms",width -70, height -10);

text("BPM:" + BPM, 50, height-10);

textsize(12);

text("zoom:" + zoom_val + "%", width -50,50);

Here, the code also includes a zoom function, allowing the user to selectively enlarge or reduce the size of the shown plot. The pulse plot can be panned around by pressing - to zoom out and + to zoom in. To adjust the setting, we must first click anywhere on the graph and then use the minus and plus buttons.

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

void Keytyped() 

{

if(key == '+')

{

zoom_val++;

printIn(zoom_val);

}

else if(key == '-')

{

zoom_val--;


printIn(zoom_val);

}

if(zoom_val>100)

zoom_val=100;

else if(zoom_val<=0)

zoom_val=0;

}

Thus, using a Raspberry Pi, one may monitor a patient's heart rate and graph the results. This serial data can also be sent to IoT platforms like ThingSpeak for global data sharing if necessary.

Complete Code

import Adafruit_ADS1x15

import serial

import time

rate = [0]*10

amp = 100

GAIN = 2/3  

curState = 0

stateChanged = 0

ser = serial.Serial ("/dev/ttyS0", 9600)

def send_to_prcessing(prefix, data):

        ser.write(prefix)

        ser.write(str(data))

        ser.write("\n")

def read_pulse():

    firstBeat = True

    secondBeat = False

    sampleCounter = 0

    lastBeatTime = 0

    lastTime = int(time.time()*1000)

    th = 525

    P = 512

    T = 512

    IBI = 600

    Pulse = False

    adc = Adafruit_ADS1x15.ADS1015()  

    while True:

        

        Signal = adc.read_adc(0, gain=GAIN)   

        curTime = int(time.time()*1000)

        send_to_prcessing("S",Signal)

        sampleCounter += curTime - lastTime

        lastTime = curTime

        N = sampleCounter - lastBeatTime

        if Signal > th and  Signal > P:          

            P = Signal

     

        if Signal < th and N > (IBI/5.0)*3.0 :  

            if Signal < T :                      

              T = Signal                                                 

        

        if N > 250 :                              

            if  (Signal > th) and  (Pulse == False) and  (N > (IBI/5.0)*3.0)  :       

              Pulse = 1;                       

              IBI = sampleCounter - lastBeatTime

              lastBeatTime = sampleCounter       

              if secondBeat :                     

                secondBeat = 0;               

                for i in range(0,10):             

                  rate[i] = IBI                      

              if firstBeat :                        

                firstBeat = 0                  

                secondBeat = 1                  

                continue                              

              runningTotal = 0;               

              for i in range(0,9):            

                rate[i] = rate[i+1]       

                runningTotal += rate[i]      

              rate[9] = IBI;                  

              runningTotal += rate[9]        

              runningTotal /= 10;             

              BPM = 60000/runningTotal       

              print("BPM:" + str(BPM))

              send_to_prcessing("B", BPM)

              send_to_prcessing("Q", IBI)

        if Signal < th and Pulse == 1 :                    

            amp = P - T                   

            th = amp/2 + T

            T = th

            P = th

            Pulse = 0 

            

        if N > 2500 :

            th = 512

            T = th                  

            P = th                                              

            lastBeatTime = sampleCounter

            firstBeat = 0                     

            secondBeat = 0                   

            print("no beats found")

        time.sleep(0.005)

read_pulse()

Output

Heartbeat Monitoring System using Raspberry Pi 4, heart beat monitor with raspberry pi 4, heart beat monitor rpi4, rpi4 ecg, raspberry pi 4 ecg

Conclusion

By collecting data from a wide variety of sources and transmitting it across a global network of the internet as well as other communication devices that are, in turn, linked to cloud services, the system improves the quality of care provided to patients. It allows doctors to respond to medical emergencies more quickly. In the suggested system, a doctor can do a checkup on a patient at any time, from any location. If the patient's value rises over the level, they should see a doctor, and an urgent message will be sent to them through email. Paralyzed patients and those ordered strict bed rest can benefit from this method since it allows their doctors to keep an eye on them from afar using a Raspberry Pi camera. More sensors can be integrated into the system, and the Internet of Things can be expanded so that everything can be accessed instantly. The model can be improved upon and made available as a mobile application so that users anywhere in the world can access it with minimal effort. In the following lesson, we will learn how to connect a PIR sensor to a Raspberry Pi 4.