Hello everyone!
Here is what I want. First, write something to SD card. Then, unplug it for viewing on PC, plug it back in and be able to write to it again, without resetting the MCU. I have tried this:
#include <SD.h>
const byte pinSDCS= 8;//pin connected to SD's chip select
const byte pinHardwareSS=12;//ss pin of the mcu
File myFile;
void setup()
{
Serial.begin(9035);//this stands for 9600, because I have 17 MHz crystal instead of 16
pinMode(pinHardwareSS, OUTPUT);//ss pin must be output, otherwise spi will not work as master
Serial.println(F("type anything for a try..."));
Wait();
if (!SD.begin(pinSDCS)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
}
void loop()
{
static byte cnt;
cnt++;
Serial.print(F("Accessing SD card... attempt ")); Serial.println(cnt,DEC);
myFile = SD.open("test1.txt", FILE_WRITE);
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.println("testing 1, 2, 3.");
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
};
Serial.println(F("type anything for another try..."));
Wait();
}
void Wait(){
//purge input
while(Serial.available()){Serial.read();};
//wait for input
while (!Serial.available());
};
That is: wait, SD.begin, open-write-close, wait, open-write-close, wait, open-write-close, and so on.
While apparently working, it loses connection to sd card after a replug. See:
Serial log:
type anything for a try...
initialization done.
Accessing SD card... attempt 1
Writing to test.txt...done.
type anything for another try...
Accessing SD card... attempt 2
Writing to test.txt...done.
type anything for another try...
Accessing SD card... attempt 3
Writing to test.txt...done.
type anything for another try...
Accessing SD card... attempt 4
Writing to test.txt...done.
type anything for another try...
contents of test1.txt:
testing 1, 2, 3.
testing 1, 2, 3.
The card was reinserted between attempts 2 and 3. The file has 2 lines of text while it should have 4 of them.
I have also tried to reinitialize the SD for every attempt (that is, put SD.begin(...) into the loop), but that causes the initialization to fail and/or the sketch to crash on second attempt regardless of whether I reinserted the card or not.
So, what should I do to gain access to SD card after a replug?
Thanks in advance!