SouthernAtHeart:
This is driving me crazy! Been working for hours trying to get results. I made the example sketch below to show my problem. There are 2 places to do a Serial printing to show the value of entryName. I comment one out and run the other. If I run the one in the loop function, I get garbled values for the names. (see photo). If I run the serial print in the nextFile() routine, it prints out the names properly. I don't understand the * char and how it is keeping my characters in the variable entryName at all. Please help!#include <SPI.h>
#include <SD.h>
File dir;
char* entryName;
void setup() {
Serial.begin(9600); // Open serial communications and wait for port to open:
Serial.print("Initializing SD card...");
if (!SD.begin(10)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
dir = SD.open("/");
}
void loop() {
nextFile(); //move the next file into the variable entryName
//debug printing
// int len = strlen(entryName); //how long is the name?
// Serial.print(F("filename is: "));
// for (int i = 0; i < len; i++) {
// Serial.print(entryName[i]);
// }
// Serial.println();
delay(1000);
}
void nextFile() { //opens the next file on the SD card
File entry = dir.openNextFile();
if (! entry) { //there isn't a next file
entry.close(); //close the entry
dir.rewindDirectory(); //rewind
entry = dir.openNextFile(); //get the first file
}
entryName = entry.name();
entry.close();
//debug printing
int len = strlen(entryName); //how long is the name?
Serial.print(F("filename is: "));
for (int i = 0; i < len; i++) {
Serial.print(entryName[i]);
}
Serial.println();
}
You defined entryName as a pointer to a single character. So, the compiler treats it as a single character.
You assign entryName = file.name(); which loads entryName with the memory location where the filename is stored.
I think what you actually want is:
char entryName[100]; // 100 bytes to store the current filename.
if(strlen(entry.filename)<100){ //got to leave room for the terminating null
strcpy(entryName,entry.filename());
}
else {
sprintf(entryName,"Filename is too long, >99 bytes");
}
Serial.print(entryName);
The reason I copied it into a buffer, is that your code accesses the value after you have called
entry.close(). There is not guarantee the the memory address entryName points to is still valid.
Chuck.