stm32f10串口dma接收数据代码
时间: 2023-05-20 12:02:30 浏览: 136
stm32用dma实现串口接收
以下是一个基本的 STM32F10 串口 DMA 接收数据的代码示例:
```c
#include "stm32f10x.h"
#define BUFFER_SIZE 256
uint8_t buffer[BUFFER_SIZE];
uint16_t buffer_index = 0;
void DMA1_Channel5_IRQHandler(void)
{
if (DMA_GetITStatus(DMA1_IT_TC5))
{
DMA_ClearITPendingBit(DMA1_IT_TC5);
buffer_index = BUFFER_SIZE - DMA_GetCurrDataCounter(DMA1_Channel5);
}
}
void USART1_IRQHandler(void)
{
if (USART_GetITStatus(USART1, USART_IT_RXNE))
{
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
if (buffer_index < BUFFER_SIZE)
{
buffer[buffer_index++] = USART_ReceiveData(USART1);
}
}
}
int main(void)
{
// 初始化串口和 DMA
USART_InitTypeDef USART_InitStructure;
DMA_InitTypeDef DMA_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&USART1->DR;
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)buffer;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
DMA_InitStructure.DMA_BufferSize = 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_Channel5, &DMA_InitStructure);
DMA_ITConfig(DMA1_Channel5, DMA_IT_TC, ENABLE);
DMA_Cmd(DMA1_Channel5, ENABLE);
// 启用中断
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = DMA1_Channel5_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_Init(&NVIC_InitStructure);
// 主循环
while (1)
{
// 处理接收到的数据
if (buffer_index > 0)
{
// 处理 buffer 中的数据
// ...
// 重置 buffer_index
buffer_index = 0;
}
}
}
```
这个代码示例使用了 STM32F10 的 USART1 和 DMA1,通过 DMA1_Channel5 接收 USART1 的数据,并将数据存储在 buffer 数组中。当 DMA1_Channel5 接收到足够的数据后,会触发 DMA1_Channel5_IRQHandler 中断,此时可以通过 DMA_GetCurrDataCounter 函数获取已经接收到的数据量,从而确定 buffer 中存储的数据量。USART1_IRQHandler 中断用于将接收到的数据存储在 buffer 数组中。在主循环中,可以处理 buffer 中的数据。
阅读全文