SD card logging works for a few cycles, then fails

I have a program that is sending data from an RTC and an accelerometer to an SD card for logging. However, when I run it the code, it works for a few cycles, then gives me an error. I have included the loop part of my code and the output from the serial monitor below.

I have tried changing the rate at which it checks data to every 5 seconds instead of every 1, and it did not make a difference. I have also tried changing the chip select pin that my SD reader is connected to, but it also did not make a difference.

Both the amount of time it runs before it fails and the number of cycles it runs before it fails vary from time to time. When I was running it and having it just output to the serial monitor, I was not encountering a problem, it showed up after I started sending to the SD card instead. Any suggestions?

void loop() {

  unsigned long currentMillis = millis();
  if((currentMillis - previousMillis) > 1000){
    myFile ="current.txt", FILE_WRITE);
    if (myFile) {
      Serial.println("File found. Recording data to file...");
      myFile ="current.txt", FILE_WRITE);
      myFile.print(", ");
      readDateTime(); //sends a datetime value to the SD card
      readXYZ();  //sends accelerometer data to the SD card

      previousMillis = currentMillis;
    } else { 
      Serial.println("Error opening file.");

What SD card reader are you using? Any other SPI devices? Anything connected to any pins?

I'm not sure about the issue that you are asking for specifically, but I have a small suggestion to improve your code. You should change your if statement that says if((currentMillis - previousMillis) > 1000) to if(abs(currentMillis - previousMillis) > 1000). Adding in the absolute value will help your program because eventually currentMillis will reset back to 0 once it reaches the upper bound of an unsigned long and then you will have a situation like 10-200000, and your program will get stuck. The absolute value will ensure that if your currentMillis variable resets to 0 or if millis() resets back to 0 your loop will still be functioning correctly.

@michaelsm: No, it won't. This is not a problem using unsigned long with subtraction. The rollover goes smooth.

Try a rollover yourself:
currentTime - earlierTime >= duration
0x0000000F - 0xFFFFFFF0 = 0xFFFFFFFF00000010 (15 after rollover - 16 before rollover)
throw away the upper 32 bits as unsigned long is only 32 bits, result is
0x0000001F = 31, rollover works.

I have not yet played around with SD card in Arduino, but this doesn't look right to me.

I see two

    myFile ="current.txt", FILE_WRITE);

but only one


@Gabriel_swe This seems to have fixed it. It's been running for several minutes now with no problems, will report back if it has an error later.