How can I set a value to 0 when I press a button?

I am trying to set a time value to 0 when I press a button so it tracks how long from 1 press to the other.

int button = 0;
int buttonstate = 0;
unsigned long time;

void setup() {
  // put your setup code here, to run once:
  pinMode(button, INPUT);


void loop() {
buttonstate = digitalRead(button);
Serial.print("time: ");
time = millis();

if(buttonstate == HIGH){
 unsigned long time = 0;


Check the scope of the last “time” variable.


 unsigned long time = 0;

declares a new variable called "time" and initialized to zero. This is a different variable from the other one called "time". This doesn't confuse the compiler but it is likely to confuse YOU.

Do this

  time = 0;

If you only want to have a single variable called "time" and you want to set its value to zero.