Measuring Memory Usage

One way to diagnose memory problems is to measure how much memory is in use.

Flash

Measuring Flash memory usage is trivial. The compiler does that for you, every time you compile!

EEPROM

You are 100% in control of EEPROM usage. You have to read and write each byte to a specific address, so there is no excuse for not knowing exactly which bytes are in use!
// ************************************************
// Write floating point values to EEPROM
// ************************************************
void EEPROM_writeDouble(int address, double value)
{
   byte* p = (byte*)(void*)&value;
   for (int i = 0; i < sizeof(value); i++)
   {
      EEPROM.write(address++, *p++);
   }
}

// ************************************************
// Read floating point values from EEPROM
// ************************************************
double EEPROM_readDouble(int address)
{
   double value = 0.0;
   byte* p = (byte*)(void*)&value;
   for (int i = 0; i < sizeof(value); i++)
   {
      *p++ = EEPROM.read(address++);
   }
   return value;
}

SRAM

SRAM usage is more dynamic and therefore more difficult to measure. The free_ram() function below is one way to do this. You can add this function definition to your code, then call it from various places in your code to report the amount of free SRAM.

SRAM utilization is dynamic and will change over time. So It is important to call free_ram() at various times and from various places in your sketch to see how it changes over time.
int freeRam () 
{
  extern int __heap_start, *__brkval; 
  int v; 
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); 
}
What free_ram() is actually reporting is the space between the heap and the stack. it does not report any de-allocated memory that is buried in the heap. Buried heap space is not usable by the stack, and may be fragmented enough that it is not usable for many heap allocations either. The space between the heap and the stack is what you really need to monitor if you are trying to avoid stack crashes.
Last updated on 2015-11-20 at 04.42.55 PM Published on 2013-08-02 at 10.19.49 AM