搜档网
当前位置:搜档网 › STM32串口2中断接收

STM32串口2中断接收

#include "Device/Include/stm32f10x.h" // Device header
u8 usart_temp;
void GPIOInit()
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD,ENABLE);
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_3|GPIO_Pin_15|GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_4;
GPIO_InitStructure.GPIO_Mode =GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed =GPIO_Speed_50MHz;
GPIO_Init(GPIOD, &GPIO_InitStructure);

RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE,ENABLE);
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_11|GPIO_Pin_15|GPIO_Pin_14|GPIO_Pin_13|GPIO_Pin_12|GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode =GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed =GPIO_Speed_50MHz;
GPIO_Init(GPIOE, &GPIO_InitStructure);
}
void USART2_Configuration(void)
{
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);

GPIO_PinRemapConfig(GPIO_Remap_USART2, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOD, &GPIO_InitStructure);

USART_https://www.sodocs.net/doc/e410391119.html,ART_BaudRate = 9600;
USART_https://www.sodocs.net/doc/e410391119.html,ART_WordLength = USART_WordLength_8b;
USART_https://www.sodocs.net/doc/e410391119.html,ART_StopBits = USART_StopBits_1;
USART_https://www.sodocs.net/doc/e410391119.html,ART_Parity = USART_Parity_No;
USART_https://www.sodocs.net/doc/e410391119.html,ART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_https://www.sodocs.net/doc/e410391119.html,ART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART2, &USART_InitStructure);

USART_Cmd(USART2, ENABLE);
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
USART_Cmd(USART2, ENABLE);
}
void delay_ms(u16 time)
{
u16 i=0;
while(time--)
{
i=12000;
while(i--);
}
}
void NVIC_Config(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);

}
void USART2_IRQHandler(void)
{
int RX_status;
RX_status = USART_GetFlagStatus(USART2, USART_FLAG_RXNE);
if(RX_status == SET)
{
usart_temp=USART_ReceiveData(USART2);
USART_SendData(USART2 , usart_temp);
while(USART_GetFlagStatus(USART2, USART_FLAG_TC)==RESET);
}
}


int main()
{
delay_ms(1000);
GPIOInit();
USART2_Configuration();
NVIC_Config();
usart_temp=0;
while(1)
{
if(usart_temp>100)
{
delay_ms(1000) ;
GPIO_SetBits(GPIOD,GPIO_Pin_3);
}
else
{
delay_ms(1000) ;
GPIO_ResetBits(GPIOD,GPIO_Pin_3);
}
}
}

相关主题