Hello. I have a problem with my microSD card used with an ethernet shiled and a mega 2560.
The problem is that SD.begin(pin) in the setup fails if:
- I write the card 2) I don't cancel the files 3) I reset arduino
If these 3 things do not happen everything works fine (open, write, cancel, create ecc..) for example if i write on a file, cancel it and reset arduino the sdBegin succeed.
If I read from a computer the file written on the SD it always looks like to be correct.
This is how I initialize the sd:
//initialize SD SETUP->SD
Serial1.println("Initializing SD card...");
// disable w5100 SPI while setting up SD
pinMode(10,OUTPUT);
digitalWrite(10, HIGH);//for arduino mega http://arduino.cc/forum/index.php/topic,46976.0.html
// On the Ethernet Shield, CS is pin 4. It's set as an output by default.
// Note that even if it's not used as the CS pin, the hardware SS pin
// (10 on most Arduino boards, 53 on the Mega) must be left as an output
// or the SD library functions will not work.
pinMode(53, OUTPUT);
digitalWrite(53, HIGH);
if (!SD.begin(4)) {
Serial1.println("cant save on SD!");
noSd=true;
}
else{
Serial1.println(F("SD inizialized"));
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
mioFile = SD.open("valori.txt", FILE_WRITE);
if (mioFile) {
Serial1.print("file opened");
if(mioFile.available()>0 )
sdScritta=true;
mioFile.close();
Serial1.println("done.");
} else {
// if the file didn't open, print an error:
Serial1.println(F("error opening valori.txt"));
}
}
this is where I write:
mioFile = SD.open("valori.txt", FILE_WRITE);
if (mioFile) {
Serial1.println(perServer);
mioFile.println(perServer);
// close the file:
mioFile.close();
sdScritta=true;
Serial1.println("done.");
and here I read one line
while (mioFile.peek()!='\r' && mioFile.peek()!=EOF)
{
stringaTemp+=(char)(mioFile.read());
}
Serial1.write(mioFile.read());//cattura il carattere di a capo
Serial1.write(mioFile.read());
Serial1.println(stringaTemp);
Serial1.println("fine di una riga");
and here I cancel the file
if(mioFile.peek()==-1){
Serial1.println("cancel old file");
mioFile.close();
SD.remove("valori.txt");
mioFile = SD.open("valori.txt", FILE_WRITE); //create new one
sdScritta=false;
nRiga=0;
}
If I phisycally eject the SD,put it inside again with the same file written and only after I reset it works!
Do you know if anything is wrong?
Thanks in advance for the time you will spent