The baud rate of usart set in the stm32 library is multiplication and division, and the initialization code can be used directly, but the code efficiency should be improved,
Enter the immediate Number of fractional division values to the BRR register and change the baud rate.
So I wrote the following macros. I hope they will be useful.
/* Macro of the fractional division value of the baud rate */
// CLK: usart clock, BPS: the baud rate to be set
# Define m_usart_baud_rate (_ CLK, _ bps )/
() (_ CLK/_ bps) & 0xfff0) +/
(_ CLK/1600)-(_ CLK/_ bps/16) * (_ bps/100 ))/
* 160/(_ bps/100) + 5)/10) & 0xf )))
Usage:
// The clock speed is 72 MHz and the baud rate is 57600. Modify the baud rate of usart1.
Usart1-> BRR = m_usart_baud_rate (72000000,57600); // The value is 0x4e2.
// The clock speed is 64 MHz and the baud rate is 57600. Modify the baud rate of usart1.
Usart1-> BRR = m_usart_baud_rate (64000000,57600); // The value is 0x457.
In particular, usart1 can be used to use the system frequency. When the baud rate macro is used in usart2 and usart3, the system clock should be divided into 2.
For example, if the clock speed is 72 MHz and the baud rate is 57600, modify the baud rate of usart2.
Usart2-> BRR = m_usart_baud_rate (36000000,57600 );