找回密码
 注册
搜索
查看: 1705|回复: 2

[讨论] STM32的串口配置

[复制链接]
发表于 2013-7-11 15:41:11 | 显示全部楼层 |阅读模式
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的库函数(发送函数和接受函数)与电脑进行数据的通信!
发表于 2013-12-21 12:50:39 | 显示全部楼层

实在是太棒了!
点评回复

使用道具 举报

发表于 2014-8-31 10:05:50 | 显示全部楼层
这种帖子换个地方
点评回复

使用道具 举报

高级模式
B Color Image Link Quote Code Smilies

本版积分规则

Archiver|手机版|小黑屋|52RD我爱研发网 ( 沪ICP备2022007804号-2 )

GMT+8, 2024-5-3 20:05 , Processed in 0.062444 second(s), 17 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表