I am using Arduino Uno and the Ethernet Shield with a 2GB SD Card. I have the following working code intended to be used to write data on the SD Card (note: the SD Library is properly initialized and I just hide the reated code in order to keep things smaller):
class Logger {
private:
File myFile;
char *myFilename;
public:
Logger (char *myFilename = "text.txt") : myFilename(myFilename) {
myFile = SD.open(myFilename, FILE_WRITE);
}
void writeAction () {
if (myFile) {
myFile.print("Sample text.");
myFile.close();
} else {
Serial.print("Error opening the file ");
}
}
};
void setup() {
Logger logger;
...
logger.writeAction();
}
However, if I change a bit the above code as made in the following one, it will not work as expected: the "Sample text."
is not written / saved on the SD card.
class Logger {
private:
File myFile;
char *myFilename;
public:
Logger (char *myFilename = "text.txt") : myFilename(myFilename) {
// Note: Here is the change. File opening statements are moved
// "inside" the writeAction function.
}
void writeAction () {
myFile = SD.open(myFilename, FILE_WRITE);
if (myFile) {
myFile.print("Sample text.");
myFile.close();
} else {
Serial.print("Error opening the file ");
}
}
};
void setup() {
Logger logger;
...
logger.writeAction();
}
Why does it happen? How can I make the myFile
to be properly opened and closed "inside" the writeAction
function?
text.txt
if it already exits? \$\endgroup\$myFile = SD.open(myFilename, FILE_WRITE);
in your second code? \$\endgroup\$