Hello,
I have a question regarding the SD card library.
Given that SD cards have a limited amount of write and erase cycles, is it better for a data-logging application to concatenate all the variables into a char array, including the delimiters, and then perform a single file.print() with the array?
Is each usage of file.print() a separate write cycle?
Or does it make no difference to just file.print() each variable and delimiter separately?
Also, is there any speed advantage with using the concatenation method?
I made 2 working methods below to illustrate what I'm comparing.
Thanks!
#include <SPI.h>
#include <SD.h>
File myFile;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
Serial.print("Initializing SD card...");
if (!SD.begin(10)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");
SD.remove("test.txt");
int var1 = 111;
unsigned long var2 = 222;
unsigned int var3 = 333;
char var4[11] = "helloworld";
float var5 = 4.44;
//METHOD 1; concatenating variables into char array
char array_to_print[100];
//convert float to char
char var5_to_Char[5];
dtostrf(var5, 3, 2, var5_to_Char);
sprintf(array_to_print, "<%d,%lu,%d,%s,%s>\n",var1,var2,var3,var4,var5_to_Char);
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.print(array_to_print);
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
//METHOD 2; printing each variable and delimmiter individually
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.print("<");
myFile.print(var1);
myFile.print(",");
myFile.print(var2);
myFile.print(",");
myFile.print(var3);
myFile.print(",");
myFile.print(var4);
myFile.print(",");
myFile.print(var5);
myFile.println(">");
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}
void loop() {
// nothing happens after setup
}