I'm creating an app that tests how fast in beats a user can achieve with taps, mouse clicks / button pushes etc.
Each time the user hits the button, I call this function, beat(); to calculate their current BPM and fill a graphic with that BPM. I also want to calculate an average at the end. See the code I am currently using below.
The issue I am currently having is that as the user clicks, the BPM is all over the place, sometimes its consistent, sometimes it is inaccurate. Reviewing my code has me confused, as I don't think I'm actually calculating BPM here, or at least, not accurately.
I also tried adding in a lerp between the old and new BPM values, to smooth the gauge, but it doesnt seem to fix the problem.
The closest thing I have found on stack overflow is this question : Tap BPM code in Processing
But I still am not sure if that is actually calculating the users BPM accurately. I would greatly appreciate some assistance here, specifically an explanation on the math behind how to calculate BPM with only 2 timestamps, an old and a new beat.
void beat()
{
if (beat0 == null)
{
beat0 = DateTime.Now;
return;
}
else if (beat1 == null)
{
beat1 = DateTime.Now;
}
else
{
beat0 = beat1;
beat1 = DateTime.Now;
}
if (beat0 != null && beat1 != null)
{
double delta = (beat1 - beat0).TotalSeconds;
double bpm = 60 / delta;
curBpm = (int)bpm;
if (oldBpm == -1)
{
oldBpm = curBpm;
return;
}
lerpBpm = (int)Mathf.Lerp(oldBpm, curBpm, (float)delta);
bpmText.text = lerpBpm.ToString();
FillGauge(lerpBpm);
oldBpm = lerpBpm;
}
}