-
Notifications
You must be signed in to change notification settings - Fork 0
/
BeatDetector.cpp
65 lines (54 loc) · 1.38 KB
/
BeatDetector.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* BeatDetector.cpp
*
* Created on: Oct 4, 2018
* Author: vkozlov
*/
#include "BeatDetector.h"
BeatDetector::BeatDetector(const int samplingFreq)
{
baselineFilter = new Biquad(bq_type_lowpass, 0.1 / samplingFreq, 0.707, 0);
}
void BeatDetector::push(const double value)
{
baselineValue = baselineFilter->process(value);
//double threshold = 3500;
double threshold = baselineValue * 1.5;
// BPM calculation check
if (value > threshold && belowThreshold == true)
{
calculateBPM();
belowThreshold = false;
}
else if(value < threshold)
{
belowThreshold = true;
}
}
double BeatDetector::getBaseline()
{
return baselineValue;
}
void BeatDetector::calculateBPM ()
{
int beat_new = millis(); // get the current millisecond
int diff = beat_new - beat_old; // find the time between the last two beats
double currentBPM = 60000 / diff; // convert to beats per minute
beats[beatIndex] = currentBPM; // store to array to convert the average
double total = 0.0;
for (int i = 0; i < BEAT_BUFFER_SIZE; i++)
{
total += beats[i];
}
BPM = int(total / BEAT_BUFFER_SIZE);
beat_old = beat_new;
beatIndex = (beatIndex + 1) % BEAT_BUFFER_SIZE; // cycle through the array instead of using FIFO queue
}
void BeatDetector::updateSamplingFrequency(const int frequency)
{
baselineFilter->setFc(0.1 / frequency);
}
int BeatDetector::getBps()
{
return BPM;
}