Question

Hello I have an Arduino Uno board that I got recently and I am trying to run a stopwatch function on the board. I have two momentary pushbuttons. When the first button is pressed it stores the amount of time that has passed, in the startTime variable, since the program began using the millis() functon. When the second button is pressed later on it also stores the amount of time that has passed since the program started running, in the endTime variable, using the same millis() function. It then calculates the timeElapsed by taking the startTime away from the endTime.

I used the Serial.print in between in an effort to debug. I get the startTime and endTime values that I expect and they are correct, however my elapsedTime value does not seem to be working correctly.

There is one clue as to the problem. The elapsed time is meant to return the value of endTime-startTime. However what it always returns instead is the value of endTime-773. Im not sure what this means exactly but I believe it could be useful information to help solve my problem.

void setup(){
  Serial.begin(9600); //start the Serial.moniter on the computer
  pinMode(2, INPUT);  //Set the button attached to pin 2 as an input
  pinMode(3, INPUT);  //Set the button attached to pin 3 as an input
}

void loop(){
  int buttonStateTwo = digitalRead(2);  //stores either a HIGH(button pressed) or LOW(button not being pressed) value
  int buttonStateThree = digitalRead(3);

  unsigned int startTime;  
  unsigned int endTime;
  unsigned int elapsedTime;

  if(buttonStateTwo == HIGH){       //if the button is pressed
    startTime = millis();  
    Serial.print(" The start time is: "); 
    Serial.print(startTime);
    delay(1000);                    //pause the program for a second
  }

  if(buttonStateThree == HIGH){
    endTime = millis();
    Serial.print(" The end time is: ");
    Serial.print(endTime);                   
    elapsedTime = endTime-startTime;         //this returns an incorrect value
    Serial.print(" The time elapsed is: ");
    Serial.println(elapsedTime);             //incorrect value 
    delay(1000);
  }
}

I would be very thankful if someone could please help me as I have tried for ages to work out the problem and have taken many different approaches.

Was it helpful?

Solution

The declaration of the variables is performed in loop(). This means that each time loop() is called by the Arduino libraries, these variables can contain arbitrary values which may or may not be the same as the values they had when loop() was last called. Move the declarations to the module scope instead (outside of and before loop()) so that they are only created once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top