How to obtain the free RAM in Arduino?

ArduinoHardwareSoftware & Coding

The Arduino-MemoryFree library can be used to obtain the free RAM within your Arduino. In order to use this library, install it first. The instructions to install a third-party library in Arduino are given here: https://www.tutorialspoint.com/using-a-third-party-library-in-arduino

Once installed, go to: Files → Examples → Arduino-MemoryFree.

Example

As you can see the BareMinimum example lives up to its name. It is very short indeed.

#include <MemoryFree.h>;
#include <pgmStrToRAM.h>; // not needed for new way. but good to have for reference.

void setup() {
   // put your setup code here, to run once:
   Serial.begin(115200);

   // forced to be compiled into and read
   Serial.println(getPSTR("Old way to force String to Flash"));

   // forced to be compiled into and read
   Serial.println(F("New way to force String to Flash"));

   //F function does the same and is now a built in library, in IDE > 1.0.0
   Serial.println(F("Free RAM = "));

   // print how much RAM is available.
   Serial.println(freeMemory(), DEC);
   // print how much RAM is available.
}

void loop() {
   // put your main code here, to run repeatedly:
}

The main function of interest is freeMemory(), which returns the amount of free RAM in the Arduino in bytes. As is mentioned in the comments, the following lines are no longer needed.

#include <pgmStrToRAM.h>;

// forced to be compiled into and read
Serial.println(getPSTR("Old way to force String to Flash"));

They have been added to show the difference between the older way of storing string to flash and the newer way (which uses the F() macro).

raja
Updated on 26-Jul-2021 11:20:46

Advertisements