You've done all the hard work already by setting the sensor up and managing to read from it.
I'd define a constant for the SpO2 threshold near the top, and convenient names for the pins:
const uint8_t SpO2_threshold = 94; // percent
const uint8_t red_pin = 4;
const uint8_t green_pin = 5;
Then set the pins to output mode in the setup()
as usual. (Maybe set them both HIGH (or LOW) too in there, to indicate that no reading has been done yet.)
In the loop, inside the reporting section, simply grab the value and toggle the pins:
...
uint8_t spo2 = pox.getSpO2();
// Print it out to serial if needed, then:
if (spo2 < SpO2_threshold) {
digitalWrite(green_pin, LOW);
digitalWrite(red_pin, HIGH);
} else {
digitalWrite(red_pin, LOW);
digitalWrite(green_pin, HIGH);
}
A more involved version that pulses one LED (short on time, variable off time) depending on the value read from the sensor. It uses the same technique as the sensor reading timing (the one used in the "blink without delay" example).
Sensor readings are clamped (any value at or below spo2_min
will result in the fasted blink time, over spo2_max
the slowest). Then that range is mapped to a range of led off times. Don't use the values in this example, I'm not a medical doctor :-)
// pin mapping
const uint8_t led_pin = LED_BUILTIN;
// sensor readings (%)
const int spo2_min = 85;
const int spo2_max = 100;
// led timings (ms)
const unsigned long led_off_min = 50;
const unsigned long led_off_max = 5000;
unsigned long led_off_time = led_off_max; // variable off time
const unsigned long led_on_time = 50; // fixed, short on time
// sensor reading timing (ms)
const unsigned long sensor_interval = 1000;
// led state
uint8_t led_state = LOW;
// "timer" state
unsigned long last_reading = 0;
unsigned long last_led_toggle = 0;
void setup() {
pinMode(led_pin, OUTPUT);
digitalWrite(led_pin, led_state);
Serial.begin(9600);
Serial.print("Initializing pulse oximeter..");
if (!pox.begin()) {
Serial.println("FAILED");
for (;;);
} else {
Serial.println("SUCCESS");
}
}
void loop() {
pox.update();
unsigned long current_millis = millis();
/* sensor reading "timer" */
if (current_millis - last_reading >= sensor_interval)
{
last_reading = current_millis;
int spo2 = pox.getSpO2();
// clamp reading to expected range
int clamped = constrain(spo2, spo2_min, spo2_max);
// map to off time range
led_off_time = map(clamped,
spo2_min, spo2_max,
led_off_min, led_off_max);
char buff[128];
sprintf_P(buff, PSTR("reading: %d (%%) -> interval: %lu (ms)"),
spo2, led_off_time);
Serial.println(buff);
}
/* led toggling "timers" */
unsigned long led_elapsed = current_millis - last_led_toggle;
if ((led_state == LOW) && (led_elapsed >= led_off_time))
{
last_led_toggle = current_millis;
led_state = HIGH;
digitalWrite(led_pin, led_state);
}
else if ((led_state == HIGH) && (led_elapsed >= led_on_time))
{
last_led_toggle = current_millis;
led_state = LOW;
digitalWrite(led_pin, led_state);
}
}