I've downloaded the Timer1 library but unfortunately it seems that the read() method has been removed from it. I tried also SimpleTimer library from the arduino website but the program didn't compile because of undefined reference to `SimpleTimer::SimpleTimer()' error. Anybody knows how to solve this error or just another timer library which has a read function?

To be more specific I need to start a timer as I press a button and to stop it as it is released.

  • Have you considered looking for an input capture library instead? Jul 29 '17 at 21:14
  • To start a timer, give it a clock by setting the CSn2..0 bits. One set of those bits stops the clock thus the timer. Read the data sheet to be sure.
    – dannyf
    Jul 29 '17 at 21:41

Here, below is a code which is you looking for. When you pressed a button then a timer is started and when you released it then a timer is stopped. And you can also see that time also means how long button is pressed.

const uint8_t button_pin = 2;

void setup()
    pinMode(button_pin, INPUT_PULLUP);

void loop()
    static int last_button_state = HIGH;
    static unsigned int push_count;
    static unsigned long last_press_time;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if (last_button_state == HIGH && button_state == LOW) {
        last_press_time = now;

    // Report when the button is released.
    if (last_button_state == LOW && button_state == HIGH) {
        unsigned long push_duration = now - last_press_time;
        if (push_duration < 10) {  // discard bounce
        else {
            Serial.print(F("pushes: "));
            Serial.print(F(", duration: "));
            Serial.println(F(" ms"));

    last_button_state = button_state;

To use this sketch, you will need to download and install the Debounce library from here: https://playground.arduino.cc/Code/Debounce. Connect one end of a N.O. push button switch to GND and the other end to pin 4 of the Arduino. NOTE: If the button is held down for less than the debounce delay time, the elapsed time will be the debounce delay time. NOTE2: The millis() function overflows after approximately 49 days.

#include <Debounce.h>
const byte SWITCH = 4;
unsigned long startTime = 0;
unsigned long endTime = 0;
unsigned long elapsedTime = 0;
const byte debounceDelayTime = 50;

Debounce debouncer = Debounce(debounceDelayTime, SWITCH);

void setup(){

void loop(){
    if(debouncer.read() == 0){
      startTime = millis();
    else if(debouncer.read() == 1){
      endTime = millis();
      elapsedTime = endTime - startTime;
      Serial.print("Button Held Down For ");
      Serial.println(" ms.");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.