Hello everyone,
How should I write this code that on every new loop the name of the file get a new name. For example every 5sec. on the SD card will be written file with different name. First one test1.txt after 5 sec. test2.txt after 5 sec test3.txt and so on. This code of course don`t work but it shows exactly what I want. Many thanks!
for (int i=0; i <= 255; i++)
myFile = SD.open("test[i].txt", FILE_WRITE);
if (myFile) {
myFile.println("arduino");
myFile.close();
}
delay(5000);
This code from a data logger example will try names from "LOGGER00.CSV" until "LOGGER99.CSV" until it finds one that doesn't already exist:
// create a new file
char filename[] = "LOGGER00.CSV";
for (uint8_t i = 0; i < 100; i++) {
filename[6] = i/10 + '0';
filename[7] = i%10 + '0';
if (! SD.exists(filename)) {
// only open a new file if it doesn't exist
logfile = SD.open(filename, FILE_WRITE);
break; // leave the loop!
}
}
if (! logfile) {
// Failed to find an unused filename
}
Few options you could explore - the last two closer to bullet proof.
1 - append the loop index as mentioned above.
2 - get system time. This works until the system is reset or the counter wraps.
3 - combo of the above (less likely of a name collision )
4 - store the next file name (or current file name) or counter in a file or flash, update it each time through the loop and use it to create a new file name
5 - if you have a rtc, create a file name based on the RTC milliseconds (or combination of time fields)
What I need to change in this code that the names will change till 999 not till 99?
// create a new file
char filename[] = "LOGGER00.CSV";
for (uint8_t i = 0; i < 100; i++) {
filename[6] = i/10 + '0';
filename[7] = i%10 + '0';
if (! SD.exists(filename)) {
// only open a new file if it doesn't exist
logfile = SD.open(filename, FILE_WRITE);
break; // leave the loop!
}
}
if (! logfile) {
// Failed to find an unused filename
}
What I need to change in this code that the names will change till 999 not till 99?
Isn't it obvious?
char filename[] = "LOGGER00.CSV";
The code is changing the 0 in this string to other values. You need to put a 3rd 0 in the name, without making it any longer.
filename[6] = i/10 + '0';
Replaces the first 0 with the tens value.
filename[7] = i%10 + '0';
Replaces the second 0 with the ones value.
You need to add another statement to replace a position with the hundreds value, change how the tens value is extracted ((i/10)%10) - 864 divided by 10 is 86; 86 modulo 10 is 6), and change the 10 to 100 in the ones statement.
Thank you very much PaulS! I would never come to this code by myself.. With all sprintf and other funny things.
Thanks you my code is working and I`am one step closer to finish the code!