I made a small set up to log temperature on SD card, everything is running smoothly until it reach 9:06:01 of logging that is 32761 seconds. I know that corresponds roughly to the maximum value of an integer. But I made all my variables unsigned long. Here is the code in the loop and the if condition to log or not. The timer is computed with currentTime (unsigned long) and startTime (unsigned long). So even if logCount*freq are both integers, they should reach maximum value after 32761 seconds, then the if condition should always be true.

void loop() { 
 String date;
 unsigned long timer;
 int freq = 60;

 tempC1 = printTemperature(insideThermometer, 18);
 tempC2 = printTemperature(outsideThermometer, 19);

 // start serial port


 CurrentTime = millis();
 timer=(CurrentTime - StartTime)/1000;
 date = TimeShowFormatted(CurrentTime - StartTime);

 if (timer > logCount * freq and StopStatus == 0) {
  logCount += 1;

  • 1
    What's StartTime? Add rest of your code so I can simulate it please. – Filip Franik Feb 8 at 8:45
  • To increment a variable, use logCount++; – SBF Feb 8 at 13:52
  • @FilipFranik StartTime is a unsigned long that is initialized at zero when arduino is started or re-initialized at zero when the logging is restarted (via menu on LCD shield) – Vincent Feb 11 at 8:57

Instead of comparing absolute times you should use the following:

unsigned long now = millis();

if(now - time_last_log >= freq){
    logCount += 1;
    time_last_log = now; 
    // or if you really want fixed intervals
    // time_last_log += freq; 

This is guaranteed to be overflow proof.

  • This code can also fail badly. It's possible for time_last_log to be close to max value of 'unsigned long' and then it never get's updated because now is always lower. I suggest adding || now < time_last_log to the if to escape that infinite loop. – Filip Franik Feb 8 at 9:25
  • 3
    @FilipFranik: No, it will not fail when time_last_log gets close to ULONG_MAX. Owing to the rules of modular arithmetic, this code is rollover safe. Try for yourself if you are not convinced. – Edgar Bonet Feb 8 at 9:35
  • @EdgarBonet You broke my brain. You are right. – Filip Franik Feb 8 at 9:47
  • @EdgarBonet Thank you for your helpful insight. It is always great to learn something! I'll test today the solution and validate the answer if everything is ok. – Vincent Feb 11 at 9:06
  • @EdgarBonet it works well, 21h of logging and still running.thank you very much – Vincent Feb 12 at 7:13

Your Answer

