How does the UART baud rate generator work, and how do you calculate the divisor from the peripheral clock?
The baud rate generator divides the peripheral clock (PCLK) by a programmable divisor to produce the bit-rate clock. The basic formula is:
Divisor = PCLK / (Oversampling x BaudRate)
Most UART peripherals oversample each bit 16 times (some support 8x oversampling for higher baud rates at the cost of noise margin). For STM32 at 16x oversampling:
USARTDIV = PCLK / BaudRateBRR register = USARTDIV (integer + fractional parts)
For example, with PCLK = 72 MHz and a target of 115200 baud: USARTDIV = 72000000 / 115200 = 625.0 — an exact integer, so the baud rate error is 0%. But with PCLK = 48 MHz: USARTDIV = 48000000 / 115200 = 416.67, which rounds to 417, producing an actual baud rate of 48000000 / 417 = 115107.9, an error of 0.08% — well within tolerance.
The critical point: always verify the actual baud rate error after choosing a system clock. Some clock/baud-rate combinations produce errors above 2%, which causes communication failures. This is a common embedded systems interview question because it tests whether you understand that UART timing is derived from the system clock and is not perfectly arbitrary.
Source: UART Q&A
