一、初始化
1.初始化串口,時鍾
MX_USART1_UART_Init();
串口時鍾初始化為內部時鍾
PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_HSI;
PeriphClkInit.Usart2ClockSelection = RCC_USART2CLKSOURCE_HSI;
2.初始化dma,端口復用
HAL_UART_MspInit()
打開空閑幀中斷
__HAL_UART_ENABLE_IT(uartHandle, UART_IT_IDLE);
二、啟動接收傳送
1.啟動數據接收
/*啟動DMA接收傳送*/ void Mx_Uart_DebugRxStart(UART_E uart) { if(uart>= UART_MAX){return ;} if(!g_stMyUart[uart].bDebugRxStop){return ;} for(uint8 i=0;i<UART_DEBUG_BUFF_LEVER;i++) { if(!g_stMyUart[uart].bDebugRxAvail[i]) { g_stMyUart[uart].bDebugRxStop=false; HAL_UART_Receive_DMA(g_stMyUart[uart].huart ,g_stMyUart[uart].cDebugBuffRx[i] ,UART_RX_BUFF_SIZE-1); g_stMyUart[uart].cCurDebugRxBuff=i; g_stMyUart[uart].uDebugRxCount[i]=0; break; } } }
2.如果接收完數據則觸發DMA中斷,觸 發DMa中斷后,調用傳送完成中斷,如果收到空閑幀,也會調用傳送完成中斷
uint32_t temp; temp = huart->Instance->ISR; temp = huart->Instance->RDR; if(HAL_OK !=HAL_UART_DMAStopRx(huart)) { Error_Handler(); } g_stMyUart[uart].bDebugRxStop=true; if(NULL != huart->hdmarx) { temp = huart->hdmarx->Instance->CNDTR; MX_UART_DebugGetData(uart,temp); Mx_Uart_DebugRxStart(uart); } else{Error_Handler();}
停止DMA傳送,置接收停止標志,讀取數據,重新開始數據接收
三、發送DMA
1.啟動傳送
if(HAL_UART_Transmit_DMA(g_stMyUart[UART_DEBUG].huart , g_stMyUart[UART_DEBUG].cDebugBuffTx[i] , g_stMyUart[UART_DEBUG].uDebugTxCount[i]) == HAL_OK) { g_stMyUart[UART_DEBUG].cCurDebugTxBuff=i; g_stMyUart[UART_DEBUG].uDebugTxCount[i]=0; }
2.DMA傳送完成時,打開串口發送完成中斷,
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) { UART_E uart; for(uart=UART_DEBUG;uart<UART_MAX;uart++) { if(g_stMyUart[uart].huart == huart){break;} } if(UART_MAX == uart){return ;} HAL_UART_DMAStopTx(huart); if(g_stMyUart[uart].cCurDebugTxBuff <UART_DEBUG_BUFF_LEVER) { g_stMyUart[uart].bDebugTxEn[g_stMyUart[uart].cCurDebugTxBuff]=false; } }