Skip to content

Commit 01660ff

Browse files
author
Marc Emmers
committed
STM32L0/4: Always try to select LSE if LPUART and baudrate <= 9600
1 parent 964e6e7 commit 01660ff

File tree

1 file changed

+20
-22
lines changed

1 file changed

+20
-22
lines changed

targets/TARGET_STM/serial_api.c

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -369,32 +369,30 @@ void serial_baud(serial_t *obj, int baudrate)
369369
struct serial_s *obj_s = SERIAL_S(obj);
370370

371371
obj_s->baudrate = baudrate;
372-
if (init_uart(obj) != HAL_OK) {
373-
374372
#if defined(LPUART1_BASE)
375373
/* Note that LPUART clock source must be in the range [3 x baud rate, 4096 x baud rate], check Ref Manual */
376-
if (obj_s->uart == LPUART_1) {
377-
/* Try to change LPUART clock source */
378-
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
379-
if (baudrate == 9600) {
380-
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_LPUART1;
381-
PeriphClkInitStruct.Lpuart1ClockSelection = RCC_LPUART1CLKSOURCE_LSE;
382-
HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);
383-
if (init_uart(obj) == HAL_OK){
384-
return;
385-
}
386-
}
387-
else {
388-
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_LPUART1;
389-
PeriphClkInitStruct.Lpuart1ClockSelection = RCC_LPUART1CLKSOURCE_SYSCLK;
390-
HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);
391-
if (init_uart(obj) == HAL_OK){
392-
return;
393-
}
394-
}
374+
if (obj_s->uart == LPUART_1) {
375+
/* If baudrate is lower than 9600 try to change to LSE */
376+
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
377+
if (baudrate <= 9600 && __HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY)) {
378+
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_LPUART1;
379+
PeriphClkInitStruct.Lpuart1ClockSelection = RCC_LPUART1CLKSOURCE_LSE;
380+
HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);
381+
} else {
382+
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_LPUART1;
383+
PeriphClkInitStruct.Lpuart1ClockSelection = RCC_LPUART1CLKSOURCE_PCLK1;
384+
HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);
395385
}
386+
if (init_uart(obj) == HAL_OK) {
387+
return;
388+
}
389+
/* Change LPUART clock source and try again */
390+
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_LPUART1;
391+
PeriphClkInitStruct.Lpuart1ClockSelection = RCC_LPUART1CLKSOURCE_SYSCLK;
392+
HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);
393+
}
396394
#endif /* LPUART1_BASE */
397-
395+
if (init_uart(obj) != HAL_OK) {
398396
debug("Cannot initialize UART with baud rate %u\n", baudrate);
399397
}
400398
}

0 commit comments

Comments
 (0)