Search code examples
embeddedstm32cortex-m

STM32F103 hangs on page update with USART enabled


I am currently working on a STM32F103, and I want to program the flash. However, it appear that programming the flash with an USART device receiving bytes in the same time make it hangs:

FLASH_BASE->CR |= FLASH_CR_PER;
while (FLASH_BASE->SR & FLASH_SR_BSY);

FLASH_BASE->AR = pageAddr;
FLASH_BASE->CR |= FLASH_CR_STRT; // Hangs forever when receiving
                                 // data on USART2 in the same time
while (FLASH_BASE->SR & FLASH_SR_BSY);
FLASH_BASE->CR &= ~FLASH_CR_PER;

Disabling the RE flag on USART2 before and re-enabling it after avoids the problem, but it prevent me from receiving data during the operation, which would be possible since the receive interrupt is in the RAM.

Actually, looks like it is not related to the interrupt itself, because it still hangs without the receive interrupt.

Any idea?


Solution

  • The STM32 Flash memory interface locks its entire data bus during erase and write operations, such that any read operation is stalled during the access A Page erase can take up to 40ms on an STM32F1xx (it is a massive 800ms on an STM32F2xx!). Because the code is also running from the flash memory, instruction fetches and therefore code execution stall during that time, delaying interrupt handling and causing a USART overrun error.

    One somewhat complex way around this is to use DMA for the USART receiver, but that is not always possible or straightforward and may not solve other problems caused by the processor stall in real-time systems.

    This little surprise nugget is hidden in the Flash Programming Manual, separate from the Reference Manual:

    During a write operation to the Flash memory, any attempt to read the Flash memory will stall the bus. The read operation will proceed correctly once the write operation has completed. This means that code or data fetches cannot be made while a write/erase operation is ongoing.

    While the actual timing information is in the datasheet: STM32F103 Flash Timing

    They seem to have spread the information around separate documents to elicit maximum surprise at this gotcha!