Determining SRAM Usage on Arduino

Doing a project, I ran into a limitation where I believed that I was using up all 2k of RAM on my Arduino (ATMega328).  I stumbled across a post on http://jeelabs.org/2011/05/22/atmega-memory-use/ that gave me what I needed to diagnose that scenario.

The only symptom I had was intermittent jumbled text (with ascii characters mixed in) for my Serial.print() commands and the fact that it would intermittently lock up and/or reboot.

The Arduino IDE shows at compile time how much flash it is using, but it unfortunately doesn’t give any indication for RAM.

As stated on the JeeLabs site:

There are three areas in RAM:

  • static data, i.e. global variables and arrays … and strings !
  • the “heap”, which gets used if you call malloc() and free()
  • the “stack”, which is what gets consumed as one function calls another

The heap grows up, and is used in a fairly unpredictable manner. If you release areas, then they will be lead to unused gaps in the heap, which get re-used by new calls to malloc() if the requested block fits in those gaps.

At any point in time, there is a highest point in RAM occupied by the heap. This value can be found in a system variable called __brkval.

The stack is located at the end of RAM, and expands and contracts down towards the heap area. Stack space gets allocated and released as needed by functions calling other functions. That’s where local variables get stored.

The trick is to keep RAM usage low, because it’s a scarce resource: an ATmega has a mere 2048 bytes of RAM.

So, to use those variables and concepts to show RAM usage, you can utilize the following function:

int freeRam () {
  extern int __heap_start, *__brkval; 
  int v; 
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); 
}

 

Just call it, not passing any parameters, and it will return the remaining bytes of ram.

i.e.:  Serial.println(freeRam());

I ended up (at one point) showing that freeRam() returned 64 then very shortly afterwards the arduino rebooted.  That’s a smoking gun that it’s a RAM issue.  Time to do some code optimization

Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>