stm32dma串口接收数据代码
时间: 2023-08-28 11:06:01 浏览: 128
以下是基于STM32的DMA串口接收数据的示例代码:
```
// 定义一些变量
#define UART_RX_BUF_SIZE 256
uint8_t uart_rx_buf[UART_RX_BUF_SIZE];
volatile uint16_t uart_rx_len = 0;
// 初始化USART和DMA
void uart_init(void) {
// 使能USART时钟和GPIO时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
// 配置USART引脚
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置USART
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 9600;
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_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
// 配置DMA
DMA_InitTypeDef DMA_InitStructure;
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&USART1->RDR;
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)uart_rx_buf;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
DMA_InitStructure.DMA_BufferSize = UART_RX_BUF_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
DMA_Cmd(DMA1_Channel5, ENABLE);
// 使能USART
USART_Cmd(USART1, ENABLE);
// 使能USART接收中断
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
}
// USART中断服务函数
void USART1_IRQHandler(void) {
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) {
// 清除中断标志
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
// 读取数据
uint8_t data = USART_ReceiveData(USART1);
// 将数据写入缓冲区
if (uart_rx_len < UART_RX_BUF_SIZE) {
uart_rx_buf[uart_rx_len++] = data;
}
}
}
// 获取接收到的数据长度
uint16_t uart_get_rx_len(void) {
return uart_rx_len;
}
// 获取接收到的数据
uint8_t* uart_get_rx_buf(void) {
return uart_rx_buf;
}
// 重置接收缓冲区
void uart_reset_rx_buf(void) {
uart_rx_len = 0;
}
```
在上面的代码中,我们使用了DMA来实现串口数据的接收。首先,我们配置了USART和DMA的参数,然后使能了USART和DMA,最后开启了USART接收中断。在接收中断服务函数中,我们读取数据并将其写入缓冲区。在使用接收缓冲区的时候,我们可以通过`uart_get_rx_len()`函数获取接收到的数据长度,通过`uart_get_rx_buf()`函数获取接收到的数据,通过`uart_reset_rx_buf()`函数重置接收缓冲区。
阅读全文