uart4.c
#include "uart4.h"
//UART4_RX ====> PB2
//UART4_TX ====> PG11
//rcc/gpio/uart4初始化
void hal_uart4_init()
{
//=========PCC章节初始化========
//使能GPTOG组控制器 MP_AHB4ENSETR[1] = 1
RCC->MP_AHB4ENSETR |= (0x1 << 1);
//使能GPTOG组控制器 MP_AHB4ENSETR[6] = 1
RCC->MP_AHB4ENSETR |= (0X1 << 6);
//使能GPTOG组控制器 MP_APB1ENSETR[16] = 1
RCC->MP_APB1ENSETR |= (0X1 << 16);
//设置PB2复用功能为UART_RX
//设置PG11
GPIOG->MODER &= (~(0X3 << 22));
GPIOG->MODER |= (0x2 << 22);
GPIOG->AFRH &= (~(0xF << 12));
GPIOG->AFRH |= (0x6 << 12);
//设置PB2
GPIOG->MODER &= (~(0x3 << 4));
GPIOG->MODER |= (0x2 << 4);
GPIOG->AFRH &= (~(0xF << 8));
GPIOG->AFRH |= (0x8 << 8);
//禁用串口
USART4->CR1 &= (~0x1);
//设置数据位为8位
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 28));
//设置无奇偶数校位
USART4->CR1 &= (~(0X1 << 10));
//设置16倍过采样
USART4->CR1 &= (~(0x1 << 15));
//设置1位停止位
USART4->CR2 &= (~(0x3 << 12));
//设置不分频
USART4->PRESC &= (~0xF);
//设置波特率为115200
USART4->BRR=0x22B;
//使能发送器
USART4->CR1 |= (0x1 << 3);
//使能接收器
USART4->CR1 |= (0x1 << 2);
//使能串口
USART4->CR1 |= (0x1);
}
//发送一个字符
void hal_put_char(const char str)
{
//先判断发送器是否为空,不为空等待
while(!(USART4->ISR &(0x1 << 7)));
//向发送寄存器写入数据
USART4->TDR=str;
//等待发送完成
while(!(USART4->ISR &(0x1 << 6)));
}
//接收一个字符
char hal_get_cahr()
{
char a;
//判断接收器是否准备好接收数据,没有等待
while(!(USART4->ISR &(0x1 << 5)));
//读取数据
a=USART4->RDR;
//返回
return a;
}
//发送一个字符串
void hal_put_string(const char* string)
{
while(*string)
{
hal_put_char(*string);
string++;
}
hal_put_char('\r');
hal_put_char('\n');
}
//接收一个字符串
void hal_get_string(char *s)
{
while(1)
{
*s=hal_get_cahr();
//键盘输入的内容在串口上回显
hal_put_char(*s);
if(*s=='\r')
break;
s++;
}
*s='\0';
}
uart4.h
main.c