The company asked me to interface a visibility detection instrument with a product from a few years ago. The mainboard uses the STM32L051C6 microcontroller to communicate with the visibility detection instrument via RS485. In theory, this should just involve implementing a serial port data reception processing logic. However, after adding the code and compiling, it directly reported “No space in execution regions with xxx”, and reverting the code compiled normally. Upon closer inspection, I found that the previous program had completely filled the memory, as shown in the figure below:
The STM32L051C6 has 8KB of on-chip memory, and in the image above, the RW-data+ and ZI-data have completely occupied the memory. RW-data: refers to global/static variables with initial values (stored in the .data section), which need to be copied from Flash to RAM. ZI-data: refers to global/static variables with an initial value of 0 or not explicitly initialized (stored in the .bss section), which need to be zeroed by the startup code at boot time. It is miraculous that previous products ran for so long without any reported failures. The memory usage during microcontroller operation is illustrated below:
It is recommended to strictly adhere to the design rule: RW Data Size + ZI Data Size + Heap Size + Stack Size < Total Physical RAM Size. The Heap Size (Heap_Size) and Stack Size (Stack_Size) are specified in the startup script .s file (startup_stm32l051xx.s). If the program does not call malloc, you can try setting the Heap Size (Heap_Size) to 0 directly. Open the .map file, search for “Global Symbols“, and you can find your defined global or static variables (ending with (.data) or (.bss)). Look for variables that occupy a large amount of memory. For example, I found a global structure array variable in my code, with 20 members, each member being 20 bytes, which used up 400 bytes. After analyzing the business requirements, I determined that I could reduce the array members to 10, immediately saving 200 bytes of space. For more applications of .map files, you can consult the AI assistant.