Measuring time between button presses

That's pretty simple to do.
Assume a button that connects a pin to Gnd when pressed:

byte button =2;
unsigned long startTime;
unsigned long endTime;
unsigned long duration;
byte timerRunning;
void setup(){
pinMode (button, INPUT_PULLUP);
Serial.begin(9600);
}
void loop(){
  if (timerRunning == 0 && digitalRead(button) == LOW){ // button pressed & timer not running already
  startTime = millis();
  timerRunning = 1;
  }
  if (timerRunning == 1 && digitalRead(button) == HIGH){ // timer running, button released
  endTime = millis();
  timerRunning = 0;
  duration = endTime - startTime;
  Serial.print ("button press time in milliseconds: ");
  Serial.println (duration);
  }
}

Even compiles on the first pass. Let me know how it works.

1 Like