[Solved] Millis() function not working as intended

I have an uno r3 board and I'm using the millis() function to create a timer that counts to 600000 milliseconds, this is the code:

unsigned long time;
int contr;
int timer;
int temp;
void setup() {
  Serial.begin(9600);
}

void loop() {
  time = millis();
  timer = time - contr;
  contr = time;
  Serial.print("Timer: ");
  Serial.println(timer);
  temp = abs(temp) + timer; //should be the same as "temp += timer" but I can't explain the change to negative at approximatly 32768
  Serial.println(temp);
  if(temp >= 60000){
    Serial.println("a minute has passed");
    temp = 0;  
  }
}

The problem that I have here is that the timer goes really well untill it hits 32768 milliseconds at that point it becomes negative and starts subtracting itself, I tried solving using an abs() function or multiplying by -1 but the error persists.

You need to use unsigned long for anything relating to millis. Not int.

This includes contr and timer. Oh and temp. 60000 is an impossible value for an int which has a range of -32768 to 32767 only.

1 Like

All variables used for millis() calculations must be 'unsigned long'.

thank you! Does the unsigned long variables have a bigger range?

use unsigned long and you'll get the bigger range

You want something larger than 4,294,967,295?

No i think it's enough :sweat_smile:

ok, thank you

It does with an 8-bit AVR processor like that on the Uno.

Changed the code:

unsigned long time;
unsigned long contr;
unsigned long timer;
unsigned long temp;
void setup() {
  Serial.begin(9600);
}

void loop() {
  time = millis();
  timer = time - contr;
  contr = time;
  Serial.print("Timer: ");
  Serial.println(timer);
  temp = abs(temp) + timer; //should be the same as "temp += timer" but I can't explain the change to negative at approximatly 32768
  Serial.println(temp);
  if(temp >= 60000){
    Serial.println("a minute has passed");
    temp = 0;  
  }
}

Now it works flawlessly. Thank you to everyone!

1 Like

usually this is written more simply as

unsigned long lastTime = 0;

void setup() {
  Serial.begin(115200);  // 9600 baud is sooooo last millenium..
}

void loop() {
  if (millis() - lastTime >= 60000ul) {
    Serial.println("a minute has passed");
    lastTime = millis();
  }
}
2 Likes

Please mark the thread as "solved"

1 Like

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