Counting Files on SD Card Directory With Arduino
**DRAFT**
Randomly choosing a file isn't hard if you know the file name that exist on your SD card. But, I didn't want to reprogram my doorbell every time I wanted to update the sounds that played when the button was pressed.
We'll be going through the process on how I did it with a working example.
Counting Files Within an SD Card Directory
int getFileCount( String dir )
{
File d = SD.open( dir );
int count_files = 0;
while( true )
{
File entry = d.openNextFile();
if( !entry )
{
// no more files. Let's return the number of files.
return count_files;
}
String file_name = entry.name(); //Get file name so that we can check
//if it's a duplicate
if( file_name.indexOf('~') != 0 ) //Igrnore filenames with a ~. It's a mac thing.
{ //Just don't have file names that have a ~ in them
count_files++;
}
}
}
NOTE: When copying files to your SD card using a Mac, it will duplicate your files with _FILE~1.mp3 type of name. I had to add the following code to the function to have it count properly.
Before:
count_files++;
After:
String file_name = entry.name();
if( file_name.indexOf('_') != 0 )
{
count_files++;
}
Think of the possibilities of a doorbell that plays sound clips according to the time of day, season or just because the Star Wars theme song is awesome!
**DRAFT**
comments powered by DisqusArduino sd card counting files random
Views: 6376