STM32用DMA接收 串口二的信息实现代码库函数实现方式
时间: 2024-04-29 13:21:52 浏览: 56
STM32 串口 DMA 接收任意长度数据
以下是使用DMA接收串口二数据的代码库函数实现方式:
1. 配置串口二接收DMA通道
```c
void USART2_DMA_Init(void)
{
DMA_InitTypeDef DMA_InitStructure;
/* 开启DMA时钟 */
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
/* 复位DMA1通道6 */
DMA_DeInit(DMA1_Channel6);
/* 配置DMA1通道6 */
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&USART2->DR;
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)USART2_RxBuffer;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
DMA_InitStructure.DMA_BufferSize = USART2_RX_BUFFER_SIZE;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA1_Channel6, &DMA_InitStructure);
/* 开启DMA1通道6 */
DMA_Cmd(DMA1_Channel6, ENABLE);
}
```
2. 配置串口二接收中断
```c
void USART2_IRQ_Init(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
/* 使能串口二接收中断 */
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
/* 配置串口二接收中断优先级 */
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
```
3. 在USART2_IRQHandler中处理中断
```c
void USART2_IRQHandler(void)
{
if (USART_GetITStatus(USART2, USART_IT_RXNE) != RESET)
{
/* 清除中断标志位 */
USART_ClearITPendingBit(USART2, USART_IT_RXNE);
/* 处理接收到的数据 */
USART2_RxBuffer[USART2_RxCounter++] = USART_ReceiveData(USART2);
/* 判断是否超出接收缓冲区大小,超出则重新开始接收 */
if (USART2_RxCounter == USART2_RX_BUFFER_SIZE)
{
USART2_RxCounter = 0;
}
}
}
```
4. 在Main函数中初始化串口二、DMA和中断
```c
int main(void)
{
/* 初始化串口二 */
USART2_Init();
/* 初始化DMA */
USART2_DMA_Init();
/* 初始化中断 */
USART2_IRQ_Init();
while (1)
{
/* do something */
}
}
```
以上代码实现了使用DMA接收串口二数据,并通过中断处理函数将数据存储到缓冲区中。在主程序中可以根据需要读取缓冲区中的数据。
阅读全文