STM32F0xx Baudrate Calculator

This Program calculates baudrates by reading MCU configuration. Only works with USART1 16 bit oversampling which is the reboot default and will exit if 8 bit oversampling is in use.

It uses Mecrisp-Stellaris s31.32 fixed point support to calculate the Baudrate to two decimal places so you can choose the best BRR integer to use when setting up your terminal baudrate.

f0-baudrate-calculator.fs

$40021000 constant RCC ( Reset and clock control )
RCC $4 + constant RCC_CFGR ( Clock configuration register  RCC_CFGR )
$40013800 constant USART1 ( Universal synchronous asynchronous receiver  transmitter )
USART1 $0 + constant USART1_CR1 ( Control register 1 )

8000000 constant clock  \ default, change if not.
: rcc_cfgr_pllmul? ( -- ) %1111  18  lshift $40021004 @ and 18 rshift ;  ( PLL Multiplication Factor )

: clock_multiplier? ( -- ) RCC_CFGR_PLLMUL? 2 + ;  \ clock multiplier value

: usart1_cr1_over8? ( oversampling8? -- true )  %1 15 lshift usart1_cr1 bit@ ;  \ oversampling mode. reboot default: 16

: oversampling? ( -- )
  usart1_cr1_over8?  if ." USART: 8 bit oversampling ! MUST use 16 bit oversampling" exit then
;

: >s31.32 ( u -- s31.32 ) 0 swap ;       \ convert to a s31.32 number

: brr? ( desired baud rate -- brr )      \ brr =  ((pll multiplier * clock)/desired baud)/2
  >r
  clock_multiplier?  clock *  >s31.32    \ calculate bus clock, convert to s31.32
  r@ >s31.32                             \ desired baud rate
  f/                                     \ f. divide
  2  >s31.32                             \ last step is divide by 2
  f/                                     \  f. divide
  2                                      \ only display 2 comma places
  ." for a baud rate of " r> . ." the usart1_brr should be: " f.n cr
;

: baud?  ( -- ) cr cr
  oversampling?
  ." CLOCK: " clock . ." PLL multiplier: " clock_multiplier? . ." BUS CLOCK: " clock clock_multiplier? * . ." Hz " cr
  115200 brr?
  460800 brr?
  921600 brr?
  1843200 brr?
  cr
;

Program Output

From my STM32F051 Discovery Board.

CLOCK: 8000000 PLL multiplier: 6 BUS CLOCK: 48000000 Hz
for a baud rate of 115200 the usart1_brr should be: 208,33
for a baud rate of 460800 the usart1_brr should be: 52,08
for a baud rate of 921600 the usart1_brr should be: 26,04
for a baud rate of 1843200 the usart1_brr should be: 13,02