Skip to main content

Subsection 3.3.3 Step 3: Set the Baud Rate

Because UART has no shared clock line, the receiver has no way to know exactly when each bit starts. Its solution is to run its internal sampling clock at 16 times the baud rate, watch for the falling edge of the start bit, count 8 ticks to land in the middle of the start bit, then sample every 16 ticks after that, always reading each bit at its center, where the signal is most stable.
Figure 3.3.8. The receiver samples the line at 16× the baud rate (dense tick marks below the waveform). After detecting the start bit’s falling edge, it counts 8 ticks to the bit center (black arrow), then samples every 16 ticks to capture each subsequent bit at its center (red arrows).
The USART Baud Rate Register (USART_BRR) holds a simple clock divisor (USARTDIV): the hardware divides the APB clock by USARTDIV to produce exactly 16 sample ticks per bit period.
Figure 3.3.9. Baud rate generation formula from the reference manual (Section 24.5.7). With oversampling by 16 (OVER8 = 0, the default), the baud rate equals the APB kernel clock divided by USARTDIV, which is simply the integer value written to BRR.
At 9600 baud with a 12 MHz APB clock:
\begin{equation*} \text{BRR} = \frac{f_\text{APB}}{\text{baud rate}} = \frac{12{,}000{,}000}{9600} = 1250 \end{equation*}
Note that BRR must be written before setting UE in CR1.
Figure 3.3.10. USART Baud Rate Register (BRR). Bits [15:0] hold USARTDIV, the integer divisor. For 9600 baud with a 12 MHz APB clock the value is 1250 (0x04E2).
#define SYS_FREQ       12000000U   // 12 MHz HSI clock
#define APB_CLK        SYS_FREQ    // APB prescaler = 1
#define UART_BAUD_RATE 9600

USART2->BRR = APB_CLK / UART_BAUD_RATE;   // = 1250
If you look at uart.c, you will see the driver write (periphClk + baudRate/2) / baudRate instead of plain division. Adding half the divisor before dividing is the standard way to round rather than truncate: it gives \(\mathrm{round}(f/\text{baud})\) rather than \(\mathrm{floor}(f/\text{baud})\text{,}\) so the result is accurate even when the clock frequency is not evenly divisible by the baud rate. With 12 MHz and 9600 baud the division is exact, so both formulas give 1250.