0
\$\begingroup\$

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?

\$\endgroup\$
  • \$\begingroup\$ Using unsigned integers will possibly help. The code seems to assume that __brkval and __heap_start are after local variables in memory, which may not be true for the Mega. \$\endgroup\$ – David Mar 7 '15 at 17:36
  • \$\begingroup\$ The Arudino Uno and Mega run at exactly the same speed. You will not solve the problem of the processor being too busy by switching. \$\endgroup\$ – Austin Mar 7 '15 at 19:59
  • \$\begingroup\$ @David, the layout of memory segments depends on the compiler. Since the two boards use the same CPU and the same compiler, it will be the same. \$\endgroup\$ – Austin Mar 7 '15 at 20:00
  • \$\begingroup\$ I found this article (learn.adafruit.com/memories-of-an-arduino/…) very helpful when I was first studying embedded programming using an Arduino. Hopefully it is helpful to future readers of this question. \$\endgroup\$ – shredalert Nov 28 '18 at 15:40
3
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.