STM32 串口通信USART(学习笔记)

波特率计算方法

T x / R x = f P C L K x / ( 16 ∗ U S A R T D I V ) Tx/Rx =fPCLKx/(16*USARTDIV) Tx/Rx=fPCLKx/(16USARTDIV)
f P C L K x fPCLKx fPCLKx是给串口的时钟
其中USART2,3,4,5 用PCLK1,USART1 用PCLK2
通过公式计算出值然后转换为16进制。

步骤(以USART为例,使用中断)

  1. 串口时钟使能, GPIO 时钟使能
    注:USART_TX对应PA9,USART_RX对应PA10
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE);	//使能GPIOA USART1
  1. 串口复位
  2. GPIO 端口模式设置
    表格来自STM32中文参考手册
    [表格来自STM32中文参考手册]

①USART_TX(PA9)

	GPIO_InitTypeDef GPIO_InitStruct1;
	GPIO_InitStruct1.GPIO_Mode=GPIO_Mode_AF_PP;//推挽复用输出
	GPIO_InitStruct1.GPIO_Pin=GPIO_Pin_9;
	GPIO_InitStruct1.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStruct1);

②USART_RX(PA10)

    GPIO_InitTypeDef GPIO_InitStruct1;
    GPIO_InitStruct1.GPIO_Mode=GPIO_Mode_IN_FLOATING;//浮空输入
	GPIO_InitStruct1.GPIO_Pin=GPIO_Pin_10;
	GPIO_Init(GPIOA,&GPIO_InitStruct1);
  1. 串口参数初始化
typedef struct
{

  uint16_t USART_Clock;   /*!< Specifies whether the USART clock is enabled or disabled.
                               This parameter can be a value of @ref USART_Clock */

  uint16_t USART_CPOL;    /*!< Specifies the steady state value of the serial clock.
                               This parameter can be a value of @ref USART_Clock_Polarity */

  uint16_t USART_CPHA;    /*!< Specifies the clock transition on which the bit capture is made.
                               This parameter can be a value of @ref USART_Clock_Phase */

  uint16_t USART_LastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted
                               data bit (MSB) has to be output on the SCLK pin in synchronous mode.
                               This parameter can be a value of @ref USART_Last_Bit */
} USART_ClockInitTypeDef;

  1. 开启中断并且初始化 NVIC(如果需要开启中断才需要这个步骤)
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ; //抢占优先级 3
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //子优先级 3
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ 通道使能
NVIC_Init(&NVIC_InitStructure); //中断优先级初始
//⑤开启中断
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); //开启中断
  1. 使能串口
USART_Cmd(USART1, ENABLE); //使能串口
  1. 编写中断处理函数
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值