请帮我写一段STM32F405RGT6单片机的串口5通信程序,要求开启串口接收中断,使能DMA传输
时间: 2023-05-17 11:03:30 浏览: 128
GD32F405RGT6串口接收发送DMA
5星 · 资源好评率100%
以下是一段基本的 STM32F405RGT6 单片机的串口5通信程序,已经开启了串口接收中断和 DMA 传输:
#include "stm32f4xx.h"
void USART5_IRQHandler(void)
{
if (USART_GetITStatus(USART5, USART_IT_RXNE) != RESET)
{
// 处理接收到的数据
uint8_t data = USART_ReceiveData(USART5);
// ...
}
}
void init_usart5(void)
{
// 使能 USART5 时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART5, ENABLE);
// 使能 DMA2 时钟
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2, ENABLE);
// 初始化 USART5
USART_InitTypeDef USART_InitStructure;
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_Mode_Tx;
USART_Init(USART5, &USART_InitStructure);
// 使能 USART5
USART_Cmd(USART5, ENABLE);
// 初始化 DMA2
DMA_InitTypeDef DMA_InitStructure;
DMA_InitStructure.DMA_Channel = DMA_Channel_4;
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&(USART5->DR);
DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)buffer;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory;
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_FIFOMode = DMA_FIFOMode_Disable;
DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_HalfFull;
DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
DMA_Init(DMA2_Stream0, &DMA_InitStructure);
// 使能 DMA2
DMA_Cmd(DMA2_Stream0, ENABLE);
// 使能 USART5 接收中断
USART_ITConfig(USART5, USART_IT_RXNE, ENABLE);
// 使能 DMA2 的 USART5 RX DMA 请求
USART_DMACmd(USART5, USART_DMAReq_Rx, ENABLE);
// 使能 USART5 的 DMA 接收
USART_DMACmd(USART5, USART_DMAReq_Rx, ENABLE);
}
int main(void)
{
// 初始化 USART5
init_usart5();
while (1)
{
// 主循环
}
}
阅读全文