效果:(字符串的收发还是有问题,只能实现预置字符串的发送,无法实现输入字符串回响)
代码:
#include "uart4.h"
void hal_uart4_init()
{
// GPIOB使能
RCC->MP_AHB4ENSETR |= (0x1 << 1);
// GPIOG使能
RCC->MP_AHB4ENSETR |= (0x1 << 6);
// UART4使能
RCC->APB1RSTCLRR |= (0x1 << 16);
// GPIOG设置为复用
GPIOG->MODER &= (~(0x3 << 22));
GPIOG->MODER |= (0x2 << 22);
// GPIOB设置为复用
GPIOB->MODER &= (~(0x3 << 4));
GPIOB->MODER |= (0x2 << 4);
// GPIOB的复用功能设置
GPIOB->AFRL &= (~(0xF << 8));
GPIOB->AFRL |= (0x8 << 8);
// GPIOG的复用功能设置
GPIOG->AFRL &= (~(0xF << 12));
GPIOG->AFRL |= (0x6 << 12);
// UART初始化
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 28));
USART4->CR1 &= (~(0x1 << 10));
USART4->CR1 &= (~(0x1 << 15));
USART4->CR1 |= (0x1 << 2);
USART4->CR1 |= (0x1 << 3);
USART4->CR1 |= (0x1);
// UART设置停止位
USART4->CR2 &= (~(0X3 << 12));
// UART设置波特率
USART4->BRR &= (~(0XFFF));
USART4->BRR |= (0X22B);
}
// 发送一个字符
void hal_put_char(const char str)
{
while (!(USART4->ISR & 1 << 6))
; // 如果不为1则一直循环等待上一位发送完毕
USART4->TDR = str;
}
// 发送一个字符串
void hal_put_string(const char *string)
{
while (*string != '\0')
{
hal_put_char(*string++);
}
}
// 接收一个字符
char hal_get_char()
{
while (!(USART4->ISR & 1 << 5))
; // 等待一直到接收到数据为止
return USART4->RDR;
}
// 接受一个字符串
char *hal_get_string()
{
char buff[128];
int i = 0;
while (hal_get_char() != '\n' || hal_get_char() != '\r')
{
buff[i++] = hal_get_char();
}
buff[i] = '\0';
return buff;
}