Arduino Uno SRAM

arduinosram

After countless hours trying to debug my 'was working fine with MEGA' code, i have diagnosed the issue to my SRAM. I except that my code (a combination of NTPClient, EthernetClient & various sensor readings that cover all available pins), is maybe too much work for the UNO & will be switching over to the MEGA.

However, during the debug i used free_ram() function below:

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

The output, with just the function in the source was around 1800 mark (about right if the UNOs limit is 2k). When i used this function with the full code, it read at -351. i expected 0 (zero) or above…

(in case the reader is interested, the MEGA's free_ram output was 7463)

My question is simple, what is the lowest limit reading of SRAM, using the function detailed?

Best Answer

A negative result for that function is indeed possible. It indicates that you are trying to use more memory than you have.

The value returned is the difference between the start of the heap and the location of the stack.

If you allocate too many global or static variables then it is possible for the heap start to be very close to where the top of the stack is, and as your program runs and local variables are allocated and the stack used by function calls, the stack pointer can end up lower in memory than the start of the heap.

So you end up with a negative value.

Further to that, the stack smashing into the heap like that causes memory corruption and strange things happen to your sketch.