Memory info

Is there a function I can call to see how much memory is left in RAM?


But this might help a few people:

  Free Memory detection
 From Arduino Cookbook
 Modified by WillR March 22, 2011
 Did I improve it or change it?
 Good Question!


// external variables from build process

//String mystring[] = "testing";

//unsigned long myVal;

void setup() {


} //end setup

void  loop()
  Serial.print("Free Memory:  ");
  Serial.println("  ");  

} //end loop

extern unsigned long __bss_end;
extern void *__brkval;

int memoryFree()
  //  long myValue;
  int freeValue;
  freeValue = 0;

  if ((unsigned long)__brkval == 0)
    freeValue = ((unsigned long)&freeValue) - ((unsigned long)&__bss_end);
    //       Serial.println("here and there");
    freeValue = ((unsigned long)&freeValue) - ((unsigned long)__brkval);
    //      Serial.println("here  2");

  return freeValue;

}//end memoryFree()

It seems to give reasonable answers.

You would also find this AVR-LIBC documentation interesting as it explains what is going on:

This topic comes up from time to time. The last time I remember was this:,50924 But if you search around a bit you'll find others, including in the old forums.

That looks pretty good. And throwing in malloc (100) into the loop gives this:

Free Memory:  1834  
Free Memory:  1732  
Free Memory:  1630  
Free Memory:  1528  
Free Memory:  1426  
Free Memory:  1324  
Free Memory:  1222  
Free Memory:  1120  
Free Memory:  1018  
Free Memory:  916  
Free Memory:  814  
Free Memory:  712  
Free Memory:  610  
Free Memory:  508  
Free Memory:  406  
Free Memory:  304  
Free Memory:  202  
Free Memory:  100  
Free Memory:  100  
Free Memory:  100

It looks like it uses 2 bytes more than the amount of memory you request (that sounds right, it has to store where the next piece of memory starts somewhere).

What a great function! Thanks so much.

I added it to the output and it shows my memory usage doesn't change between program executions. It does however show I am working with very little spare sram and therefore I can now use this number to whittle it down.


Don't thank me.

Thank this guy! ]:)

It has been worth every penny. I know how to do everything he points out in the book. What I did not know was how to do it efficiently on an Arduino. Nor did I really understand the C++/C paradigm.

Ignorance is not bliss. It sucks!

I think WillR intended this link: