Arduino Timer Help.

Hi guys,

I need to create a timer that starts counting only when a button is pressed. The timer will count and print onto the serial monitor for the next 60 seconds and stop printing after ward. It will print for the next 60 seconds if the button is pressed again.

I’ve created a code with the limited programming skill that I have but it’s not doing what I want it to do. The millis() starts counting the moment I run the code, not when I press the button. Because of that I’m having trouble getting the time being recorded on the serial monitor for the next 60 seconds when the button is pressed.

All helps appreciated.

Here is my code:

// set pin numbers:
const int buttonPin = 8; 

// variables will change:
int buttonState = 0;         

void setup() {
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    unsigned long milliSeconds;
    int startTime = milliSeconds;
    while ( milliSeconds < startTime + 60000 ) {
      milliSeconds = millis();
      Serial.println(" ms");

millis() works similar to a clock, starting when the code has started and never stopping or being reset.

You need to record the value in millis() when the button is first pressed.

When the current time (given by millis()) minus the recorded time (previously given by millis()) is greater than or equal to 1000 milliseconds (or whatever your printing interval is), then it is time to print onto the serial monitor as well as record a new time from which to measure for the next print.

See "Example of subtracting - recommended" in Nick Gammon's forum article at

Also, these will help you alot with you want to do...

Demonstration code for several things at the same time Blink Without Delay