stm32f103 串口2+dma源代码
时间: 2023-12-06 13:00:30 浏览: 78
STM32F103实验:串口收发程序源代码.rar
stm32f103的串口2可以通过DMA来实现数据传输,以下是串口2 DMA的源代码示例:
```c
#include "stm32f10x.h"
void USART2_Init(void) {
// 使能串口2时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
// 初始化串口2的GPIO
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 初始化串口2
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(USART2, &USART_InitStructure);
// 使能串口2
USART_Cmd(USART2, ENABLE);
}
void DMA_Init(void) {
// 使能DMA1时钟
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
// 初始化DMA配置
DMA_InitTypeDef DMA_InitStructure;
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&(USART2->USART_DR);
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)buffer;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
DMA_InitStructure.DMA_BufferSize = 256;
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_Normal;
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
// 初始化DMA通道
DMA_Init(DMA1_Channel7, &DMA_InitStructure);
// 使能DMA通道
DMA_Cmd(DMA1_Channel7, ENABLE);
// 使能串口2的DMA发送
USART_DMACmd(USART2, USART_DMAReq_Tx, ENABLE);
}
```
以上是一个简单的串口2 DMA使用的初始化函数,首先通过USART2_Init函数初始化了串口2,然后通过DMA_Init函数初始化了DMA配置并使能了 DMA 通道和串口2的DMA发送功能。在实际使用时,可以根据具体需求进行相应的配置和调整。
阅读全文