Try Embedded

Heart rate monitor

Count heartbeats from a pulse sensor's waveform and work out beats per minute.

Sensors · Intermediate

In a real product: Fitness tracker (Wearables): Turns the optical pulse waveform into beats per minute.

A pulse sensor shines light into a fingertip and measures how much comes back. Each heartbeat pushes more blood through, which shows up as a peak in the signal. Timing the peaks gives the heart rate.

What you'll learn

  • Detecting peaks in an analog waveform with a threshold
  • Hysteresis: a separate, lower threshold to re-arm, so noise does not double-count
  • Turning the time between beats into beats per minute

How it works

OUT goes to A0. Each beat makes a sharp peak followed by a smaller bump. The signal sits around 360 between beats, and the main peak goes over 800.

When the reading rises above 600, that is a beat: the time since the last beat gives bpm = 60000 / interval_ms. The code then waits for the reading to fall back below 550 before it looks for the next beat. Without that gap, small wiggles around 600 would count as several beats. The built-in LED flashes on each beat.

Try this

  • Change the sensor's bpm slider while it runs.
  • Average the last five intervals for a steadier reading.
  • Warn when the rate goes above 120 or below 50.

sketch.ino

// A heart beat sensor on A0: count peaks above a threshold and print the rate in beats per minute.
const int SENSOR = A0;
const int THRESHOLD = 600;   // a beat when the signal rises above this
const int REARM = 550;       // ...and the next one only after it falls below this
bool inBeat = false;
unsigned long lastBeat = 0;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int signal = analogRead(SENSOR);
  if (!inBeat && signal > THRESHOLD) {
    inBeat = true;
    digitalWrite(LED_BUILTIN, HIGH);
    unsigned long now = millis();
    if (lastBeat != 0) {
      int bpm = 60000 / (now - lastBeat);
      Serial.print("Heart rate: ");
      Serial.print(bpm);
      Serial.println(" BPM");
    }
    lastBeat = now;
  } else if (inBeat && signal < REARM) {
    inBeat = false;
    digitalWrite(LED_BUILTIN, LOW);
  }
  delay(5);
}

Lessons behind it