UART automatic baud rate detection

Hi,

I can’t find how to set uart automatic baud rate detection in the docs.
If it isn’t supported, can you point me in the right direction in the code to implement it?
I’ve had a look and I can see it in the HAL, but I’m not sure which file in the open MV source implements the uart library.

Cheers

We use MicroPython’s drivers, you need to edit MicroPython UART driver.

Hi, you can use the stm module to access registers and memory directly in MicroPython. This will allow you to turn on this feature in the ST HAL. That said, its literally going to involve you manually accessing memory addresses and read/writing register bits.

If anyone else is interested this should work.

# Automatic baud rate detection
import stm
from pyb import UART

USART_BASE_ADDRESS = 0x40011000

USART2_ADDRESS = USART_BASE_ADDRESS  + 4

USART2_ABRMODE_SHIFT = 21
USART2_ABRMODE_STARTBIT = 0 << USART2_ABRMODE_SHIFT
USART2_ABRMODE_FALLINGEDGE = 1 << USART2_ABRMODE_SHIFT
USART2_ABRMODE_0x7F = 2 << USART2_ABRMODE_SHIFT
USART2_ABRMODE_0x55 = 3 << USART2_ABRMODE_SHIFT

USART2_ABRMODE_MASK = 3 << USART2_ABRMODE_SHIFT
USART2_ABREN = 1 << 20

USART_ISR_ADDRESS = USART_BASE_ADDRESS + 0x1C
USART_RQR_ADDRESS = USART_BASE_ADDRESS + 0x18


def initUart():
    uart = UART(1, 115200)
    # change USART2_ABRMODE_STARTBIT to whatever mode you want here
    stm.mem32[USART2_ADDRESS] = USART2_ABREN | USART2_ABRMODE_STARTBIT | (stm.mem32[USART2_ADDRESS] & ~USART2_ABRMODE_MASK)
    return uart

def isAutoBaudRateDetected():
    return stm.mem32[USART_ISR_ADDRESS] & (1<<15)

def retryAutomaticBaudRateDetection():
    stm.mem32[USART_RQR_ADDRESS] |= 1


uart = initUart()

while(True):
    try:
        if (isAutoBaudRateDetected()):
            uart.write('Hello!')
    except OSError as error:
        # should really be more specific here about which OSError it is
        # if baud rate is wrong you'll get an [Errno 110] ETIMEDOUT
        print(error)
        retryAutomaticBaudRateDetection()

Thanks for posting!