波特率计算方法
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/(16∗USARTDIV)
f
P
C
L
K
x
fPCLKx
fPCLKx是给串口的时钟
其中USART2,3,4,5 用PCLK1,USART1 用PCLK2
通过公式计算出值然后转换为16进制。
步骤(以USART为例,使用中断)
- 串口时钟使能, GPIO 时钟使能
注:USART_TX对应PA9,USART_RX对应PA10
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE); //使能GPIOA USART1
- 串口复位
- GPIO 端口模式设置
[表格来自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);
- 串口参数初始化
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;
- 开启中断并且初始化 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); //开启中断
- 使能串口
USART_Cmd(USART1, ENABLE); //使能串口
- 编写中断处理函数