File names from Arduino SD card module to Array

960 views c++
-2

I'm trying to make a simple wav player using arduino and the SD card module, i've barely started and have already encountered some problems. I need to get all the file names from a specific folder inside the SD card and save them to an array. My first problem was, i needed an array that could change sizes during the runtime. After researching a litle bit i found this solution on the code, is it the best way to do it? Second, whenever i run the code, i get diferent outputs, sometimes some song names show up, sometimes they don't. They never show up every song name correctly. And third, when the song name shows up, it is incomplete.

My folder structure is:

MUSIC/
    HakunaMatata1.wav
    HakunaMatata2.wav
    HakunaMatata3.wav
    HakunaMatata4.wav
    HakunaMatata5.wav
    HakunaMatata6.wav
    HakunaMatata7.wav
    HakunaMatata8.wav

My Serial output looks like:

Program started
SD initialization done.
Songs found:8
Songs List:
HAKUNA~1.WAV

HA1170~1.WAV
HA899A~1.WAV

And finally, my code:

#include <SPI.h>
#include <SD.h>

#define path "/music"
#define CSPin 53

String *songList;
File dir;
int nSongs = 0;


void setup() {
  Serial.begin(9600);
  while(!Serial){
  }

  Serial.println("Program started");
  if (!SD.begin(CSPin)) {
    Serial.println("SD initialization failed!");
    while (1);
  }
  Serial.println("SD initialization done.");

  dir = SD.open(path);
  listSongs(dir);
}

void loop() {
  // put your main code here, to run repeatedly:

}



void listSongs(File folder){
  nSongs = 0;

  while(true){
    File entry = folder.openNextFile();
    if(!entry){
      folder.rewindDirectory();
      break;
    }else{
    nSongs++;
    }   
    entry.close();
  }

  Serial.print("Songs found:");
  Serial.println(nSongs);

  songList =(String*) malloc(nSongs);

  Serial.println("Songs List:");

  for(int i = 0; i < nSongs; i++){
    File entry = folder.openNextFile();
    songList[i] = entry.name();
    entry.close();
    Serial.println(songList[i]);
  }
}

Wiring is probably correct since the SD card initializes correctly but, here it is:

SD CARD MODULE     ARDUINO MEGA
GND                GND
MISO               50
SCK                52
MOSI               51
CS                 53
5V                 5V

answered question

Probably you need array of strings (may be pointer to pointer) and how is String defined in your case because C standard does not support String?

@kiranBiradar String is Arduino's equivalent to standard's std::string.

1 Answer

4

You've got two problems in this line of code:

songList =(String*) malloc(nSongs);

First, you're not allocating enough memory and second, you'll end up with uninitialized Strings.

Since this is C++, the easiest way to fix this is to use new instead of malloc:

songList = new String[nSongs];

posted this

Have an answer?

JD

Please login first before posting an answer.