SD Card Sometimes not listing all of the files

Hello,

I am working on a data logger that writes the data from an MPU6050 to an SD card. I am using an Arduino Nano. I am facing a strange problem. In my setup function, I have code that is supposed to print out all of the files in the directory. If at the end of my setup() function I put in an infinite while loop: while(true){delay(100);}, all of the files are printed. However, if I don’t have that infinite loop there, it prints out about 4 file names and then it behaves as if intercepted a return statement and the setup() method exists prematurely.

I tried changing the infinite loop to a delay(20000); to see if that would “fix” the problem, the program waits 20 seconds before starting loop() as expected, however it seems to skip the Serial.println("File couunt is: " + String(fileCount));

Could anyone explain what is going on? I am sure how a statement that appears at the end of my setup() function could impact the behavior of code that has already executed.

#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <MPU6050.h>
#include <stdio.h>
#include <string.h>

File output;
MPU6050 accelgyro;
int fileCount = 0;
void setup() {
  // Setup Sensor and SD Card
  Serial.begin(115200);
  Serial.println("~~~~~~MPU DataLogger~~~~~~");
  
  if(!SD.begin(4)){
    Serial.println("Failed to start SD Card");
    while(true);
  }else{
    Serial.println("SD Card Ready");
  }
  pinMode(6, INPUT_PULLUP);
  pinMode(7, OUTPUT);
  
  Wire.begin();
  accelgyro.initialize();
  Serial.println(accelgyro.testConnection()?"MPU6050 Connected":"MPU6050 Not Found");

  // Open new file for writing
  File dir = SD.open("/");
  File f;
 
  while(true){
    f = dir.openNextFile();
    if(!f){
      Serial.println("Breaking");
      break;
    }
    Serial.println("Found file: " + String(f.name()));
    fileCount++;
  }
  output = SD.open("/d_"+String(fileCount)+".dat", FILE_WRITE);
  Serial.println("File count is: " + String(fileCount));

  while(true){delay(100);}  //Program works with this statement, but not without it.
  
}

int16_t ax, ay, az;
int16_t gx, gy, gz;
int input;
int flag=0;
char buffer[100];
char* format = "%d,%d,%d,%d,%d,%d,%d\n";
long count = 0;

void loop() {
    //If count is getting too big, then switch files.
    if(count >= 1024){//1073741824){
      output.close();
      fileCount++;
      count = 0;
      Serial.println("-----> Switching to file " + String(fileCount) + ".");
      output = SD.open("/d_"+String(fileCount)+".dat", FILE_WRITE);
      if(!output){
        Serial.println("Failed to open file!");
      }
    }

    accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
    input = digitalRead(6);
    if(input != 1){
     Serial.println("Switch Toggled, Delaying readings 30 seconds");
     flag = (flag == 1)?0:1;
     digitalWrite(7, flag);
     delay(30000); 
    }
   
   
    sprintf(buffer, format, flag, ax, ay, az, gx, gy, gz);
    Serial.print(buffer);
    
    int len = strlen(buffer);
    count += len;
    
    output.write(buffer, len);
    output.flush();
    delay(100);
}

Nevermind. I realized that I was not closing the files inside of the while loop.

Not sure if there is a limit on the number of files you will have on the SD card, but the use of String when processing the filenames can fragment the heap memory and lead to unexpected and bizarre errors - especially true if used in a situation where the code is expected to run for long periods.