There are several points in your code’s execution journey where the amount of available RAM maybe important. It helps a lot during development, and depending on your application, some runtime decisions may also be taken based on this value. For example, if your application can disallow further Bluetooth connections if the available memory falls below a threshold that can affect the functioning of other tasks.
Luckily, we need not do much to get this value. There are readymade functions available, that give out the value in bytes. Let’s have a look at them:
Overall Free Memory
If you want to get overall free memory available, use the function esp_get_free_heap_size(). An example usage (in ESP-IDF) is:
static const char *TAG = "Main File"; ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
This prints the available memory in bytes. The equivalent statement in Arduino IDE is:
Serial.println("[APP] Free memory: " + String(esp_get_free_heap_size()) + " bytes");
Task-specific free memory
There’s another function that comes in handy when you have multiple tasks running. At any given point, a task cannot occupy more memory than the allocated stack. The function uxTaskGetStackHighWaterMark() tells you, at any point, the minimum amount of stack space available to the task so far. The syntax is
As you can see, it takes the task handle as the input. If you call this from within a task, then you can pass NULL in place of the task handle, to get the watermark for that particular task. Example implementation (ESP-IDF):
static const char *TAG = "THISTASK"; ESP_LOGI(TAG, "This Task watermark: %d bytes", uxTaskGetStackHighWaterMark(NULL));
The equivalent of the above statement for Arduino IDE is:
Serial.println("This task watermark: " + String(uxTaskGetStackHighWaterMark(NULL)) + " bytes");
If you subtract the output of this function from the stack size allocated to your task, you can get the maximum memory occupied by the task during its execution so far. Note that the output of this function can only decrease with time, if the task takes up larger and larger stack space during the course of its execution.
This function can help predict stack overflow and can prompt you to allocate larger stack space to your task, or optimize the code execution.