Arduino Available Memory Test

arduino_extreme_260.jpg

I’ve been meaning to make a nice little function to test available memory for some time, so tonight in response to a mailing list question, I went ahead and created an Arduino Available RAM Test for exploring memory allocation.

While I’m still learning about AVR’s memory management, here’s what I understand so far: The ATMEGA8 has 8K of program memory but only 1K of RAM. (Program memory is for code and RAM is for dynamic variables.) Actually it’s effectively less than 1K of RAM, I think because the Arduino libraries take up some dynamic memory space for themselves. The ATMEGA168 increases program memory to 16K, but RAM remains unchanged at 1K.

The Arduino environment will happily let you compile a program that exceeds the microcontroller’s RAM limits, however program behavior will become totally unpredictable, the code will do bizarre things and/or crash. It is equally difficult to describe the negative emotional results for the coder. Dysphoria comes to mind.

Hopefully, the Arduino Available RAM Test code can provide a pathway back to happiness, or at least cathartic understanding.

3 Comments on “Arduino Available Memory Test

  1. Hi rob, thanks for the memory test code. It prompted a couple of questions:
    1) Is the memory needed for all functions generally allocated from the beginning or just when the function is activated.

    2) The test shows 158 bytes free anywhere I put it in my program (loop, setup, subroutine, even inside an interrupt) does that make sense and does it seem like enough? It seems ok to me.

    • Available memory may remain static or change constantly depending upon the specifics of your code. So if you use the test in different types of programs you’ll see different behaviors. If your program is running fine then you have enough free memory. The 168 chip only has 1,024 bytes of RAM so it looks like you still have about 16% unused.

  2. The code seems to no longer work on recent boards, though I don’t really get why. It returns a (seemingly) fixed number as Bill Rowe described, which can vary from sketch to sketch, but is entirely unaffected by, for example, malloc()’ing more memory. E.g. getting free memory, mallocing 128 bytes, then checking free memory again using this method will return the same result both times, not the expected 128 less the second time around.

    There seems to be a working solution, though:
    http://forum.pololu.com/viewtopic.php?f=10&t=989#p4218

    “extern void __bss_end;” needs to be declared “extern int __bss_end;”, otherwise the current arduino environment complains, but it does return sensible values, which change as expected.