1. 串口配置
void USART3_Configuration(uint32_t Baudrate)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_11;
GPIO_Init(GPIOB,&GPIO_InitStructure);
USART_InitStructure.USART_BaudRate=Baudrate;
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(USART3,&USART_InitStructure);
USART_ITConfig(USART3, USART_IT_IDLE,ENABLE);
USART_Cmd(USART3,ENABLE);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
2.DMA配置
void DMA_USART3Rx_Init(void)
{
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
DMA_DeInit(DMA1_Channel3);
DMA_InitStructure.DMA_PeripheralBaseAddr=(u32)&USART3->DR;
DMA_InitStructure.DMA_MemoryBaseAddr=(u32)USART3_DMA_Rxbuf;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
DMA_InitStructure.DMA_BufferSize=DMA1_MEM_LEN;
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_VeryHigh;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA1_Channel3,&DMA_InitStructure);
DMA_Cmd(DMA1_Channel3,ENABLE);
USART_DMACmd(USART3,USART_DMAReq_Rx,ENABLE);
}
3.串口中断处理
void USART3_IRQHandler(void)
{
int temp = 0;
unsigned int i=0;
if(USART_GetITStatus(USART3,USART_IT_IDLE)!=RESET)
{
temp = USART3->SR;
temp = USART3->DR;
DMA_Cmd(DMA1_Channel3,DISABLE);
temp=DMA_GetCurrDataCounter(DMA1_Channel3);
Rx_Len=USART_BUF_MAX-DMA_GetCurrDataCounter(DMA1_Channel3);
if(Rx_Len>=USART_BUF_MAX)
{
}
else
{
if(USART_data_flag==0)
{
for(i=0;i<Rx_Len;i++)
DMA_Rxbuf[i]=USART3_DMA_Rxbuf[i];
DMA_Rxbuf[i]='\0';
}
USART_EOF=1;
}
DMA_SetCurrDataCounter(DMA1_Channel3,USART_BUF_MAX);
DMA_Cmd(DMA1_Channel3,ENABLE);
temp=temp;
}
}
备注:在此串口接收函数中 如果接收的数据大于接收buffer 则会出错 需要防止这种错误