打印

STM32的串口配置

[复制链接]
945|2
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
tianli1980|  楼主 | 2014-7-8 15:30 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
STM32的串口配置(USART1为例)
今天学习串口配置,先将自己的体会整理如下!
一、首先配置串口的Tx(发送)和Rx(接受)引脚!
               GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
        GPIO_Init(GPIOA, &GPIO_InitStructure);

        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
        GPIO_Init(GPIOA, &GPIO_InitStructure);
二、开启时钟使能(包含USART1和所使用的GPIO管脚)
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);
三、配置串口的相关信息(包含波特率、数据长度、停止位、奇偶校验、硬件流控制,即USART_InitTypeDef结构体的配置)
        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_Mode = USART_Mode_Rx | USART_Mode_Tx;
        USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
        USART_Init(USART1, &USART_InitStructure);

四、使能以及读状态寄存器的值
        USART_Cmd(USART1, ENABLE);
        USART1->SR;//防止第一个字节丢失

五、添加printf的输出定向函数(刚开始我就是没有添加此函数导致printf函数不能正常工作)
       int fputc(int ch, FILE *f)
       {
               /* Place your implementation of fputc here */
               /* e.g. write a character to the USART */
               USART1->DR = (u8)ch;

               /* Loop until the end of transmission */
               while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);

               return ch;
       }

       此函数可以添加可以添加USART.C中或其他地方!
六、体会
       如果不添加int  fputc函数也可以(只要前四步做好了),可以使用USART的库函数(发送函数和接受函数)与电脑进行数据的通信!
评分
参与人数 1威望 +3 收起 理由
mmuuss586 + 3 赞一个!
沙发
mmuuss586| | 2014-7-8 16:20 | 只看该作者

讲的比较详细,赞一个

使用特权

评论回复
板凳
拿起书本| | 2014-7-8 20:31 | 只看该作者
STM32 USART1和USART3做串口使用时有什么区别呢?   

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

482

主题

2214

帖子

11

粉丝