I am pretty new with Arduino and programming in general.
I am playing with files in an SD card, using "SD.h" library. I tried most of the options and made them work correctly in a program. But I have found issues with listing files, and I got stuck.
Find below an example code (the original is embedded in a larger sketch, but this section is the one causing problems):
If I enter the command "dir" for the first time (list all files and folders) it prints all files and directories from my SD card correctly.
But if I enter "dir" again, then it only prints "done!".
Please find below results from the serial monitor when I enter "menu", then when I enter "dir" for the first time, and then when I enter "dir" for the second time:
Menu options:
'menu' - Menu options
'dir' - List files and directories
Command: menu
Menu options:
'menu' - Menu options
'dir' - List files and directories
I have tried using "rewindDirectory()", but I still get some weird behavior:
The first time I enter the "dir" command, I get all the files and folders.
The second time, I only get a few of them.
The third time, I get nothing (only "done!", like when I was not using "rewindDirectory()").
Please find below my modified code and the results in the Serial Monitor:
I guess I am not using "rewindDirectory()" correctly, but I cannot guess what would be the right way. I was looking at SD.h examples and this is how it was used...
As additional info: I tried reducing the number of files and folders in the SD. Using the same sketch, with "rewindDirectory()", now I get the following:
The first time I enter "dir" command: all files and folders are shown correctly.
The second time I enter "dir" command: all files and folders are shown correctly.
The third time, I start loosing some files.
The fourth time, I loose some more files.
The fifth time I get nothing.
Find below results:
Menu options:
'menu' - Menu options
'dir' - List files and directories
IIRC, the SD library can only handle four open files. You may need to close some. To start with, I'd try moving the opening of root to your print directory function. I also wonder if dir.openNextFile consumes one of those four.
I'd rewind at the start of printDirectory unconditionally too.
I think you got it!! Thanks a lot for your help, I would have never found it myself
I did not know that "SD library can only handle four open files". That is a very good point. And I was not realizing that the sketch keeps opening every file, but it never closes any file.
I just entered "entry.close()" at the very end of the "while" funcition.
So everytime I print a file name, I close this file.
It is working good now. I also tried adding a few more files and directories, and it keeps working on and on.