I have an Arduino Mega connected to an SD card reader (Catalex branded), that at least detects the card as it displays the info of the card. But when I try to create a file, it does not create it. I am using the following code:
if (SD.exists("data.txt")) {
Serial.println("data.txt exists.");
} else {
Serial.println("data.txt doesn't exist.");
}
File root=SD.open("data.txt", FILE_WRITE); //open of the File for writting
if (SD.exists("data.txt")) {
Serial.println("data.txt exists.");
} else {
Serial.println("data.txt doesn't exist.");
}
I also tried with this code:
File root2 = SD.open("file.txt", O_RDWR | O_APPEND);
if (!root2) {
// It failed, so try and make a new file.
root2 = SD.open("file.txt", O_RDWR | O_CREAT);
if (!root2) {
// It failed too, so give up.
Serial.println("Failed to open file.txt");
}
}
[Update]
I also tried with this easier code and it does not work either:
#include <SD.h>
const int chipSelect = 10;
Sd2Card card;
void setup() {
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
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:
return;
}
Serial.println("card initialized.");
}
void loop() {
File myFile = SD.open("Data.txt", FILE_WRITE);
if (myFile) {
for (int i = 0; i < 101; i++) {
myFile.print(i);
myFile.print(" multiplied by two is ");
myFile.println(i * 2, DEC);
}
Serial.println("Finished");
myFile.close();
} else {
Serial.println("Error opening Data.txt");
}
//do nothing else
do { } while(1);
}
-
I don't think it should matter, but can you try to close the file after opening and before the exists call?Michel Keijzers– Michel Keijzers07/18/2017 08:53:42Commented Jul 18, 2017 at 8:53
-
@MichelKeijzers Yes i tried it and it neither workMiguel Sanz Narrillos– Miguel Sanz Narrillos07/18/2017 08:59:24Commented Jul 18, 2017 at 8:59
-
You can try to format the card in a different format (I don't know which formats are supported by the library), also you can check if the file really is created (on a PC) or that the exists fails.Michel Keijzers– Michel Keijzers07/18/2017 10:03:19Commented Jul 18, 2017 at 10:03
-
@MichelKeijzers i do not why i open a new code file and copy the code and it worked. thanks for the helpMiguel Sanz Narrillos– Miguel Sanz Narrillos07/18/2017 10:32:40Commented Jul 18, 2017 at 10:32
-
Glad you can continue nowMichel Keijzers– Michel Keijzers07/18/2017 10:39:03Commented Jul 18, 2017 at 10:39
2 Answers 2
// open a new file and immediately close it:
Serial.println("Creating example.txt...");
myFile = SD.open("example.txt", FILE_WRITE);
myFile.close();
This is what you missed (I guess..).
Please see the link and check the steps followed:
https://www.arduino.cc/en/Tutorial/Files
If you want to make it sure it will not have problem with SD card format then format it to FAT it's most compatible format type.