[Solved] Variable wont count past 4 without adding delay

l want buttonTimer to reset every 1500 milliseconds ,but the problem is that it only counts to 4. When I run it in the serial monitor the value jumps between 3 and 4. If I take out buttonTimerOld it resets once and then stays at 0, which is to be expected. Does anyone have an explanation for what's wrong with my code?

Edit:
If I add 10 ms of delay it jumps between 10 and 11 in the serial monitor.

unsigned long milliseconds = 0;
unsigned long buttonTimer =  0; unsigned long buttonTimerOld  = 0; 
void setup() {
Serial.begin(9600);
}

void loop() {
  milliseconds = millis();
  buttonTimer = milliseconds - buttonTimerOld; 
  buttonTimerOld = milliseconds;
  if(buttonTimer >= 1500){
    buttonTimer = 0;
  }
  Serial.println(buttonTimer);
}

Ok nevermind this it was a dumb mistake that i should have found hours ago.
See code to see what I changed.

unsigned long milliseconds = 0;
unsigned long buttonTimer =  0; unsigned long buttonTimerOld  = 0;
void setup() {
  Serial.begin(9600);
}

void loop() {
  milliseconds = millis();
  buttonTimer = milliseconds - buttonTimerOld;
  if (buttonTimer >= 1500) {

    buttonTimerOld = milliseconds; //I just had to move this inside the if
    buttonTimer = 0;
  }
  Serial.println(buttonTimer);
}

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.