I just did a test using a UNO-3 where I wrote data to one file, closed it and started with a new one.
The test sketch created file t-00000.dat, t-00001.dat and t-00002.dat. But when trying to open t-00003.dat it failed:
17:41:40.035 -> File size: 164352
17:41:40.555 -> Closing file
17:41:40.555 -> t-00002.dat
17:41:40.555 -> Free ram=909
17:41:40.595 -> ERROR opening file: t-00003.dat
17:41:40.635 -> Free ram=909
17:41:40.635 -> Free ram=909
17:41:40.635 -> ERROR opening file: t-00004.dat
17:41:40.675 -> Free ram=909
17:41:40.715 -> Free ram=909
17:41:40.715 -> ERROR opening file: t-00005.dat
...
17:41:46.675 -> ERROR opening file: t-00099.dat
17:41:46.715 -> Free ram=909
17:41:46.715 -> Test completed!!
I do not understand why. It's a 32 Gb card formatted as advised on this forum. Most of the space on the card is unused.
After the test I modified the sketch so that the filename is s-000000.dat, uploaded it and now it continue to create data on the card.
Why does it behave like this?
The test sketch:
#include <SPI.h>
#include <SD.h>
/*
* SD card
* MOSI: pin 11
* MISO: pin 12
* SCK : pin 13
* CS : pint 10
*/
const uint8_t chipSelect = 10;
File csvFile;
int freeRam()
{
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
void printFreeRam()
{
Serial.print(F("Free ram="));
Serial.println(freeRam());
}
/*
*
* Setup function.
*
*/
void setup()
{
Serial.begin(9600);
Serial.println(F("\n\n\nInitialzing..."));
printFreeRam();
// Initial SD card.
Serial.println(F("Initializing SD card"));
if (!SD.begin(chipSelect)) {
Serial.println(F("Initialization failed!"));
while (true) ;
}
Serial.println(F("Initialization done."));
delay(500);
Serial.println(F("Ready!"));
printFreeRam();
}
/*
* Main loop function.
*
*/
void loop()
{
char filename[14];
for (int fileNumber = 0; 100 > fileNumber; fileNumber++) {
// Open a file.
printFreeRam();
sprintf_P(filename, PSTR("t-%05.5d.dat"), fileNumber);
csvFile = SD.open(filename, FILE_WRITE);
if (csvFile) {
unsigned long fsize;
int x1, x2, x3, x4;
char data[60];
Serial.print(F("Writing to file: "));
Serial.println(filename);
printFreeRam();
for (int i = 0; 10000 > i; i++) {
x1 = random(1, 100);
x2 = random(1, 1000);
x3 = random(1, 1000);
x4 = random(1, 10000);
sprintf_P(data, PSTR("%d;%d;%d;%d;%d"), i, x1, x2, x3, x4);
csvFile.println(data);
fsize = csvFile.size();
Serial.print(F("Line: "));
Serial.print(1 + i);
Serial.print(F(", file size: "));
Serial.println(fsize);
delay(100);
}
Serial.println(F("Closing file "));
Serial.println(csvFile.name());
csvFile.close();
} else {
Serial.print(F("ERROR opening file: "));
Serial.println(filename);
printFreeRam();
}
}
Serial.println(F("Test completed!!"));
while (true) ;
}