'Arduino RTC DS1302 Date change to 2165 While code is running

DS1302 RTC DateTime invalid while the code is running.

float getDayAvg(File &file){
    float sum=0.0;
    int count=0;
    while(file.available()){
            String line=file.readStringUntil('\n');
            String data=line.substring(line.indexOf(' '));
            sum+=data.toFloat();
            count++;
          }
    file.close();
    return (count==0) ? 0 : sum / (count*1.0);
  }

int retrieveDataDays(String starting_path,uint8_t from_day=0,uint8_t to_day=0){
    File dir = SD.open(starting_path);
    to_day = (to_day==0) ? 31:to_day;
    RtcDateTime current= rtc->GetDateTime();
    Serial.println(String(current.Year())); // prints a valid date
    while (true) {
      
      File file =  dir.openNextFile();
      if (! file) {
        break;
      } 
      current = rtc->GetDateTime(); // date no longer valid with output sometimes 2165 and 2000 another times
      Serial.println(String(current.Year()));
       

      String name=String(file.name());
      uint8_t file_day=name.toInt();
      if(file_day<from_day || file_day>to_day) continue;
      float avg=getDayAvg(file);
      Serial.println("Avg for day " + name + " is " + String(avg));
  }
  dir.close();
  }
};

also checked isDateTimeValid() for the RTC modules, it returns true before the while loop and after the while loop, it returns false.

Any idea what could cause this problem? If I removed this code the error no longer happens.

PS: I'm only printing the loop for testing since after hours of debugging I narrowed down the error to be in this code.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source