本帖最后由 chenqiang10 于 2018-7-29 20:57 编辑
初始化串口2- void RS485_Init(void)
- {
- GPIO_InitTypeDef GPIO_InitStructure;
- USART_InitTypeDef USART_InitStructure;
- NVIC_InitTypeDef NVIC_InitStructure;
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOG,ENABLE);
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
-
- 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_SetBits(GPIOA,GPIO_Pin_2);//默认高电平
-
- GPIO_InitStructure.GPIO_Pin=GPIO_Pin_3;//PA3(RX)输入上拉
- GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;
- GPIO_Init(GPIOA,&GPIO_InitStructure);
-
- GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;//PG9(RE/DE)通用推挽输出
- GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
- GPIO_Init(GPIOG,&GPIO_InitStructure);
- GPIO_ResetBits(GPIOG,GPIO_Pin_9);//默认接收状态
-
- USART_DeInit(USART2);//复位串口2
- USART_InitStructure.USART_BaudRate=RS485_Baudrate;
- USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
- USART_InitStructure.USART_WordLength=USART_WordLength_8b;
- USART_InitStructure.USART_StopBits=USART_StopBits_1;
- USART_InitStructure.USART_Mode=USART_Mode_Rx|USART_Mode_Tx;//收发模式
- switch(RS485_Parity)
- {
- case 0:USART_InitStructure.USART_Parity=USART_Parity_No;break;//无校验
- case 1:USART_InitStructure.USART_Parity=USART_Parity_Odd;break;//奇校验
- case 2:USART_InitStructure.USART_Parity=USART_Parity_Even;break;//偶校验
- }
- USART_Init(USART2,&USART_InitStructure);
-
- USART_ClearITPendingBit(USART2,USART_IT_RXNE);
- USART_ITConfig(USART2,USART_IT_RXNE,ENABLE);//使能串口2接收中断
-
- NVIC_InitStructure.NVIC_IRQChannel=USART2_IRQn;
- NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=2;
- NVIC_InitStructure.NVIC_IRQChannelSubPriority=2;
- NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
- NVIC_Init(&NVIC_InitStructure);
-
- USART_Cmd(USART2,ENABLE);//使能串口2
- RS485_TX_EN=0;//默认为接收模式
-
- Timer7_Init();//定时器7初始化,用于监视空闲时间
- Modbus_RegMap();//Modbus寄存器映射
- }
|