Strange STM32 USART behaviour?

Is my code faulty? Does the STM32F103RET6 have an unknown bug? Could it be a problem with ARM GCC compiler? Who knows?

During the past couple of evenings I’ve been trying to figure out what’s going wrong with it’s USARTs. What happens is when sending multiple characters only the last character is received (characters send right before never leave the controller). The reference manual states this on page 741:

7. Write the data to send in the USART_DR register (this clears the TXE bit). Repeat this for each data to be transmitted in case of single buffer.

and:

The TXE bit is always cleared by a write to the data register.

and on page 742:

When no transmission is taking place, a write instruction to the USART_DR register places the data directly in the shift register, the data transmission starts, and the TXE bit is immediately set.

It even comes with the following figure:

However what happens in reality is that there’s a delay between writing to the USART_DR register and the moment TXE is set. This messes things up.

Take the following code to send a string:

  while(*pSrc)
  {
    USART_SendData(USART3, *pSrc++);
    while(USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET);
  }

This is also what the STM32F10x Standard Peripherals Firmware Library USART examples do. However this does not work. The while loop is never entered (try turning on a LED, it stays turned off). Now instead of assuming the TXE bit is cleared by the write, wait for the bit to be set:

  while(*pSrc)
  {
    USART_SendData(USART3, *pSrc++);
    while(1) {
      if (USART_GetFlagStatus(USART3, USART_FLAG_TXE) == SET) {
        break;
      }
    }
  }

This does work (although I can’t recommend it) and a string is transmitted as it should be. So far I’m stumped as to what’s actually going on. Also played around with compiler settings (with/without optimisation), but no effect.┬áIt just doesn’t make sense.

Asking around on ST’s e2e community forums has so far resulted in hints and tips, but no solution. Well actually it has left me with the feeling I’d rather chew off an arm than to visit that forum again. The people are great, but the Sharepoint forum software ST uses is a total disaster! And it’s down… again… *sigh*

Anyhow, the investigation continues…

Comments are closed.