Want to create one file, but it's making two

Working on a data logging project, and I want to create log files with filenames in the format of yymmddnn.csv, where nn is a sequential number from 00 to 99, and should be a new file (i.e., I don’t want to overwrite or append to an existing file). For some reason, though, my sketch is finding the first unused file name, creating that, and then creating the next one too. Here’s the code:

//test file creation with date and sequence number

#include <Time.h>
#include <SdFat.h>

const int SdChipSelect = 0;
int i = 0;
char logFile[13];
SdFat sd;
SdFile myFile;

void setup()
{
  Serial.begin(38400);
  setTime(1341963000);
  if (!sd.init(SPI_HALF_SPEED, SdChipSelect))
  {
    Serial.println("SD Init failed!");
  }
  else
  {
    if(!sd.chdir("/logs/")) Serial.println("Failed to chdir /logs/");
    time_t t = now();
    int yr = year(t) - 2000;
    sprintf(logFile,"%.2d%.2d%.2d00.csv",
    yr, month(t), day(t));
    logFile[12]=0;
    for (i = 0; i < 100; i++)
    {
      logFile[6] = i/10 + '0';
      logFile[7] = i%10 + '0';
      if (sd.exists(logFile))
      {
        continue;
      }
      if(myFile.open(logFile,O_RDWR | O_CREAT | O_AT_END)) 
      {
        Serial.print ("Opened for writing: ");
        Serial.println(logFile);
      }
      else
      {
        Serial.print("Failed to open ");
        Serial.println(logFile);
      }

      break;
    }
  }
}

void loop()
{
}

…and here’s the output on the serial monitor:

Opened for writing: 12071001.csv
Opened for writing: 12071002.csv

The two files are, in fact, created on the SD card as well.

I’m sure I’m missing something simple here–how do I get it to just create one file?

Please repost the code without the BBC tags.

Fixed. So much for the “Copy for Forum” function in the Arduino software…

When you open the serial monitor, you cause the Arduino to reset. Sometimes, when a sketch starts to run but no serial device is reading it, the buffer on the 8u2 gets filled.

Opening the serial monitor causes the Arduino's ATMega328 to reset but not the 8u2. This creates a second file and printing the next "opening for writing". Once connected, the 8u2 dumps its entire buffer so you see the previous and the current file operation.

Put a delay of 5seconds or so after the Serial.begin(), to give yourself time to open the serial monitor after the code is loaded.

The delay did it. Thanks! Never would have guessed that one.

danb35: The delay did it. Thanks! Never would have guessed that one.

Just to be clear, you code does not create two files. You, as the user were causing two files to be created since a file is created each time your Arduino resets.

That's why the delay() works.

Got it. That also helps explain why I couldn't see anything wrong with my code--there wasn't. It was the reset behavior (that I wasn't aware of) that was doing it. I'm learning, little by little.