Note: For Arduino 1.0, you have to replace
#include <WProgram.h>
with
#include <Arduino.h>.
The microcontrollers used on Arduino boards (ATmega8, ATmega168 and ATmega328) have a small amount of RAM.
In order to determine the amount of memory currently available the most accurate result can be found by using this MemoryFree library. It is based on code posted in the forum (here), extended to include walking the free list:
MemoryFree.h:
Example sketch:
Other simpler functions that compute how much memory you have free (but use dynamic allocation and deallocation of memory which may not be ideal):
// this function will return the number of bytes currently free in RAM
// written by David A. Mellis
// based on code by Rob Faludi http://www.faludi.com
int availableMemory() {
int size = 1024; // Use 2048 with ATmega328
byte *buf;
while ((buf = (byte *) malloc(--size)) == NULL)
;
free(buf);
return size;
}
Here is an alternative function:
/* This function places the current value of the heap and stack pointers in the
* variables. You can call it from any place in your code and save the data for
* outputting or displaying later. This allows you to check at different parts of
* your program flow.
* The stack pointer starts at the top of RAM and grows downwards. The heap pointer
* starts just above the static variables etc. and grows upwards. SP should always
* be larger than HP or you'll be in big trouble! The smaller the gap, the more
* careful you need to be. Julian Gall 6-Feb-2009.
*/
uint8_t * heapptr, * stackptr;
void check_mem() {
stackptr = (uint8_t *)malloc(4); // use stackptr temporarily
heapptr = stackptr; // save value of heap pointer
free(stackptr); // free up the memory again (sets stackptr to 0)
stackptr = (uint8_t *)(SP); // save value of stack pointer
}
Note: For my 2K ATMega328 system, the first simpler function gave me bogus random results and caused the system to hang. The second gave me consistent and I think accurate results.
Another method that seems to be even simpler is the following:
Declare this function:
int freeRam () {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
and call it anywhere in your program like that: Serial.println(freeRam());
In my test the results were quite similar with the first method, the one that uses the library. I found this function here: http://www.controllerprojects.com/2011/05/23/determining-sram-usage-on-arduino/