# Understanding Heart Rate Detection algorithm

Hi there, I am using the Sparkfun Max30105 library to detect heart rate and had some questions regarding the following code

``````int32_t ir_avg_reg = 0;
int32_t sample;
IR_Average_Estimated = averageDCEstimator(&ir_avg_reg, sample);

//  Average DC Estimator
int16_t averageDCEstimator(int32_t *p, uint16_t x)
{
*p += ((((long) x << 15) - *p) >> 4);
return (*p >> 15);
}
``````

I have seen the answers to these topics.
(https://forum.arduino.cc/index.php?topic=519626.msg3541568#msg3541568)

I understand that it is efficient to use the shift operator
But I still do not get it, so I post a question.
I do not know how the numbers were determined by some method.
why it use 15 and 4
I believe somebody will explain it easily

Thank you for your precious time

That is a first order digital low pass filter, of the type IIR, using shifts instead of multiplies. It is used to estimate the DC level.

See this general discussion (among others).

Hi jremington

It was not resolved due to lack of knowledge about filters.

I'm trying to understand, but it's not easy.

Is that code implementing the following expression?

y := y[i-1] + α * (x - y[i-1])
I do not know which is the cutoff frequency and which is alpha

This line:

``````  *p += ((((long) x << 15) - *p) >> 4);
``````

is equivalent to

y = y + ( x*215 - y)/24

ksghj2000:
I do not know how the numbers were determined by some method.
why it use 15 and 4
I believe somebody will explain it easily

jremington:
This line:

``````  *p += ((((long) x << 15) - *p) >> 4);
``````

is equivalent to

y = y + ( x*215 - y)/24

The 215 is a scale factor for a fixed-point arithmetic representation of the data. This allows the calculations to retain significance smaller than 1 bit of the ADC. As an example (B100000000000 + B000000000000) >> 1 = B10000000000 in this scheme is (1 + 0)/2 = 0.5. Fixed point arithmetic is generally much faster than floating point arithmetic on processors (like most Arduino) that don’t have hardware floating point capability.

The 1/24 = 1/16 is the “alpha” value as per the discrete IIR discussion in the low pass filter article linked in post #1. The filter cutoff frequency can be calculated knowing “alpha” and the sample interval as per that article.

MrMark:
The filter cutoff frequency can be calculated knowing “alpha” and the sample interval as per that article.

The cut-off frequency fc on that Wikipedia page is the analog cut-off frequency.
The digital normalized cut-off frequency of the exponential moving average filter is given by arccos((α² + 2α -2) / (2α - 2)). See this link:

Exponential moving average filter

Pieter

Everyone is so grateful.

I finally figured it out

It took quite a long time when I was alone without help

Thanks again.