While() not working as expected for incrementing SD file name

Hello,

I have written a simple program to initialize an SD card and test if a file name is present. The file name has a numerical increment value. The program should increment this value until the file it is looking for does not exist.

The console data is as follows:

Initializing SD card...card initialized.
data01.TXT already exists
incremented file name is now data02.TXT

data01.TXT already exists
incremented file name is now data02.TXT

data01.TXT already exists
incremented file name is now data02.TXT

The string filename has changed to data02.txt yet it becomes the old value of data01.txt when the loop repeats.

What can I do to fix this?

Thank you.

[code]
#include <SPI.h>
#include <SD.h>

const int chipSelect = 10; //using pin 10 as chip select
String filenum = "01";
String filename = "data" + filenum + ".TXT"; //first file name is data01.TXT

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect
  }

  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");
}

void loop() {
//Note: SD library only recognizeds file names 8.3 !!

while (SD.exists(filename)) {
  Serial.print(filename); Serial.println(" already exists");
  int file_increment = filenum.toInt(); //change file increment to an integer
  ++file_increment; //add one to the file increment
  String filenum = "0" + String(file_increment); //create a new increment with leading 0
  String filename = "data" + filenum + ".TXT"; //creates the new file name incremented by 1
  Serial.print("incremented file name is now "); Serial.println(filename); //prints new file
  Serial.println();

//should now check for the incremented file name and repeat until an non-existent file name occurs
}

Serial.print("next available file name "); Serial.print(filename);

}
[/code]

How many different String objects named filenum have you got in your sketch and how does the compiler know which one to use ?

If the last file name was looked for in setup, parsed for the higest file number, the highest number is saved to a variable, and incremented when a file is to be saved.

Thank you. I should not have redefined filenum and filename with String in the while().

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.