This is my first post so I hope I am doing it all correctly. I am incorporating the following code into a larger project but am having trouble with the SD file read. The
two “functions” at the end of the sketch are basically copies of the sample files included
with the SD library. I just attached a two item menu to select one or the other.
The directory read works perfectly. The file read works perfectly “ONCE”. The second
time I select the read file option, I immediately get the “Card failed, or not present”
error. I would appreciate any ideas as to why this is so.
Larry
#include <PS2Keyboard.h>
#include <SPI.h>
#include <SD.h>
Sd2Card card;
SdVolume volume;
SdFile root;
const int chipSelect = 53;
PS2Keyboard keyboard;
File myFile;
//////////////////////////////////
void setup() {
keyboard.begin(10, 3);
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect.
}
}
// end setup
/////////// loop ////////////////
void loop() {
Serial.print ("\nSelect from following menu");
Serial.print ("\nd - SD card directory ");
Serial.print ("\nr - read file ");
while (!keyboard.available());
char c = keyboard.read();
Serial.print(c);
// switch here
switch (c) {
case'r':
readfile();
break;
case'd':
directory();
break;
}
} // end loop
/////// function declarations ///////
////// directory function ///////
void directory() {
Serial.print("\nInitializing SD card...");
if (!card.init(SPI_HALF_SPEED, chipSelect)) {
Serial.println("\nInitialization failed.");
return;
}
else {
Serial.println("\nCard is present.");
}
volume.init(card);
Serial.println("\nFiles found on the card ");
root.openRoot(volume);
// list all files in the card
root.ls(LS_R );
} // end directory function
///////// read file function ////////
void readfile() {
if (!SD.begin(chipSelect)) {
Serial.println("\nCard failed, or not present");
// don't do anything more:
return;
}
Serial.println("\ncard initialized.");
myFile = SD.open("test2.csv", FILE_READ);
if (myFile) {
Serial.println("test2.csv:");
// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
} // end readfile function