今天,在调试项目的时候,遇到设置串口2波特率为19200的时候,USART_SetBaudrate(M4_USART2, 19200)函数返回 ErrorInvalidParameter,导致程序陷入了死循环,配置程序如下:
void USART2_LIN_Config(void){ #ifdef LIN_EN #ifdef HC32_MCU stc_usart_uart_init_t stcInitCfg; en_result_t enRet; stcInitCfg.enClkDiv = UsartClkDiv_1; stcInitCfg.enClkMode = UsartIntClkCkNoOutput; stcInitCfg.enDataLength = UsartDataBits8; stcInitCfg.enDirection = UsartDataLsbFirst; stcInitCfg.enStopBit = UsartOneStopBit; stcInitCfg.enParity = UsartParityNone; stcInitCfg.enSampleMode = UsartSamleBit8; stcInitCfg.enDetectMode = UsartStartBitFallEdge; stcInitCfg.enHwFlow = UsartRtsEnable; enRet = USART_UART_Init(M4_USART2, &stcInitCfg); if (enRet != Ok) { while (1); } enRet = USART_SetBaudrate(M4_USART2, 19200); if (enRet != Ok) { while (1); } USART_FuncCmd(M4_USART2, UsartRx, Enable); USART_FuncCmd(M4_USART2, UsartTx, Enable); USART_FuncCmd(M4_USART2, UsartRxInt,Enable); #endif #endif }
之后,我百思不得其解,根据函数注释来看是“ErrorInvalidParameter USARTx is invalid”,也就是串口无效,这怎么可能呢,之后我进入底层函数查看
在 static en_result_t SetUartBaudrate(M4_USART_TypeDef *USARTx, uint32_t u32Baudrate) 函数里看,
DIV = ((float)C / ((float)B * 8.0f * (2.0f - (float)OVER8))) - 1.0f; DIV_Integer = (uint32_t)(DIV); if (!((DIV < 0.0f) || (DIV_Integer > 0xFFul))) { enRet = Ok; if ((DIV - (float32_t)DIV_Integer) > 0.00001f) { /* FBME = 1 Calculation formula */ /* B = C * (128 + DIV_Fraction) / (8 * (2 - OVER8) * (DIV_Integer + 1) * 256) */ /* DIV_Fraction = ((8 * (2 - OVER8) * (DIV_Integer + 1) * 256 * B) / C) - 128 */ /* E = (C * (128 + DIV_Fraction) / (8 * (2 - OVER8) * (DIV_Integer + 1) * 256 * B)) - 1 */ /* DIV_Fraction = (((2 - OVER8) * (DIV_Integer + 1) * 2048 * B) / C) - 128 */ u64Tmp = (uint64_t)(((uint64_t)2ul - (uint64_t)OVER8) * ((uint64_t)DIV_Integer + 1ul) * (uint64_t)B); DIV_Fraction = (uint32_t)(2048ul * u64Tmp / C - 128ul); if (DIV_Fraction > 0x7Ful) { enRet = ErrorInvalidParameter; } } if (Ok == enRet) { USARTx->CR1_f.FBME = (DIV_Fraction > 0x7Ful) ? 0ul : 1ul; USARTx->BRR_f.DIV_FRACTION = DIV_Fraction; USARTx->BRR_f.DIV_INTEGER = DIV_Integer; } }
我怀疑是频率的问题,原先给串口分配的频率是42MHz,之后我改为10.5MHz,就好了
标签:USART,19200,串口,enRet,Fraction,Integer,波特率,DIV,stcInitCfg From: https://www.cnblogs.com/tlazy-12138/p/17598492.html