I have an Arduino Mega 2560 and Arduino Ethernet shield with SD card slot and 4 gig SD card. I am getting an SD Fail error most of the time. Sometimes it works but mostly it fails. So it is never exiting SETUP without a fail. The simple test sketch I am using to test is:
#include <SD.h>
#include <SPI.h>
File myFile;
int j; //loop counter
char kwh[10];
float testk = 10.00;
float results;
void setup() {
Serial.begin(9600);
pinMode(53, OUTPUT);
//pinMode(10, OUTPUT);
while (!SD.begin(53)) {
Serial.println("SD fail");
return; }
if (SD.begin(53)) Serial.println("SD card ready");
}
void loop() {
Serial.println("Start of test");
myFile = SD.open("test.txt", FILE_WRITE); //open file for writing
if (myFile) {
Serial.println("Open file test for Write");
myFile.seek(0); //set to write to first byte of file
myFile.println(testk);
myFile.close(); //save kilowattHour to file
myFile = SD.open("test.txt");
j = 0;
do {
// test for kwh full
if (j == sizeof(kwh)) {
Serial.println("line too long");
break; }
kwh[j] = myFile.read(); }
while (kwh[j++] != '\r');
results = atof(&kwh[0]);
myFile.close();
Serial.print("Read from SD card: ");
Serial.println(results);
} // end of if myfile code
else {
// if the file didn't open, print an error:
Serial.println("error reading test.txt");
}
testk++;
} // LOOP end
I don’t know why it is not working. I tried various CS pins and BEGIN statements but nothing works. This shouldnt be so hard!! Ideas?