# Measuring Heartbeats with Arduino

I'm trying to measure a human heartbeat in beats per minute (bpm) and am having some trouble with my code. The serial monitor keeps giving me a value of -1 even though all my math should turn out positive. I am currently using an oscilloscope and a square wave function to simulate a heartbeat. Any help would be appreciated.

unsigned long ulStartTime;
unsigned long duration;
int x = 0;
int bpm = 0;
int led = 13;
int oscillo = 2;
int iState = -1;

void setup(){
pinMode(led, OUTPUT);
pinMode(11, OUTPUT);
pinMode(9, OUTPUT);
pinMode(oscillo, INPUT);
Serial.begin(9600);
duration = 0;
ulStartTime = millis();
}

void loop(){
delay(10);

{
duration = millis()-ulStartTime;
ulStartTime = millis();
//time = millis();
if (1 != iState)
{
x = x + 1;
bpm = x / (duration / 60000);
Serial.print("bpm: ");
Serial.println(bpm);
digitalWrite(led, HIGH);
iState = 1;
}
}
else
{
if (0 != iState)
{
digitalWrite(led, LOW);
iState = 0;
}
}
}

``````      bpm = x / (duration / 60000);
``````

Since duration is going to be less than 60000, the result of that division will always be 0 (integer division). It seems like there is a much simpler way to do this: On a positive (or negative, doesn't matter) transition record the time. On the next transition, find the time difference (you're calling it duration). That gives you the milliseconds/beat. Dive 60000 by that number and you have the beats/minute.