'Data are not saved in the Arduino SD

I have created a code that takes temperature measurement data and saves it in a variable. Now I would like to save the data in a .txt file inside an SD card connected to Arduino. The initialization of the SD works, but when it manages to access the file it gives me errors, writing me a set of strange symbols instead of the file name and it doesn't write inside the file. I tried a very similar code to write inside the SD and it works fine. What problem can it be? I enclose the part of the writing code on the SD and the photo with the output. Initialization part:

Serial.println(F("Intializing SD card"));
if(!SD.begin(4))
{
  Serial.print(F("Initialization failed"));
  while(!SD.begin(4))
  {
    Serial.print(F("."));
    delay(1000);
  }
}
else Serial.println(F("Initialization done"));

Writing part:

sdFile = SD.open("records.txt",FILE_WRITE);
Serial.print("Writing to ");
Serial.println(sdFile.name());
sdFile.print(" Temperature: ");
sdFile.print(tempC);
sdFile.print(" taken at: ");
sdFile.print(hour());
sdFile.print(":");
sdFile.print(minute());
sdFile.print(":");
sdFile.println(second());

sdFile.close();

Image with the strange output



Solution 1:[1]

I suspect you are opening the SD card before it has a chance to initialise, to fix this, implement a check at the start like so:

if(!SD.begin(8)){ // Here, 8 is the CS (chip select) pin of your SD card.
Serial.println("initialization failed!");
    while (1);
}

sdFile = SD.open("records.txt",FILE_WRITE);

if(myFile){ // If we opened our file successfully!
// Write to our card here

}
sdFile.close();

Does this fix your issue? Also, watch out for size limitations on how large the Arduino can read SD cards. This is usually 2GB for full-size cards, and 16GB for "micro" cards.

Additional documentation can be found on the arduino website, as well as examples here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GhostDog98