#include "uart4.h"
extern void delay_ms(int ms);
//1.初始化函数
void uart4_init()
{
/*******RCC章节初始化******/
//1.使能GPIOB控制器 MP_AHB4ENSETR[1] = 1
RCC->MP_AHB4ENSETR |= (0x1 << 1);
//2.使能GPIOG控制器 MP_AHB4ENSETR[6] = 1
RCC->MP_AHB4ENSETR |= (0x1 << 6);
//3.使能UART4控制器 MP_APB1ENSETR[16] = 1
RCC->MP_APB1ENSETR |= (0x1 << 16);
/*******GPIO章节初始化******/
//PB2---->UART4_Rx
//PG11----->UART4_Tx
//1.设置PB2引脚为复用功能 MODER[5:4] = 10
GPIOB->MODER &= (~(0x3 << 4));
GPIOB->MODER |= (0x1 << 5);
//2.设置PB2引脚复用功能为UART4_Rx AFRL[11:8] = 1000
GPIOB->AFRL &= (~(0xf << 8));
GPIOB->AFRL |= (0x1 << 11);
//3.设置PG11引脚为复用功能 MODER[23:22] = 10
GPIOG->MODER &= (~(0x3 << 22));
GPIOG->MODER |= (0x1 << 23);
//4.设置PG11引脚复用功能为UART4_Tx AFRH[15:12] = 0110
GPIOG->AFRH &= (~(0xf << 12));
GPIOG->AFRH |= (0x3 << 13);
/*******UART章节初始化******/
if(USART4->CR1 & (0x1 << 0))
{
delay_ms(500);
//将UE为禁止 CR1[0] = 0
USART4->CR1 &= (~(0x1 << 0));
}
//1.串口初始化 8位数据位 无奇偶校验位 CR1[28][12]=00 CR1[10]=0
USART4->CR1 &= (~(0x1 << 28));
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 10));
//2.设置串口一位停止位 CR2[13:12] = 00
USART4->CR2 &= (~(0x3 << 12));
//3.设置串口16倍采样率 CR1[15] = 0
USART4->CR1 &= (~(0x1 << 15));
//4.设置串口不分频 PRESC[3:0] = 0000
USART4->PRESC &= (~(0xf << 0));
//5.设置串口波特率115200 BRR = 0x22b
USART4->BRR = 0x22b;
//6.设置串口发送器使能 CR1[3] = 1
USART4->CR1 |= (0x1 << 3);
//7.设置串口接收器使能 CR1[2] = 1
USART4->CR1 |= (0x1 << 2);
//8.设置串口使能 CR1[0] = 1
USART4->CR1 |= (0x1 << 0);
}
//2.发送一个字符
void put_char(const char str)
{
//1.判断发送数据寄存器是否有数据 ISR[7]
//读0:发送数据寄存器满,需要等待
//读1:发送数据寄存器为空,才可以发送下一个字节数据
while(!(USART4->ISR & (0x1 << 7)));
//2.将要发送的字符,写入到发送数据寄存器中
USART4->TDR = str;
//3.判断发送数据是否发送完成
//读0:发送数据没有完成,需要等待
//读1:发送数据完成,可以发送下一帧数据
while(!(USART4->ISR & (0x1 << 6)));
}
//3.发送一个字符串
void put_string(const char* str)
{
//判断是否为'\0'
//一个一个字符的进行发送
while(*str)
{
put_char(*str++);
}
put_char('\n');
put_char('\r');
}
//4.接收一个字符
char get_char()
{
char ch;
//1.判断接收寄存器是否有数据可读 ISR[5]
//读0:没有数据可读,需要等待
//读1:有数据可读
while(!(USART4->ISR & (0x1 << 5)));
//2.将接收数据寄存器中的内容读出来
ch = USART4->RDR;
return ch;
}
char buffer[50] = {0};
//5.接收一个字符串
char* get_string()
{
unsigned int i;
//1.循环进行接收
//2.循环实现:接收一个字符之后,发送一个字符
//当键盘回车建按下之后,代表字符串接收结束'\r'
for(i=0;i<49;i++)
{
buffer[i] = get_char();
put_char(buffer[i]);
if(buffer[i] == '\r')
break;
}
//3.字符串补'\0'
buffer[i] = '\0';
put_char('\n');
return buffer;
}
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_uart.h"
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
//1.初始化函数
void uart4_init();
//2.发送一个字符
void put_char(const char str);
//3.发送一个字符串
void put_string(const char* str);
//4.接收一个字符
char get_char();
//5.接收一个字符串
char* get_string();