DEV Community

zhuyue
zhuyue

Posted on

Why I don't dynamically allocate RAM memory for ESP8266 based simple programmable controller

Using ESP8266 to design the controller for script programming, I think the RAM space of ESP8266 is only 96kB, if the program occupies the memory through dynamic memory allocation, it will affect the execution efficiency and reliability of the program.

The controller has many functions and complex code, it is difficult to control the allocation and release of memory, also difficult to ensure that there will not be a failure to allocate memory, at this time, the exception handling and waiting for the memory free will become complex, and will inevitably affect the efficiency of the program execution, finally affects the efficiency of the controller, timing and logic.

Therefore, when I designed the code, I allocated a fixed amount of memory to several important functional modules, including the cache for sending and receiving data from the TCP server and client, the cache for parsing the HTTP protocol, and the write cache for rewriting the script program in flash.

This allocation, 96kByte is stretched to the limit, after the development of all the functions, only about 7kByte heap size left.

In many places, time must be sacrificed for RAM space.
For example, when designing the remote firmware upgrade function, encountered the problem of reading and writing flash memory requires 4-byte alignment, not only read and write the address and length of the data need to be 4-byte alignment, and memory constraints can't be fixed by just allocating enough memory to move the data to achieve 4-byte memory, can only be directly in the upper level of the data passed down to the data memory operation, and the data memory address is not 4-byte aligned, passed directly to the function spi_flash_read/spi_flash_write operation, then it will throw the data alignment exception with error code 9 and reboot.

In the end, I can only add additional codes to achieve 4-byte alignment of the address and data length, and read and write by a word (4 bytes) as a unit one by one, and read and write from the upper level in units of bytes.

Actual test, it does affect the read and write speed of flash, resulting in a longer time to upgrade the firmware.

However, the upgrade is an infrequently used function, a little longer time is acceptable, stability is still the most important.

Image description

Top comments (0)