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";

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

void setup() {
  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()
  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)