Right now I'm trying to make a project using the Arduino PulseSensor to read a user's pulse without using the given PulseSensor library. This is the code I have so far:
#include <Arduino.h>
#include <avr/interrupt.h>
#include <stdint.h>
// Variables
int PulseSensorPurplePin = 0; //PulseSensor input, reads signal from sensor
int LED = LED_BUILTIN; //Arduino Uno R3 built-in LED
int Signal; //Raw signal from sensor
int Threshold = 510; //Signal is read from 0-1024, if signal is above 510 it registers as a heartbeat
volatile int bPM = 0; //initial BPM
volatile int beatCount = 0; //initial beatCount
volatile int timesThrough = 0; //initial times through
ISR(TIMER1_COMPA_vect) //Timer 1 interrupt handler
{
timesThrough += 1; //adds 1 to timesThrough
if (timesThrough == 5) //if we've reached this interrupt 5 times
{
bPM = (beatCount * 12); //update bpm
timesThrough = 0; //reset times through
beatCount = 0; //reset beatCount
}
TCNT1 = 0; //reset Timer1
OCR1A = 15625; //reset Timer1Compare
}
// The SetUp Function:
void setup() {
pinMode(LED,OUTPUT); //set the Arduino LED pin as output
Serial.begin(9600); //start Serial monitor
TCCR1A |= (1 << COM1A0); //toggle OC1A ON COMPARE MATCH
TCCR1B |= (1 << CS12); //set Timer1 to 1024 prescaler
TCCR1B |= (1 << CS10); //set Timer1 to 1024 prescalewr
OCR1A = 15625; //Timer1 Compare Number
TIMSK1 |= (1 << OCIE1A); //Timer 1 Output Compare A Match Interrupt Enable
TCNT1 = 0; //set Timer1 to 0
}
// The Main Loop Function
void loop() {
Signal = analogRead(PulseSensorPurplePin); //read raw data from PulseSensor
if(Signal > Threshold){ //if the signal is a heartbeat
digitalWrite(LED,HIGH); //turn on Pin
beatCount += 1; //add 1 to beatCount
delay(50); //delay 50 ms
Serial.println(beatCount); //print the beatCount to console, only here for testing
} else { //if the signal is not a heartbeat
digitalWrite(LED,LOW); //turn off LED
}
}
This is a very rough draft, but I did have some questions if anyone of you could help me through. The Interrupt handler that I created never actually does anything. Does anyone know if I wrote the handler incorrectly where it wouldn't function? Also, when getting the beatCount, the output is greater than one because the PulseSensor returns multiple values that are above the given threshold. Is there a way for it to just read the first one? I've tried using the delay() function but it doesn't seem to work, so is there another way around it?