天天看點

STM32F103序列槽使用及配置序列槽

序列槽

初始化

時鐘

注意必須先開啟時鐘後再進行配置,否則無效

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);

         RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);

端口

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; //

    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;      //

    GPIO_Init(GPIOA, &GPIO_InitStructure);//

         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3; //

    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;

GPIO_Init(GPIOA, &GPIO_InitStructure);//

序列槽配置

    Usart2_structure.USART_BaudRate=9600;

    Usart2_structure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;

    Usart2_structure.USART_Mode=USART_Mode_Rx;

    Usart2_structure.USART_Parity=USART_Parity_No;

    Usart2_structure.USART_StopBits=USART_StopBits_1;

Usart2_structure.USART_WordLength=USART_WordLength_8b;

USART_Init(USART2,&Usart2_structure);

         Usart2_structure.USART_BaudRate=9600;

    Usart2_structure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;

    Usart2_structure.USART_Mode=USART_Mode_Tx;

    Usart2_structure.USART_Parity=USART_Parity_No;

    Usart2_structure.USART_StopBits=USART_StopBits_1;

Usart2_structure.USART_WordLength=USART_WordLength_8b;

中斷配置

注意使能中斷時不允許,用|連接配接符進行多項使能

                  NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;

                  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=1 ; //

                  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; //

                  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ

                  NVIC_Init(&NVIC_InitStructure);

               USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);

                  USART_ITConfig(USART2, USART_IT_TC, ENABLE);

使能

USART_Cmd(USART2,ENABLE);

中斷函數

void USART2_IRQHandler(void)

{

     if(USART_GetITStatus(USART2, USART_IT_TC)!=RESET)

                   {

                           ledctr=!ledctr;

                           USART_ClearITPendingBit(USART2,USART_IT_TC);

                   }

                          if(USART_GetITStatus(USART2, USART_IT_RXNE)!=RESET)

                          {

                                   ledctr=USART_ReceiveData(USART2);         

                          }

}

繼續閱讀