stm32f4/usart: fix BRR calculation logical issues

Fix two issues in the BRR calculation logic.
First the fractional part was computed using an incorrect formula, which
can produce invalid values and does not match the USARTDIV equation. This
also risks a division-by-zero in some cases. The calculation is updated to
follow the correct relation between pclk, baud, and USARTDIV.
Second the computation of the higher approximation of USARTDIV was not
consistent with the intended logic. The update ensures the next valid
step is computed properly when refining the divisor.
These changes make the baud rate calculation more accurate and reliable.
This commit is contained in:
Mohamed Ayman
2026-03-17 04:43:43 +02:00
committed by Kinsey Moore
parent 050fc00c5a
commit beea2a5683

View File

@@ -122,7 +122,7 @@ static uint32_t usart_get_bbr(
{
uint32_t a = 8 * (2 - ((usart->cr1 & STM32F4_USART_CR1_OVER8) != 0));
uint32_t div_mantissa_low = pclk / (a * baud);
uint32_t div_fraction_low = pclk / (baud - a * div_mantissa_low);
uint32_t div_fraction_low = (pclk - baud * a * div_mantissa_low) / baud;
uint32_t div_mantissa_high;
uint32_t div_fraction_high;
uint32_t high_err;
@@ -131,10 +131,10 @@ static uint32_t usart_get_bbr(
uint32_t div_fraction;
if (div_fraction_low < a - 1) {
div_mantissa_high = div_fraction_low;
div_mantissa_high = div_mantissa_low;
div_fraction_high = div_fraction_low + 1;
} else {
div_mantissa_high = div_fraction_low + 1;
div_mantissa_high = div_mantissa_low + 1;
div_fraction_high = 0;
}