stm32f103vet6用HAL库写串口通信中断接受DMA发送程序
时间: 2023-11-01 10:06:46 浏览: 122
以下是基于HAL库的stm32f103vet6串口通信中断接收DMA发送程序:
1. 首先定义串口和DMA的相关变量和配置:
```
UART_HandleTypeDef huart1;
DMA_HandleTypeDef hdma_usart1_tx;
uint8_t uart_buffer[100];
uint8_t dma_buffer[100];
void MX_USART1_UART_Init(void)
{
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
}
void MX_DMA_Init(void)
{
__HAL_RCC_DMA1_CLK_ENABLE();
hdma_usart1_tx.Instance = DMA1_Channel4;
hdma_usart1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_usart1_tx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_usart1_tx.Init.MemInc = DMA_MINC_ENABLE;
hdma_usart1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_usart1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_usart1_tx.Init.Mode = DMA_NORMAL;
hdma_usart1_tx.Init.Priority = DMA_PRIORITY_LOW;
if (HAL_DMA_Init(&hdma_usart1_tx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(&huart1, hdmatx, hdma_usart1_tx);
}
```
2. 接着编写串口接收中断处理函数:
```
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if (huart == &huart1)
{
HAL_UART_Receive_IT(&huart1, uart_buffer, 100); //重新开启接收中断
}
}
```
3. 在main函数中初始化串口和DMA,并开启串口接收中断:
```
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART1_UART_Init();
MX_DMA_Init();
HAL_UART_Receive_IT(&huart1, uart_buffer, 100); //开启串口接收中断
while (1)
{
if (strlen((char *)uart_buffer) > 0) //判断串口接收缓存是否有数据
{
memcpy(dma_buffer, uart_buffer, strlen((char *)uart_buffer)); //将串口接收缓存内容拷贝至DMA发送缓存
HAL_UART_Transmit_DMA(&huart1, dma_buffer, strlen((char *)dma_buffer)); //开启DMA发送
memset(uart_buffer, 0, sizeof(uart_buffer)); //清空串口接收缓存
}
}
}
```
4. 最后编写DMA发送完成中断处理函数:
```
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
if (huart == &huart1)
{
memset(dma_buffer, 0, sizeof(dma_buffer)); //清空DMA发送缓存
}
}
```
以上是基于HAL库的stm32f103vet6串口通信中断接收DMA发送程序的基本框架,具体实现根据实际需求进行修改。
阅读全文