#include <Wire.h>
#include "MAX30105.h"
#include "spo2_algorithm.h"
MAX30105 particleSensor;
#define MAX_BRIGHTNESS 255
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
uint16_t irBuffer[100]; // IR LED sensor data
uint16_t redBuffer[100]; // Red LED sensor data
#else
uint32_t irBuffer[100];
uint32_t redBuffer[100];
#endif
int32_t bufferLength;
int32_t spo2;
int8_t validSPO2;
int32_t heartRate;
int8_t validHeartRate;
void setup() {
Serial.begin(115200);
if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) {
Serial.println(F("MAX30105 was not found. Please check wiring/power."));
while (1);
}
Serial.println(F("Attach sensor to finger and press any key to start..."));
while (Serial.available() == 0);
Serial.read();
particleSensor.setup(60, 4, 2, 100, 411, 4096); // Sensor settings
}
void loop() {
bufferLength = 100; // 4 seconds of samples
for (byte i = 0; i < bufferLength; i++) {
while (particleSensor.available() == false)
particleSensor.check();
redBuffer[i] = particleSensor.getRed();
irBuffer[i] = particleSensor.getIR();
particleSensor.nextSample();
}
// Calculate heart rate and SpO2
maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);
while (1) {
for (byte i = 25; i < 100; i++) {
redBuffer[i - 25] = redBuffer[i];
irBuffer[i - 25] = irBuffer[i];
}
for (byte i = 75; i < 100; i++) {
while (particleSensor.available() == false)
particleSensor.check();
redBuffer[i] = particleSensor.getRed();
irBuffer[i] = particleSensor.getIR();
particleSensor.nextSample();
}
// Recalculate every second
maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);
// Print heart rate, SpO2, and corresponding emoji
if (validHeartRate && validSPO2) {
Serial.print(F("Heart Rate: "));
Serial.print(heartRate);
Serial.print(F(" BPM "));
Serial.print((heartRate >= 50 && heartRate <= 100) ? "\xF0\x9F\x98\x81" : "\xF0\x9F\x98\x9E"); // 😀 or 😞
Serial.print(F(", SpO2: "));
Serial.print(spo2);
Serial.print(F("% "));
Serial.println((spo2 >= 90) ? "\xF0\x9F\x98\x81" : "\xF0\x9F\x98\x9E"); // 😀 or 😞
} else {
Serial.println(F("Invalid reading. Please adjust finger placement."));
}
}
}