diff --git a/examples/FreeRam/FreeRam.ino b/examples/FreeRam/FreeRam.ino index 9af5fe5..02724b6 100644 --- a/examples/FreeRam/FreeRam.ino +++ b/examples/FreeRam/FreeRam.ino @@ -3,6 +3,7 @@ void setup() { Serial.begin(115200); + Serial.println(F( "Running " __FILE__ ", Built " __DATE__)); Serial.println(F("Starting state of the memory:")); Serial.println(); @@ -17,9 +18,14 @@ void setup() Serial.println(); FREERAM_PRINT; + + //byte *p = new byte[3000]; + byte *p = new byte[300]; // Uno (ATmega328) only has 2k RAM - byte *p = new byte[3000]; - + if(!p) { + Serial.println(F("could not allocate bytes for p[] array!")); + } + Serial.println(); Serial.println(); @@ -37,6 +43,9 @@ void setup() Serial.println(); FREERAM_PRINT; + + delete p; + p = 0; } void loop() diff --git a/examples/GetMemorySize/GetMemorySize.ino b/examples/GetMemorySize/GetMemorySize.ino new file mode 100644 index 0000000..c56ab0f --- /dev/null +++ b/examples/GetMemorySize/GetMemorySize.ino @@ -0,0 +1,53 @@ +#include + +// Simple example to report memory sizes + +void reportAllocation(int numBytes) { + + Serial.print(F("Allocating for ")); + Serial.print( numBytes ); + Serial.print(F(" bytes; ")); + + byte *p = new byte[numBytes]; + + if (p) { + Serial.println(F("...success.")); + } else { + Serial.println(F("...allocation FAILED")); + } + + MEMORY_PRINT_HEAPSIZE + FREERAM_PRINT + + Serial.println(F("\ndeleting byte array with delete")); + delete p; // don't want a memory leak! + p = 0; // don't want a dangling/obsolete pointer + + MEMORY_PRINT_HEAPSIZE + FREERAM_PRINT +} + +void setup() { + Serial.begin(115200); + delay(1000); + Serial.println(F( "Running " __FILE__ ", Built " __DATE__)); + + Serial.println(F("\nStarting conditions")); + MEMORY_PRINT_TOTALSIZE + MEMORY_PRINT_HEAPSIZE + FREERAM_PRINT + + Serial.println(F("\nallocate a byte array with new; too big to fit in RAM?")); + reportAllocation(3000); + + Serial.println(F("\nallocate smaller byte array with new (it should fit)")); + reportAllocation(300); + + Serial.println(F("\nFinal conditions")); + MEMORY_PRINT_HEAPSIZE + FREERAM_PRINT +} + +void loop() { + // User reads output from setup(). +} diff --git a/src/MemoryUsage.h b/src/MemoryUsage.h index 0cc1f2b..11b21fd 100644 --- a/src/MemoryUsage.h +++ b/src/MemoryUsage.h @@ -136,7 +136,7 @@ extern uint8_t *__bss_end; /// Print free ram size on serial console. #define MEMORY_PRINT_FREERAM { Serial.print(F("Free ram:")); Serial.println((int) SP - (int) (__brkval == 0 ? (int)&__heap_start : (int)__brkval)); } /// Print total SRAM size on serial console. -#define MEMORY_PRINT_TOTALSIZE { Serial.print(F("SRAM size:")); Serial.println((int) RAMEND - (int) &__data_start); } +#define MEMORY_PRINT_TOTALSIZE { Serial.print(F("SRAM size:")); Serial.println(((int) RAMEND + 1 - (int) &__data_start)); } /// Displays the 'map' of the current state of the Arduino's SRAM memory on the Serial console. void SRamDisplay(void);