A timer which activates by pressing a button

I’m trying to make a timer which starts by pressing a button.
I’ve tried millis() but it starts counting as soon as I start the program.

Hi,

You were right, you need to use the millis() function. It’s true that it’s counting the number of milliseconds from the beginning of the execution but if we store that value when we press a button, it’s the same as taking the current time.

Think of it as a watch. If you want to measure the duration of an event, you look at the time on your watch then wait until the end of the event. At that time, you look at your watch and compute the difference in time.

Here is an example :

// The duration of the timer
int timerDuration = 2000;

// The time at which we start the timer
int startTime = 0;

// Whether or not the timer was started
boolean timerStarted = false;

void setup() {
  size(200, 200);
}

void draw() {
  background(255);
  
  if (timerStarted) {
    // We subtract the current time and the time when we started the timer
    int currentDuration = millis() - startTime;
    
    fill(0);
    textAlign(CENTER, CENTER);
    text(currentDuration, width / 2, height / 2);
    
    // If the event is over
    if (currentDuration > timerDuration) {
      timerStarted = false;
    }
  }
}

// When the mouse is pressed, take the current time and store it
void mousePressed() {
  startTime = millis();
  timerStarted = true;
}
2 Likes