@@ -369,32 +369,30 @@ void serial_baud(serial_t *obj, int baudrate)
369
369
struct serial_s * obj_s = SERIAL_S (obj );
370
370
371
371
obj_s -> baudrate = baudrate ;
372
- if (init_uart (obj ) != HAL_OK ) {
373
-
374
372
#if defined(LPUART1_BASE )
375
373
/* 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 );
385
+ }
386
+ if (init_uart (obj ) == HAL_OK ) {
387
+ return ;
395
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
+ }
396
394
#endif /* LPUART1_BASE */
397
-
395
+ if ( init_uart ( obj ) != HAL_OK ) {
398
396
debug ("Cannot initialize UART with baud rate %u\n" , baudrate );
399
397
}
400
398
}
@@ -527,6 +525,18 @@ HAL_StatusTypeDef init_uart(serial_t *obj)
527
525
huart -> Init .Mode = UART_MODE_TX_RX ;
528
526
}
529
527
528
+ #if defined(LPUART1_BASE )
529
+ if (huart -> Instance == LPUART1 ) {
530
+ if (obj_s -> baudrate <= 9600 ) {
531
+ HAL_UARTEx_EnableClockStopMode (huart );
532
+ HAL_UARTEx_EnableStopMode (huart );
533
+ } else {
534
+ HAL_UARTEx_DisableClockStopMode (huart );
535
+ HAL_UARTEx_DisableStopMode (huart );
536
+ }
537
+ }
538
+ #endif
539
+
530
540
return HAL_UART_Init (huart );
531
541
}
532
542
0 commit comments