串口设置流程
设置GPIO口模式为复用,并复用GPIO口为串口(AFR寄存器),顺便使能串口时钟【AFR寄存器为数组AFR[1]就是AFEH,AFR[0]就是AFEL】
RCC->AHB1ENR |= 1 << 0;
GPIOA->MODER &= ~(0x3 << (2*9)); //设置复用模式
GPIOA->MODER |= 0x2 << (2*9);
GPIOA->MODER &= ~(0x3 << (2*10)); //设置复用模式
GPIOA->MODER |= 0x2 << (2*10);
GPIOA->AFR[1] &= ~(0xf << (4*1)); //复用PA9为串口1
GPIOA->AFR[1] |= 0x7 << (4*1);
GPIOA->AFR[1] &= ~(0xf << (4*2)); //复用PA10为串口1
GPIOA->AFR[1] |= 0x7 << (4*2);
RCC->APB2ENR |= 1 << 4; //使能串口
配置CR1和CR2寄存器:
USART1->CR1 &= ~(1 << 15); //16倍过采样
USART1->CR1 |= 1<<13; //使能usart
USART1->CR1 |= 0x11<<2; //使能发送接收位
USART1->CR1 |= 1 << 3; //发送使能
USART1->CR1 |= 1 << 2; //接收使能
USART1->CR1 &= ~(1 << 12); //数据位8位
USART1->CR2 &= ~(3 << 12); //1位停止位
波特率计算公式(常用的波特率有115200,9600):
小数要存到寄存器时得先 乘以16(相当于左移4位)(小数部分必须是16分之一的倍数)
编写发送接收函数:
(DR寄存器相当于单片机的BUFF寄存器)
void Send_byte(uint8_t byte) //发送
{
while (!(USART1->SR & 1 << 7));
USART1->DR = byte;
}
void Send_str(uint8_t *str)
{
while(*str != '