SD Card Sometimes not listing all of the files


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.println("~~~~~~MPU DataLogger~~~~~~");
    Serial.println("Failed to start SD Card");
    Serial.println("SD Card Ready");
  pinMode(6, INPUT_PULLUP);
  pinMode(7, OUTPUT);
  Serial.println(accelgyro.testConnection()?"MPU6050 Connected":"MPU6050 Not Found");

  // Open new file for writing
  File dir ="/");
  File f;
    f = dir.openNextFile();
    Serial.println("Found file: " + String(;
  output ="/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){
      count = 0;
      Serial.println("-----> Switching to file " + String(fileCount) + ".");
      output ="/d_"+String(fileCount)+".dat", FILE_WRITE);
        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);
    sprintf(buffer, format, flag, ax, ay, az, gx, gy, gz);
    int len = strlen(buffer);
    count += len;
    output.write(buffer, len);

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.