论坛元老
 
- 积分
- 3071
- 金钱
- 3071
- 注册时间
- 2018-2-7
- 在线时间
- 285 小时
|
发表于 2018-3-26 09:26:49
|
显示全部楼层
void UART2_Init(u32 bound)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
// 1、串口时钟使能 GPIO时钟使能
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
// 2、串口复位
USART_DeInit(USART2);
// 3、GPIO端口设置
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_2; //PA2 TX
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP; //复用推挽输出
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_3; //PA3 RX
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING; //浮空输入
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
// 4、串口参数初始化
USART_InitStructure.USART_BaudRate=bound;
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);
// 5、初始化NVIC
NVIC_InitStructure.NVIC_IRQChannel=USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3;
NVIC_InitStructure.NVIC_IRQChannelSubPriority=3;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);
// 6、开启中断
USART_ITConfig(USART2,USART_IT_RXNE,ENABLE);
// 7、使能串口
USART_Cmd(USART2,ENABLE);
}
void USART2_IRQHandler(void)
{
u8 res;
if(USART_GetITStatus(USART2,USART_IT_RXNE)!=RESET)
{
res=USART_ReceiveData(USART2);
USART_SendData(USART2,res); //把接收到的数据发送出去
}
}
最简单的串口2接收到的数据,在通过串口2发送出去,如果要通过串口1发就,就把中断中断发送函数串口2改成串口1就行。
|
|