SD card shield v4

The CardInfo sketch works fine.

I am trying to write a simple text file to the SD card.
I am getting error message Error opening Data.txt which means the SD.open( ) failed.
Data.txt does not exist but according to the documentation the file should be created.

I am not sure what I am doing wrong as this sketch is based on an example sketch for the SD library.

#include <SD.h>
#include <SPI.h>


const int chipSelect = 4;

Sd2Card card;

void setup()
{
    Serial.begin(9600);

    //pinMode(10, OUTPUT);
    
    while (!Serial) 
    {
        ; // wait for serial port to connect. Needed for native USB port only
    }
     
    if (!card.init(SPI_HALF_SPEED, chipSelect))
    {
        Serial.println("Initialization failed.");
        return;
    }
    else
    {
        Serial.println("Initialization passed.");
    }
}

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);

}

Hi,

We have made few changes in your code so that it works.
Please find the modifies version below.

[code]#include <SD.h>
#include <SPI.h>

const int chipSelect = 4;

void setup()
{
Serial.begin(9600);

while (!Serial)
{
; // wait for serial port to connect. Needed for native USB port only
}

if (!SD.begin(chipSelect))
{
Serial.println(“Initialization failed.”);
return;
}
else
{
Serial.println(“Initialization passed.”);
}
}

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);

}

[/code]

Thanks and Regards

Thank you.

That works.