stm32 hal库uart中断形式的发送函数
时间: 2023-05-25 20:03:10 浏览: 240
下面给出基于STM32 HAL库的UART中断形式的发送函数示例。
注意事项:
- 使用前请确保已经初始化了UART。
- 建议在使用前先判断一次是否可发送,避免发送堵塞。
- 本例采用了DMA方式发送,需要提前配置好DMA。
示例代码如下:
```c
void UART_DMA_Send_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
uint32_t *tmp;
uint16_t tmp1 = 0;
uint32_t tmpisr = DISABLE;
tmp = (uint32_t*)pData;
/* Disable the UART DMA Tx request */
huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT);
/* Configure the DMA Tx interrupt */
/* Configure the DMA Tx interrupt */
tmpisr = __HAL_UART_DMA_GET_IT_SOURCE(huart, UART_DMA_TX_IT);
if(tmpisr == SET)
{
__HAL_DMA_DISABLE_IT(huart->hdmatx, DMA_IT_TC | DMA_IT_HT | DMA_IT_TE);
/* Set the DMA Tx transfer complete callback */
huart->hdmatx->XferCpltCallback = NULL;
/* Set the DMA Tx transfer half complete callback */
huart->hdmatx->XferHalfCpltCallback = NULL;
/* Set the DMA error callback */
huart->hdmatx->XferErrorCallback = NULL;
/* Set the DMA abort callback */
huart->hdmatx->XferAbortCallback = NULL;
/* Clear the DMA transfer complete flag */
__HAL_DMA_CLEAR_FLAG(huart->hdmatx, __HAL_DMA_GET_TC_FLAG_INDEX(huart->hdmatx));
/* Clear the DMA transfer half complete flag */
__HAL_DMA_CLEAR_FLAG(huart->hdmatx, __HAL_DMA_GET_HT_FLAG_INDEX(huart->hdmatx));
/* Clear the DMA transfer error flag */
__HAL_DMA_CLEAR_FLAG(huart->hdmatx, __HAL_DMA_GET_TE_FLAG_INDEX(huart->hdmatx));
}
/* Enable the UART DMA Tx request */
huart->Instance->CR3 |= USART_CR3_DMAT;
/* Enable the DMA Tx Channel */
HAL_DMA_Start_IT(huart->hdmatx, (uint32_t)tmp, (uint32_t)&huart->Instance->TDR, Size);
/* Enable the DMA channel IRQ Channel */
HAL_NVIC_EnableIRQ(huart->hdmatx->IRQn);
tmp1 = huart->TxXferSize;
/* Check if a non-blocking transfer is ongoing or not */
if (huart->gState == HAL_UART_STATE_BUSY_TX)
{
return;
}
/* If it is a put buffer */
if (huart->Init.WordLength == UART_WORDLENGTH_9B)
{
while (Size--)
{
huart->pTxBuffPtr[tmp1++] = (*tmp & (uint32_t)0x01FF);
tmp++;
}
}
else
{
while (Size--)
{
huart->pTxBuffPtr[tmp1++] = (*tmp & (uint8_t)0xFF);
tmp++;
}
}
huart->TxXferSize = tmp1;
huart->TxXferCount = tmp1;
/* Process Unlocked */
__HAL_UNLOCK(huart);
/* Enable the UART Transmit data register empty interrupt */
__HAL_UART_ENABLE_IT(huart, UART_IT_TXE);
}
```
以上是基于HAL库的UART中断形式的发送函数示例,由于不同版本的HAL库实现细节有所不同,因此具体实现可能会有所差异。
阅读全文