Auto filename increment on SD card


If you log your data on an SD card you usually do not want to append new data to your old log files every time you restart your Arduino or even overwrite your old files.
As there is plenty of space on a Micro SD card you can start writing data to a new file. But how to enter a new filename, especially if there is no PC around?
Well, do it just the same way as your digital camera does: just increment the filename.

This is how it can be done: Each time you press RESET
(or power-on your board)
a new filename will be created:
#include <SD.h>
const int chipSelect = 10;
boolean cardOK = true;
long fileNum = 10000;  // maximum 99999
String fileName;
char name[13];
File dataFile;

void incFileNum() { // generate next file name:
  String s = "dat" + String(++fileNum) + ".txt";
  s.toCharArray(name,13);
}

void save(String s) {
  dataFile = SD.open(name, FILE_WRITE);
  if (dataFile) {
    dataFile.println(s);
    dataFile.close();
    Serial.println(s);
  }  
  else Serial.println("error opening " + String(name));
}

void setup() {
  Serial.begin(9600);
  Serial.print("Initializing SD card...");
  pinMode(chipSelect, OUTPUT);
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    cardOK = false; // don't perform the loop()
    return;
  }
  Serial.println("card initialized.");
  
  //--------------------------------------------------
  incFileNum(); // set it to dat10000.txt
  while (SD.exists(name)) incFileNum();
  Serial.println("new file name: " + String(name));
  //--------------------------------------------------

  save("this is the log file");
}

void loop() {
  if (!cardOK) return;
  
  // do your job
  
}





contact: nji(at)gmx.de