0

i am using ESP32 and trying to write a micropython code for heart rate. the raw signal changes when touching the sensor but the BPM start high and then stays at 60 all the time whether i am touching the sensor or not. can anyone help please. here is my code

import machine
import time

# Define the ADC pin to read the analog signal from the pulse sensor
adc = machine.ADC(machine.Pin(34))

# Set the attenuation level to 11dB to increase the input voltage range
adc.atten(machine.ADC.ATTN_11DB)

# Set the width of the ADC conversion to 12 bits to increase the resolution
adc.width(machine.ADC.WIDTH_12BIT)

# Define some variables for calculating the heart rate
signal_max = 0
signal_min = 4095
pulse_threshold = 1500  # pulse sensor threshold value
last_beats = [time.time()] * 10  # initialize the last_beats list with 10 elements
bpm = 0

# Set the initial time for the delay
next_print_time = time.time() + 3

# Read the analog signal from the pulse sensor continuously
while True:
    signal = adc.read()
    signal_max = max(signal_max, signal)
    signal_min = min(signal_min, signal)
    
    # Detect a pulse by comparing the signal to a threshold
    if signal > pulse_threshold and time.time() - last_beats[-1] > 0.2:
        last_beats.pop(0)  # remove the oldest beat from the list
        last_beats.append(time.time())  # add the current beat to the list
        # Calculate the time between the last few beats in seconds and take the average
        time_diffs = [(last_beats[i] - last_beats[i-1]) for i in range(1, len(last_beats))]
        time_diff = sum(time_diffs) / len(time_diffs)
        if time_diff > 0:
            bpm = 60 / time_diff
            
        # Print the BPM value every 3 seconds
        if time.time() >= next_print_time:
            print("BPM: {}".format(int(bpm)))
            next_print_time += 3
    
    # Print the raw signal value every 1 second
    if time.time() >= next_print_time - 2:
        print("Raw signal value: {}".format(signal))
    
    time.sleep(1)

i tried using high pass filter and changing the algorithm but no good

0 Answers0