Millis function overflow

Hello!

Im working on an Arduino based project to water my plants, however I do have a concern about the millis function. What will happen to this code once millis overflows? From the information I have gathered from other forums and videos this should be ok however I still doubt it. If anyone wants to give feedback it would be greatly appreciated. CurrentTime and PreviousTime are both set as unsigned longs. I only posted a small portion of the the code but if more is needed to give feedback around the question feel free to ask. And if anyone is interesting in the watering code, feel free to ask for it, keep in mind I haven’t added comments to everything.

  if (CurrentTime - PreviousTime >= ReadTime  &&  DifferenceTime == true ){  
     
      PreviousTime = CurrentTime;         
}

Thanks you!

I missed one thing when adding the code, CurrentTime = millis(); is set at the start of the void loop.

After roughly 50 days, millis will reset to zero and start counting up again so you will have to write your code to check when that’s about to happen and recalculate times after that happens.

So If I write an If statement that checks if CurrentTime - Previoustime returns a negative value it sets Previoustime to 0 I should be ok?

Thanks for the quick reply

The good news is that your will program will work despite millis() overflowing after around 48 days. Since the millis() value is unsigned you don’t have to worry about the value overflowing, the math will still work for you, that is how unsigned integers work.

Using an unsigned “uint8_t a,b;” as an example. if “a” represents the millis() value and it has overflowed to 2 from 255 and “b” is 254, the value of (2-254) is 4 which is the number of millis() between the two values. You can try this yourself with:

void setup() {
  Serial.begin(9600);
}

void loop() {
  uint8_t a,b,c;
  a = 2; // "overflowed" millis value()
  b = 254; // last millis value
  c= a-b;
  Serial.println(c);
}

Thanks! Great news, I will test the code to see it first hand.

I added this line in my current program before I read the last comment:

  if (CurrentTime - PreviousTime <  0 ){
    PreviousTime = 0; 
    delay(5);
  }

The main issue that can happen I guess is that the read time will double if it doesn’t trigger right before millis overflows.

That will not work - “(CurrentTime - PreviousTime)” will never be less than zero since both variables are unsigned. Leave your original code as is, it will work even when millis() overflow back to 0.

Thank you again!