I'm trying to get an average from three intervals to get bpm. However, when I use the code below the bpm would slowly decrease when used with the sensor. Can anyone please check for what is wrong with the code and for reference I have to modify the below code from the link for 4 beats to get bpm. Getting BPM from the given code
#include <LiquidCrystal.h>
LiquidCrystal lcd(24, 25, 26, 27, 28, 29);
//global variables
int ibeats, iInterval1, iInterval2, iInterval3, iCount = 1;
unsigned long iFirstPulse, iSecondPulse, iThirdPulse, iFourthPulse;
bool bIgnoreread = false;
bool bFirstPulse = false, bSecondPulse = false, bThirdPulse = false, bFourthPulse = false;
float BPM, fAverage;
void setup()
{
//initialize USB serial port, I2C bus and LCD
Serial.begin(115200); //set this comm up in-case you want to troubleshoot
lcd.begin(20, 4); delay(2);
lcd.clear(); delay(2);
lcd.setCursor(0, 0); lcd.print(" Patient Prober");
}
void loop()
{
ibeats = analogRead(15); delay(5);// Read the Pulse Sensor's value.
lcd.setCursor(0, 3); lcd.print("BPM:"); lcd.print(BPM); lcd.print(" ");// displaying bpm value on LCD
if (ibeats > 780 && bIgnoreread == false) //once the signal is high and bIgnoread is false inital condition, inside if statment will start
{
if (bFirstPulse == false && iCount == 1)
{
iFirstPulse = millis(); // time when the pulse is high for the FirstPulse
bFirstPulse = true; // to turn off if statement
}
if (bSecondPulse == false && iCount == 2)
{
iSecondPulse = millis();
iInterval1 = iSecondPulse - iFirstPulse; // first interval
bSecondPulse = true;
}
if (bThirdPulse == false && iCount == 3)
{
iThirdPulse = millis();
iInterval2 = iThirdPulse - iSecondPulse; //Second Interval
bThirdPulse = true;
}
if (bFourthPulse == false && iCount == 4)
{
iFourthPulse = millis();
iInterval3 = iFourthPulse - iThirdPulse; // third interval
bFourthPulse = true;
}
bIgnoreread = true; // to turn off when millis second is assign to variable Pulse When the signal is high
}
// reseting all the bollean to intial condition
if (ibeats < 300)
{
bIgnoreread = false;
bFirstPulse = false;
bSecondPulse = false;
bThirdPulse = false;
bFourthPulse = false;
iCount++; // incrment to help to diffrent if ststment above
}
//if(ibeats==0)iCount++;
fAverage = ( iInterval1 + iInterval2 + iInterval3) / 3; // Average for the interval
BPM = (60000.0 / fAverage); // Bpm calculation
if (iCount > 4)iCount = 1; // reseting icount to start the cycle again
}
//********************************************************************************************