Worried about memory (RAM) usage

Hello there. I have two questions:

  • How a function receives an array or an "object"? Passed by value or by reference?
  • Any array or "object" created within a function, get actually "destroyed" when that function finishes?

Thanks beforehand...

  1. you have control of that
  2. unless you make it static

LarryD: I thought arrays were always passed by reference. Not right?

A naked array can not be returned from a function.

Arrays are passed by reference as addresses.

  1. you have control of that

How?

LarryD: I thought arrays were always passed by reference. Not right?

In fact, it will be so strange if not...

A naked array can not be returned from a function.

And what if I create a new one from a function and try to return it?

Arrays are passed by reference as addresses.

So, can I calmly create a void function if it receives an array?

And by the way, is there a way to output the free memory in runtime?

Thanks again...

You could use memcpy() to copy the array.

And one for merging two arrays? That's because why I asked how a function receives an array. Because I'm making a function that merges two arrays...

I think we're starting to get in trouble here.

Perhaps you could tell us in more detail what you want to do at a higher level?

All right then. I will tell you what's going on.
I'm actually trying to merge two character arrays. One is from a global variable (or constant), and the other is from the filename returned from a File object (SD library). I know, it might look complicated; but that's because I'm starting to distrust in the String objects.

This is my actual problem right now:

I've made a stereo WAV player with almost just my Arduino board; the only extra is an SD card module.
I'm using the TMRpcm library to accomplish this; and it playbacks the audio files very well (even the stereo ones), no complains for now.
Now I tried that, but playing all the files in a single directory (folder), one-by-one (like a MP3 player does). Now here's the problem: the player is in the 13th song (file); but when it attempts to go further, the board resets itself if the previous song plays until the end; or "freezes" and makes a funny (and very very loud) noise in the audio outputs, if I skip that 13th song. Clarifying: all the directory's files are valid for the library I'm using.
In conclusion, that's definitely a software problem, not a hardware problem.

I'm pretty sure that the auto-resetting and the "freezing" are caused by running out of memory (RAM).

Is that true? I was using the String class to concatenate directory's path and file's name. So, creating String objects over and over will fill up the memory? (Even if those are only used within a function?)

Auto-resets and freezing are not necessary out of memory. It's very well possible that you copy something to a byte / char buffer outside the boundaries of that buffer. E.g.

// 64 byte buffer
char buffer[64];
// place string terminator in the 65th element (that does not exist)
buffer[64]='\0';

Unless you know exactly how Strings (capital S) behave, you should not use them in my opinion.

void loop()
{
  String str = "abc";
}

What does this do exactly? Does it create a String object on the stack or will there be a part on the heap? Whatever is created on the stack will be 'cleared' when loop() terminates. But what happens with the part that possibly is created on the heap? Will it be removed as well?

I don't know and hence I will not use String.

Lucario448:
All right then. I will tell you what's going on.

It is better, in the Programming part of the forum, to post code, not try to describe it.

That's like going to a Musician's conference, and trying to describe your music, rather than playing it.

Duh, how fool am I. You are right, I forgot post all the code, sorry for that.

Now here it is:

/*
  This sketch demonstrates playing a stereo audio track using a single timer.

  16-24kHz sample rate recommended

  Steps:
  1. Edit pcmConfig.h
    a: On Uno or non-Mega boards, uncomment #define buffSize 128. May need to increase or lower sample rate.
    b: Uncomment #define STEREO_OR_16BIT

  2. Usage is as below. See https://github.com/TMRh20/TMRpcm/wiki/Advanced-Features#wiki-stereo-and-16-bit-playback for
   additional information.

*/

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

//#define SD_ChipSelectPin 53  //example uses hardware SS pin 53 on Mega2560
#define SD_ChipSelectPin 4  //using digital pin 4 on arduino nano 328, can use other pins

TMRpcm audio;   // create an object for use in this sketch
File songDir;
const char musicPath[] = "/music/";
const byte nextButton = 2;

void setup() {

  audio.speakerPin = 9; //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc
  pinMode(10, OUTPUT); //Pin pairs: 9,10 Mega: 5-2,6-7,11-12,46-45
  pinMode(nextButton, INPUT);

  if (!SD.begin(SD_ChipSelectPin)) {
    while (true) {} // Do nothing until reset
  }
  songDir = SD.open("/music");
  if (! playFirstSong()) {
    while (true) {} // Do nothing until reset
  }
}


void loop() {
  if (digitalRead(nextButton) == HIGH) {
    playNextSong();
    delay(300); // De-bouncer delay
  }
  if (! audio.isPlaying()) { // Plays the next song automatically when the current one finishes.
    playNextSong();
  }

}

boolean playFirstSong() {
  File song = songDir.openNextFile(); // Open the first file of the directory
  if (! song) { // If no file in the directory (even a "invalid" file will bypass the validation)
    return false;
  }
  while (song.isDirectory()) { // Keep going until we find an actual file
    song = songDir.openNextFile();
    if (! song) {
      return false;
    }
  }
  String name = String(musicPath);
  name.concat(song.name()); // I don't know how to concatenate character arrays directly
  byte length = name.length() + 1;
  char finalName[length];
  name.toCharArray(finalName, length);
  audio.play(finalName);
  // This function only receives a character array (file's path) instead of a File object, which is annoying
  // when dealing with a "dynamic" file list
  return true;
}

void playNextSong() {
  if (audio.isPlaying()) { // I don't know if the TMRpcm player would "overlap" one song to another.
    audio.stopPlayback();
  }
  File song = songDir.openNextFile();
  if (! song) { // If no more files in the directory
    songDir.rewindDirectory(); // Go back to the first file
    song = songDir.openNextFile(); // May this skip the very first file in the directory?
  }
  while (song.isDirectory()) {
    song = songDir.openNextFile();
    if (! song) {
      songDir.rewindDirectory();
      song = songDir.openNextFile();
    }
  }
  String name = String(musicPath);
  name.concat(song.name());
  byte length = name.length() + 1;
  char finalName[length];
  name.toCharArray(finalName, length);
  audio.play(finalName);
}
  name.concat(song.name()); // I don't know how to concatenate character arrays directly
  name += song.name ();

  char finalName[length];
  name.toCharArray(finalName, length);
  audio.play(finalName);

Instead of that, how about:

    audio.play(name.c_str ());

Ahhhhh nope. Just take a look of this compiler error:

Arduino:1.6.7 (Windows 7), Placa:"Arduino Nano, ATmega328"

C:\Users\Brayan\Documents\Arduino\Stereo_multifile_player\Stereo_multifile_player.ino: In function 'boolean playFirstSong()':

Stereo_multifile_player:69: error: invalid conversion from 'const char*' to 'char*' [-fpermissive]

   audio.play(name.c_str ());

                          ^

In file included from C:\Users\Brayan\Documents\Arduino\Stereo_multifile_player\Stereo_multifile_player.ino:19:0:

C:\Users\Brayan\Documents\Arduino\libraries\TMRpcm/TMRpcm.h:31:7: error:   initializing argument 1 of 'void TMRpcm::play(char*)' [-fpermissive]

  void play(char* filename);

       ^

C:\Users\Brayan\Documents\Arduino\Stereo_multifile_player\Stereo_multifile_player.ino: In function 'void playNextSong()':

Stereo_multifile_player:93: error: invalid conversion from 'const char*' to 'char*' [-fpermissive]

   audio.play(name.c_str ());

                          ^

In file included from C:\Users\Brayan\Documents\Arduino\Stereo_multifile_player\Stereo_multifile_player.ino:19:0:

C:\Users\Brayan\Documents\Arduino\libraries\TMRpcm/TMRpcm.h:31:7: error:   initializing argument 1 of 'void TMRpcm::play(char*)' [-fpermissive]

  void play(char* filename);

       ^

exit status 1
invalid conversion from 'const char*' to 'char*' [-fpermissive]

PD: and yes, "Brayan" is the username of the computer. And if the "code boxes" appear too large for a few lines... don't ask me why because I don't know...

Is that your function? "play"? If so, make it take a "const char *" argument. I don't see why a "play" function needs to modify the name of the file to play.

I've had to modify the library (h and cpp files) in order to make that work, but... still no luck. Now after the 13th file, the board neither resets, nor make funny noises in the audio output.
By the way, I already tried the concatenation with the strcpy and strcat functions (with the library untouched). The only change in the code, was in the playFirstSong and playNextSong functions, and it looks like this:

void playNextSong() {
  if (audio.isPlaying()) { // I don't know if the TMRpcm player would "overlap" one song to another.
    audio.stopPlayback();
  }
  File song = songDir.openNextFile();
  if (! song) { // If no more files in the directory
    songDir.rewindDirectory(); // Go back to the first file
    song = songDir.openNextFile(); // May this skip the very first file in the directory?
  }
  while (song.isDirectory()) {
    song = songDir.openNextFile();
    if (! song) {
      songDir.rewindDirectory();
      song = songDir.openNextFile();
    }
  }
  // Forming the neccesary string for the play function
  char finalName[20];
  strcpy(finalName, musicPath);
  strcat(finalName, song.name());
  audio.play(finalName);
}

It compiles with no problem; however, this doesn't solve my problem either. I could advance just one more file than before, and then... nothing happens.
What can I do now? Keep figuring out how to save memory, or look for another way to save the list of files? (in fact, I was thinking in an auto-generated list saved in another file, but I don't know if that would be a good idea)

Update: when trying to make the "automatic filelist", I noticed that it only printed out 12 files (of 49). Later, I suspected on this line of my code:

song = songDir.openNextFile();

Why? (you maybe wondering). Well; after some research on Google, I found something that took my attention. Someone in the C++ forum said something like "closing" a File class will release any resource occupied by it (including its part in the memory). So I tried that. Now that dubious part of the code looks like this:

song.close();
song = songDir.openNextFile();

Then I uploaded the modified sketch, and... BOOM! All the 49 files are now listed!

In conclusion: the problem here was in the openNextFile function. If you just re-assign a new File object into the same variable, then the previous File object will keep occupying space in memory. So I was creating a File object over and over, until the memory were full.

I learned the lesson: ALWAYS CLOSE A FILE IF YOU DON'T NEED IT ANYMORE!

Thank you for all the help you gave me!

And here is the file-listed version code of my WAV player, just in case you want to see it...

/*
  This sketch demonstrates playing a stereo audio track using a single timer.

  16-24kHz sample rate recommended

  Steps:
  1. Edit pcmConfig.h
    a: On Uno or non-Mega boards, uncomment #define buffSize 128. May need to increase or lower sample rate.
    b: Uncomment #define STEREO_OR_16BIT

  2. Usage is as below. See https://github.com/TMRh20/TMRpcm/wiki/Advanced-Features#wiki-stereo-and-16-bit-playback for
   additional information.

*/

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

//#define SD_ChipSelectPin 53  //example uses hardware SS pin 53 on Mega2560
#define SD_ChipSelectPin 4  //using digital pin 4 on arduino nano 328, can use other pins

TMRpcm audio;   // create an object for use in this sketch
File songDir;
File fileList;
const char musicPath[] = "/music/";
const char listPath[] = "Filelist.txt";
char currentSongPath[20];
const byte nextButton = 2;
const byte errorPin = 4;

void setup() {

  audio.speakerPin = 9; //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc
  pinMode(10, OUTPUT); //Pin pairs: 9,10 Mega: 5-2,6-7,11-12,46-45
  pinMode(nextButton, INPUT);
  pinMode(errorPin, OUTPUT); // Pulls HIGH if an error occurred
  digitalWrite(errorPin, LOW);

  if (!SD.begin(SD_ChipSelectPin)) {
    digitalWrite(errorPin, HIGH);
    while (true) {} // Do nothing until reset
  }
  songDir = SD.open("/music");
  if (! songDir) {
    digitalWrite(errorPin, HIGH);
    while (true) {} // Do nothing until reset
  }
  updateList();
//  while (true) {} // Uncomment this line if you just want to test the updateList function
  fileList = SD.open(listPath, FILE_READ);
  if (! fileList) {
    digitalWrite(errorPin, HIGH);
    while (true) {} // Do nothing until reset
  }
  playNextSong();
}


void loop() {
  if (digitalRead(nextButton) == HIGH) {
    playNextSong();
    delay(300); // De-bouncer delay
  }
  if (! audio.isPlaying()) { // Plays the next song automatically when the current one finishes.
    playNextSong();
  }

}

void playNextSong() {
  if (audio.isPlaying()) { // I don't know if the TMRpcm player would "overlap" one song to another.
    audio.stopPlayback();
  }
  fetchNextName();
  audio.play(currentSongPath);
}

void updateList() { // Known limitation: this will pick up even non-WAV files
  if (SD.exists(listPath)) {
    SD.remove(listPath);
  }
  fileList = SD.open(listPath, FILE_WRITE);
  if (! fileList) {
    digitalWrite(errorPin, HIGH);
    return;
    // Warns that the list failed to update. The program continues as normal, but with
    // a risk of an eventual "crash" (or simply get stuck and do nothing until reset)
  }
  File song = songDir.openNextFile();
  while (song) {
    while (song.isDirectory()) {
      song.close();
      song = songDir.openNextFile();
      if (! song) {
        break; // Break second while
      }
    }
    if (! song) {
      break; // Break first while
    }
    fileList.print(musicPath);
    fileList.println(song.name());
    song.close();
    song = songDir.openNextFile();
  }
  if (fileList.size() == 0) { // If the list is still empty
    digitalWrite(errorPin, HIGH);
    while (true) {} // Do nothing until reset
  }
  fileList.close();
}
// If created sucessfully (as it should), then there should be a file named "FILELIST.TXT" in the root
// directory of the SD card. This file should contain a complete list of the names of all files within
// the "music" directory, terminated by a empty line.

void fetchNextName() {
  // Known limitation: fetching a non-WAV file may cause an unexpected behavior, or program "crash"
  if (fileList.available() <= 0) { // aka "if reached the EOF or further (?)"
    fileList.seek(0);
  }
  byte index = 0;
  char currentChar = fileList.read();
  do {
    currentSongPath[index] = currentChar;
    currentChar = fileList.read();
    index++;
  } while ((currentChar != '\r') && (index < 20));
  fileList.seek(fileList.position() + 1); // Maybe I should add 2 instead
  if (index < 20) {
    currentSongPath[index] = 0; // Add the "null" character, aka "string terminator"
  } else {
    currentSongPath[19] = 0;
    // Or else, the string will be trimmed to 19 characters
    // WARNING: this may produce an invalid file path; thus, a program "crash"
  }
}

Well done. I suspected some sort of memory exhaustion, typical symptoms are things working "for a while". And yes, if you open a file it allocates things on the "heap". If you don't close it, the allocated memory is still there, even if you overwrite a reference to where it is.

It'd be nice if the File class's destructor would automatically close the file. It makes sense to me, anyway, that the file gets closed when the File object ceases to exist. I consider it a bug that it doesn't.