Simvik

Baud rate divider from the reference manual

Turn the reference manual's baud rate formula into a BRR register value, in both oversampling modes. A medium embedded C problem (Reading datasheets and…

medium · Reading datasheets and schematics · datasheets · uart · clocks · rounding

An STM32-style reference manual gives the USART baud rate as:

baud = f<sub>CK</sub> / (8 × (2 − OVER8) × USARTDIV)

USARTDIV is a fixed-point number held in the BRR register:

OVER8USARTDIV resolutionBRR[15:4]BRR[3:0]
0 (×16 oversampling)1/16mantissafraction, 4 bits
1 (×8 oversampling)1/8mantissaBRR[3] must be 0; BRR[2:0] is the fraction, 3 bits

In both modes the divider counted in fraction steps is d = fck / baud. Round it to the nearest integer, not down. A note below the table adds: "USARTDIV in fraction steps must be at least 16", and the mantissa must fit its 12 bits.

Write usart_brr(fck, baud, over8) that returns the BRR value, or 0 if the rate cannot be reached (d below 16, or a mantissa that does not fit).

Starter code

uint16_t usart_brr(uint32_t fck, uint32_t baud, int over8) {
  (void)over8;
  return (uint16_t)(fck / baud);
}

Example tests

x16 oversampling at 16 MHz

show(16000000, 115200, 0);
show(16000000, 9600, 0);

Expected output:

16 MHz, 115200 baud, x16: BRR 0x008B (115108 baud)
16 MHz, 9600 baud, x16: BRR 0x0683 (9598 baud)

x8 oversampling

show(16000000, 115200, 1);
show(84000000, 921600, 1);

Expected output:

16 MHz, 115200 baud, x8: BRR 0x0113 (115108 baud)
84 MHz, 921600 baud, x8: BRR 0x00B3 (923077 baud)

Learn it first

More Reading datasheets and schematics problems