Example Code for Raspberry Pi – Heart Rate Monitor Sensor

Last revision 2026/01/20

The article provides a comprehensive guide to using a DFRobot heart rate sensor with a Raspberry Pi, including setup instructions, example code, and explanations of the sensor's operation using PPG technology.

Introduction

The DFRobot heart rate sensor, despite a tiny size of just a thumb, can monitor human heart rates. Compatible with Arduino main controllers, this plug-and-play module is really convenient to use that it’s equipped with Gravity 3-Pin interface. It uses PPG (Photo Plethysmo Graphy) to measure heart rate, a low-cost optical technology that monitors the human heart rate by detecting blood oxygen levels in subcutaneous capillaries. Besides, this technology features fast response, stable performance and strong adaptability.
As being equipped with two mounting holes, the sensor can be wrapped on your finger, wrist, earlobe or other areas where it has contact with your skin.

Hardware Preparation

The module has two signal output modes: square wave and pulse wave, which can be freely switched through the on-board switch. The pulse wave outputs a continuous heart rate waveform, while the square wave outputs a corresponding square wave according to heart rates.

Precautions

  1. This is a static heart rate sensor. Please do not move or press too tightly during its measurement.
  2. This product is NOT a professional medical device and should not be used to diagnose or treat medical conditions.

Wiring Diagram

  • Connect the digital LED light-emitting module to the pin 12 on extension board, the heart rate sensor to the pin 8, and the analog light sensor to the analog port 0.

Sample Code

  • Open Thonny Python IDE and copy the following program into it.

import RPi.GPIO as GPIO
import time
import atexit

LED=12
Heart_Rate=8

atexit.register(GPIO.cleanup)
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED,GPIO.OUT)
GPIO.setup(Heart_Rate,GPIO.IN)

while True:
    if GPIO.input(Heart_Rate):
        GPIO.output(LED,GPIO.HIGH)
    else :
        GPIO.output(LED,GPIO.LOW)
    time.sleep(0.1)

  • Then the LED will go on and off with your heartbeat.

Was this article helpful?

TOP