I found this code on github and used it, however my Max30102 cannot measure SpO2 and Heart Rate at the same time, sometimes it cannot measure both. Can anyone help me find out if the error is due to the code or the device?
You can read full code in this link(youjunjer/ESP32-MAX30102 (github.com))
void loop() {
long irValue = particleSensor.getIR();
if (irValue > 7000 ) {
float temperature = readTemperature();
float avgBeat = calculateAvgHeartBeat(irValue);
double spO2 = calculateSpO2();
}
// Handle no finger detected case
else {
for (byte rx = 0 ; rx < RATE_SIZE ; rx++) rates[rx] = 0;
beatAvg = 0;
avered = 0; aveir = 0; sumirrms = 0; sumredrms = 0; rateSpot = 0;
SpO2 = 0; ESpO2 = 90.0;
}
particleSensor.nextSample();
}
float calculateAvgHeartBeat(long irValue){
if (checkForBeat(irValue) == true) {
//Calculate beatsPerMinute
long delta = millis() - lastBeat;
lastBeat = millis();
beatsPerMinute = 60 / (delta / 1000.0);
if (beatsPerMinute < 255 && beatsPerMinute > 20) { //Check if the BPM value is within a valid range
rates[rateSpot++] = (byte)beatsPerMinute; //Store this reading in the array
rateSpot %= RATE_SIZE; //Wrap variable
//Take average of readings
beatAvg = 0;
for (byte x = 0; x < RATE_SIZE; x++)
beatAvg += rates[x];
beatAvg /= RATE_SIZE;
}
}
return beatAvg;
}
float readTemperature(){
float temperature = mlx.readObjectTempC() + 1.0;
return temperature ;
}
double calculateSpO2() {
uint32_t ir, red ;
double fred, fir;
if (particleSensor.available()) {
i++;
ir = particleSensor.getFIFOIR();
red = particleSensor.getFIFORed();
fir = (double)ir;
fred = (double)red;
aveir = aveir * frate + (double)ir * (1.0 - frate); //average IR level by low pass filter
avered = avered * frate + (double)red * (1.0 - frate);//average red level by low pass filter
sumirrms += (fir - aveir) * (fir - aveir);//square sum of alternate component of IR level
sumredrms += (fred - avered) * (fred - avered);
if (i % Num_Readings == 0) {
double R = (sqrt(sumirrms) / aveir) / (sqrt(sumredrms) / avered);
SpO2 = -23.3 * (R - 0.4) + 100;
ESpO2 = FSpO2 * ESpO2 + (1.0 - FSpO2) * SpO2;
if (ESpO2 <= MINIMUM_SPO2) ESpO2 = MINIMUM_SPO2;
if (ESpO2 > 100) ESpO2 = 99.9;
sumredrms = 0.0;
sumirrms = 0.0;
SpO2 = 0;
i = 0;
}
}
return ESpO2;
}