Configuring Memory

FreeRTOS has two memory allocation schemes: Static and dynamic allocation. Static memory allocation requires the application itself to allocate and deallocate memory. This can be more difficult to implement but provides more control. When using the dynamic allocation scheme, the memory allocation occurs automatically within the API functions. The application only has to call the create and delete functions. To use dynamic allocation, set the configSUPPORT_DYNAMIC_ALLOCATION define in the configuration file to 1.

With dynamic allocation, FreeRTOS needs to have a portion of RAM allocated for an area called the heap. FreeRTOS functions ending with “Create” allocates memory on the heap. When creating a task by calling xTaskCreate(), the memory will be allocated on the heap for that particular task consisting of a stack and a task control block (TCB). The task stack size is defined when creating the task. Queues, mutexes, and semaphores will also allocate heap memory when created. For tips on defining the right stack size, see the “Debugging in FreeRTOS” section. Refer to the figure below for an illustration of how the FreeRTOS memory works.

When the dynamic allocation is used, configTOTAL_HEAP_SIZE needs to be sufficiently large. In other words, it must be large enough to fit all the task stacks and other allocated memory. In the demo example, the heap size is set to 0x800 (2048 bytes). To optimize the heap size, xPortGetFreeHeapSize() can be used. This function returns the amount of unallocated heap. See the “Debugging in FreeRTOS” section for tips on how to find the correct heap size.

There are five different heap implementations, named heap 1-5, available in FreeRTOS. To choose which heap allocation to use, change the USE_HEAP define in the heap.c file found in the freeRTOS/portable/MemMang folder.

The Atmel | START example uses the heap 1 implementation. Heap 1 is similar to static allocation in the way that once the memory is taken, it cannot be freed or reallocated. Heap 1 is easy to debug but requires that tasks and other FreeRTOS objects such as queues, semaphores, and mutexes are kept on the heap throughout the life of the application, as creating and destroying these objects will make the application run out of memory.

The heap 2 scheme does, unlike heap 1, allow memory to be freed, but should be used with care if the memory allocated is of random size because it may cause the available free memory to become fragmented, which can result in allocation failures.

Heap 3, 4 and 5 are more advanced schemes. For more information, refer to https://www.freertos.org/a00111.html.

Figure 1. FreeRTOS Memory