STM32 gotchas
110. Using interrupt or DMA, only first few data are transmitted correctly (due to local/nonstatic variable used as buffer) - not ST-specific

Libraries such as Cube provide functions, which transmit an array of data (a packet) through communication interfaces such as UART, SPI, I2C etc. These functions come in various flavours, usually there are "polling"/blocking versions available, as well as non-blocking versions based on interrupts or DMA. As one of the parameters, these function take pointer to an array, which contains the data to be transmitted.

Sometimes users define the array, which holds the data (buffer), as a local variable in a function. As local non-static variables are placed at the stack, content of the buffer may get overwritten after program execution leaves the function in question and executes other functions. As data transmission using interrupts/DMA happens "at the background", while other code is executed, the data transmitted come from the already modified buffer, i.e. are different from the intended ones.

This does not happen necessarily with local buffers. For example, if execution dwells long enough in given function for all data to be transmitted; or if the function is the furthest on the execution tree (more precisely if its stack frame is the deepest in the stack usage tree), or if execution never exits from given function (as is case of main()), using local buffers is seemingly "safe". The danger then lies in potentially excessive stack use, and in potential problems if transmitting piece of code is migrated to a different function, or if the execution tree changes due to other functions being rewritten/reordered.

As occurence of symptoms depends on the code execution path, may be not apparent immediately and may "bite" surprisingly some time later, it is important that users are aware of this problem and avoid consciously it when writing the code.


Counterpart to this issue, related to Rx rather then Tx, which potentially results in program crash, is described here.