STM32寄存器配置串口USART1及USART->BRR值的计算
main.c
#include "stm32f10x.h"
#include "SYSCLK.h"
#include "USART.h"
int main()
{
CLK_Init();
Serial_Init();
Serial_SendByte(0xaa);
while (1)
{
}
}
Serial.c
#include "stm32f10x.h"
void Serial_Init()
{
RCC->APB2ENR|=0x00004005;
GPIOA->CRH|=0x000000b0;
USART1->CR2&=0xcfff;
USART1->CR1&=0xe9f3;
USART1->CR1|=0x0008;
USART1->CR3&=0xfcff;
USART1->CR3|=0x0000;
USART1->BRR=0x00001d4c;
USART1->CR1|=0x2000;
}
void Serial_SendByte(unsigned int Byte)
{
while((USART1->SR&0x80)==0x00);
USART1->DR=Byte&0x01ff;
}
SYSCLK.c
#include "stm32f10x.h"
void CLK_Init()
{
RCC->CR |= RCC_CR_HSEON;
while ((RCC->CR & RCC_CR_HSERDY) == 0)
{
}
RCC->CFGR |= RCC_CFGR_PLLMULL9;
RCC->CFGR |= RCC_CFGR_PLLSRC;
FLASH->ACR |= FLASH_ACR_LATENCY_2;
RCC->CR |= RCC_CR_PLLON;
while ((RCC->CR & RCC_CR_PLLRDY) == 0)
{
}
RCC->CFGR |= RCC_CFGR_HPRE_DIV1;
RCC->CFGR |= RCC_CFGR_PPRE2_DIV1;
RCC->CFGR |= RCC_CFGR_PPRE1_DIV2;
RCC->CFGR &= (~(RCC_CFGR_SW));
RCC->CFGR |= RCC_CFGR_SW_PLL;
while ((RCC->CFGR & RCC_CFGR_SWS) != 0x08)
{
}
}
USART->BRR寄存器计算
BRR寄存器:

BRR计算
- fck是时钟频率,这里我们假设72000000Hz,如果需要设置的波特率为115200,那我们可以计算出USARTDIV = 39.0625
- 位4到位15表示整数部分也就是39(十进制)---->0x27
- 位0到位3表示小数部分也就是 0.0625 *16 ---->0x01
- 即 USART->BRR = 0x0271
- 同理,如果配置波特率为9600,fck =72MHz, USART->BRR = 0x1d4c