int PulseSensorPurplePin = A0; // Pulse Sensor connected to analog pin A0
int LED = LED_BUILTIN; // On-board LED
int Threshold = 550; // Threshold for detecting a heartbeat
int Signal; // Holds raw analog reading
bool PulseDetected = false; // True when a beat is detected
unsigned long lastBeatTime = 0; // Time (ms) of the last beat
float BPM = 0; // Calculated Beats Per Minute
void setup() {
pinMode(LED, OUTPUT);
Serial.begin(115200);
}
void loop() {
// Read the sensor
Signal = analogRead(PulseSensorPurplePin);
// Check if signal crosses the threshold upward (beat detected)
if (Signal > Threshold && !PulseDetected) {
PulseDetected = true; // mark that we’re in a beat
unsigned long currentTime = millis();
unsigned long delta = currentTime - lastBeatTime;
if (lastBeatTime > 0) { // skip first beat (no interval yet)
BPM = 60000.0 / delta; // 60000 ms per minute
Serial.print("BPM: ");
Serial.println(BPM);
}
lastBeatTime = currentTime;
digitalWrite(LED, HIGH); // flash LED on beat
}
// When signal goes back below threshold, reset for next detection
if (Signal < Threshold && PulseDetected) {
PulseDetected = false;
digitalWrite(LED, LOW);
}
// Small non-blocking pause (optional for stability)
// Just ensures serial output isn’t too fast
static unsigned long lastPrint = 0;
if (millis() - lastPrint > 20) {
//Serial.print("Signal: ");
//Serial.println(Signal);
lastPrint = millis();
}
}