博客首页 | 排行榜 |

xuqj4490的博客

个人档案
博文分类
STM32-USART查询方式  2010-08-10 22:27

USART一般有查询和中断两种方式,在此介绍查询方式。

步骤一:初始化GPIO
GPIO_InitTypeDef GPIO_InitStructure;
/* Configure USART1 Tx (PA.09) as alternate function push-pull */
 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
 GPIO_Init(GPIOA, &GPIO_InitStructure);
 
 /* Configure USART1 Rx (PA.10) as input floating */
 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
 GPIO_Init(GPIOA, &GPIO_InitStructure);
 
/* Configure LED1 (PD.8) as output floating */
 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOD, &GPIO_InitStructure);
 
步骤二:开时钟
/* Enable USART1, GPIOA, GPIOD and AFIO clocks */
 RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOD
                         | RCC_APB2Periph_AFIO, ENABLE);
 
在此说明,不用设置RCC_APB2Periph_AFIO也是可以的,也就是在此没有使用复用功能。
 
步骤三:初始化USART1
USART_InitStructure.USART_BaudRate = 9600;
 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;
 /* Configure USART1 */
 USART_Init(USART1, &USART_InitStructure);
 /* Enable USART1 Receive and Transmit interrupts */
 /* Enable the USART1 */
 USART_Cmd(USART1, ENABLE);
步骤四:实现串口通信
for( i=0;TxBuffer1[i]!='\0';i++)
 {
      USART_SendData(USART1, TxBuffer1[i]);
    while(USART_GetFlagStatus(USART1, USART_FLAG_TC)==RESET);
 }
向上位机传送一串字符
 while (1)
 {
           GPIO_ResetBits(GPIOD, GPIO_Pin_8);
         RX_status = USART_GetFlagStatus(USART1, USART_FLAG_RXNE);
         if(RX_status == SET)
           {
             USART_SendData(USART1 , USART_ReceiveData(USART1));
             while(USART_GetFlagStatus(USART1,USART_FLAG_TC)==RESET);
             GPIO_SetBits(GPIOD, GPIO_Pin_8);
            // Delay(0xFFF);
          }
 }
循环接收到上位机发过来的字符,然后再回传给上位机。
这里要说明些,如果在while (1)加入Delay(0xFFFFF),接收一串字符后每次只能回发2个字符,如果参数给为Delay(0xFFF), 接收一串字符后每次只能回发4个字符,如果去掉这句,就可以正常了。
类别:STM32 |
上一篇:STM32 -USART中断方式 | 下一篇:在MDK下创建工程
以下网友评论只代表其个人观点,不代表本网站的观点或立场