I'm mostly getting all the SD functions to work except that I can't get a directory list after reading a file. For example if I follow this sequence the last directory list won't work.
get directory list... works
get directory list... works
get contents of a file... works
get contents of a file... works
get directory list... this one never works
Could someone please help me figure out what I am doing wrong? Here is my code,
#include <SD.h>
char inChar;
File MyFile;
File MyDir;
void setup() {
Serial.begin(9600);
Serial.println ("Starting...");
if (!SD.begin(8)) Serial.println("Card failed, or not present");
}
void loop() {
if (Serial.available()){
inChar = (char)Serial.read();
switch (inChar){
case 'D': // Directory
MyDir = SD.open("/");
if (MyDir){
SdDirPrint(MyDir, 0);
MyDir.close();
Serial.println ("Finished listing directory");
}else{
Serial.println ("Couldn't open directory");
}
break;
case 'W': //Write a file
MyFile = SD.open("datalog.txt", FILE_WRITE);
if (MyFile) {
for (int index = 1; index < 10; index++){
MyFile.print("Line ");
MyFile.println (index);
}
MyFile.close();
Serial.println("Finished writing.");
} else {
Serial.println("error opening file for write");
}
break;
case 'R': //Read a file
MyFile = SD.open("datalog.txt", FILE_READ);
if (MyFile) {
while (MyFile.available()) {
Serial.write(MyFile.read());
}
MyFile.close();
Serial.println("Finished reading");
}else{
Serial.println ("Couldn't open file for read");
}
break;
}
Serial.println ("");
}
}
void SdDirPrint(File dir, int numTabs) {
while(true) {
File entry = dir.openNextFile();
if (! entry) {
dir.rewindDirectory();
break;
}
for (uint8_t i=0; i<numTabs; i++) {
Serial.print('\t');
}
Serial.print(entry.name());
if (entry.isDirectory()) {
Serial.println("/");
SdDirPrint(entry, numTabs+1);
} else {
// files have sizes, directories do not
Serial.print("\t\t");
Serial.println(entry.size(), DEC);
}
entry.close();
}
}