Skip to main content
Wie wil meedoen met de solarbike zelfbouw club?
Who wants to join the solarbike DIY club?

Simple Arduino Stopwatch library

Published: 21 April 2013
Last updated: 28 September 2018

Measure interval times

With this library we can measure interval times. Another application is measuring the execution time of a piece of code. The interface is easy and the results can be printed to the serial monitor:

Serial << stopwatch.interval << "\n";  

Time measurements of fast interrupt service routines

Because interrupt service routines (ISR) are time-critical; it is important to know the maximum execution time. In order not to disturb the ISR, the stopwatch values can't be printed inside the ISR itself, therefore printing is done in the main program loop().

It is impractical to print every stopwatch result; this will be done just 2 times per second, with the aid of the Metro library. The intermediate Stopwatch results are ignored.

Maximum interval time

As the duration of an ISR can vary, the maximum interval time is measured also. We can select whether we want to reset this value every time: maxInterval(0) or maxInterval(1).

Stopwatch example program

Usually, we will measure in micro seconds instead of milli seconds: Stopwatch stopwatch(micros);

#include "Stopwatch.h"
#include <Streaming.h>
#include <Metro.h>
#include <FrequencyTimer2.h>
Metro metroTimer(500);
Stopwatch stopwatch_ms(millis); 
Stopwatch stopwatch_us(micros); 
void setup() 
{ Serial.begin(9600);
  FrequencyTimer2::setPeriod(100); // static member functions without object
  stopwatch_ms.start(); // simple example
  Serial << "\nstopwatch_ms interval: " << stopwatch_ms.interval << "\n";  
void loop() // print here, outside the ISR, just 2 x per second
{ if(metroTimer.check()) Serial << "stopwatch_us counter: " << stopwatch_us.counter << " interval: " 
                << stopwatch_us.interval << " maxInterval: " << stopwatch_us.maxInterval(1) << "\n"; 
void timer2ISR() // 10kHz
{ stopwatch_us.start();

Stopwatch library


Simple stopwatch library for the Arduino.
Albert van Dalen
#ifndef Stopwatch_h
#define Stopwatch_h
#if ARDUINO >= 100
    #include "Arduino.h"
    #include "WProgram.h"
class Stopwatch 
    Stopwatch(unsigned long (*timeFunctionPtr)()); 
    void start();
    void stop(); 
    unsigned long maxInterval(bool reset=0); 
    unsigned long counter, interval; 
    unsigned long (*timeFunctionPtr)();
    unsigned long starttime, _maxInterval;    


Simple stopwatch library for the Arduino.
Albert van Dalen
Version 20-4-2013
#include "Stopwatch.h"
Stopwatch::Stopwatch(unsigned long (*timeFunctionPtr)()): 
void Stopwatch::start()
{ starttime = timeFunctionPtr();
void Stopwatch::stop()
{ interval = timeFunctionPtr() - starttime; 
  _maxInterval = max(_maxInterval, interval); 
unsigned long Stopwatch::maxInterval(bool reset) 
{ unsigned long returnValue = _maxInterval;
  if(reset) _maxInterval = 0;
  return returnValue;