Time between two impulses(Heartbeats)

Hello community,

I am a newbie and I want to measure the time between impulses of heartbeats, via a pulsesensor, and display it on the Serial Monitor. Underneath you will see my code. I uploaded it on my Arduino Uno but I only get 0´s in the Serial Monitor. Can someone explain to me where my error lies? I appreciate every help from every forum-user.

Thank you very much in advance

Best regards Kosta

int AnalogPin = A0;

int Signal;                
int Threshold = 500;            


volatile unsigned long last;
volatile unsigned long timediff;


void setup() {

  pinMode(AnalogPin,INPUT);        
   Serial.begin(9600);        

}


void loop() {

  Signal = analogRead(AnalogPin);  

   //Serial.println(Signal);                 


  if (Signal > Threshold) {

    
     volatile unsigned long current = millis();
     last = current;
    
     timediff = current - last;
 
    
  }

   Serial.println(timediff);

delay(200);


}

Yes, the error is in these three lines.

If you set last to be the same as current the difference between the two will always be zero in the next line.
Most probably you wanted to put the last = current line after the timeDiff line.

Hello pylon,

thank you very much for taking your time and helping me, I appreciate it.

Best regards

Kosta

There's another problem.

You don't want the above code to run all the time that the signal is higher than the threshold, which is what this line says:

if (Signal > Threshold) {

You only want the code to run once for each heartbeat, at the moment the signal crosses the threshold. To do that, your code needs to remember the signal level last time it was read.

Hello PaulRB,

you mean that I have to detect the current and previous highest peak every time and calculate the timedifference between them or did I understood it wrong? Thank you for your notification.

Best regards Kosta

Not quite. You don't need to detect the peaks. You only need to detect the moment when the signal first rises above your threshold, on each heartbeat. Right now, your code to calculate time difference will run repeatedly while the signal is above that threshold, so it could run many times, perhaps hundreds of times, for each heartbeat.

Maybe I can observe the waveformsignal with its highest peak and than set a new value for the threshold, so that I can remove the underneath of the treshold values. Is it ok like this?

Thank you very much for your help PaulRB. Best regards