Chinaunix首页 | 论坛 | 博客
  • 博客访问: 448590
  • 博文数量: 62
  • 博客积分: 1312
  • 博客等级: 中尉
  • 技术积分: 1555
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-24 18:10
文章分类

全部博文(62)

文章存档

2014年(1)

2013年(5)

2012年(56)

分类: C/C++

2012-10-03 18:08:01

使用串口可以提高CPU的利用率。在程序中处理流程如下:
 
一:串口初始化
1.配置串口时钟
    在void Rcc_Configuration(void)函数中实现

点击(此处)折叠或打开

  1. void Rcc_Configuration(void)
  2. {
  3.     RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO,ENABLE);
  4.     RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
  5. }
 
2.配置串口管脚
    在void UsartGPIO_Configuration(void)中实现

点击(此处)折叠或打开

  1. void UsartGPIO_Configuration(void)
  2. {
  3.     GPIO_InitTypeDef GPIO_InitStruct;

  4.     GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
  5.     GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9;
  6.     GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;

  7.     GPIO_Init(GPIOA, &GPIO_InitStruct);

  8.     GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  9.     GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10;
  10.     
  11.     GPIO_Init(GPIOA, &GPIO_InitStruct);
  12. }

 

3.初始化参数设置

点击(此处)折叠或打开

  1. USART_InitStruct.USART_BaudRate = 115200;
  2.     USART_InitStruct.USART_StopBits = USART_StopBits_1;
  3.     USART_InitStruct.USART_WordLength = USART_WordLength_8b;
  4.     USART_InitStruct.USART_Parity = USART_Parity_No;
  5.     USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  6.     USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
  7.     
  8.     USART_Init(USART1, &USART_InitStruct);

    注意:设置参数时只需要向串口初始化数据结构体中写入相应的配置参数,然后调用USART_Init函数将信息写入处理器即可。


4.串口中断配置
    调用USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);函数实现。允许串口1接收中断。

5.调用USART_Cmd(USART1, ENABLE);函数使能串口1中断。

    完整的串口初始化代码如下:

点击(此处)折叠或打开

  1. void usart_Configuration(void)
  2. {
  3.     USART_InitTypeDef USART_InitStruct;

  4.     Rcc_Configuration();

  5.     UsartGPIO_Configuration();

  6.     USART_InitStruct.USART_BaudRate = 115200;
  7.     USART_InitStruct.USART_StopBits = USART_StopBits_1;
  8.     USART_InitStruct.USART_WordLength = USART_WordLength_8b;
  9.     USART_InitStruct.USART_Parity = USART_Parity_No;
  10.     USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  11.     USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;    
  12.     USART_Init(USART1, &USART_InitStruct);

  13.     USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
  14.     USART_Cmd(USART1, ENABLE);    
  15. }


 

阅读(9342) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~