include/uart4.h
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_uart.h"
//初始化相关操作
void hal_uart4_init();
//发送一个字符
void hal_put_char(const char str);
//发送一个字符串
void hal_put_string(const char* string);
//接收一个字符
char hal_get_char();
//接收一个字符串
char* hal_get_string();
#endif
src/yart4.c
#include "uart4.h"
//PB2--->UART4_RX
//PG11--->UART4_TX
//初始化相关操作
void hal_uart4_init()
{
//~~~~~~~~~~~~~RCC章节初始化~~~~~~~~~~~~~~~~~~~~~~~~//
//使能AHB4初始化GPIOB GPIOG[1] [6] =1
RCC->MP_AHB4ENSETR |= (0x21 << 1);
//使能APB1初始化[16]=1
RCC->MP_APB1ENSETR |= (0x1 << 16);
//~~~~~~~~~~~~~GPIO章节初始化~~~~~~~~~~~~~~~~~~~~~~~//
//GPIOB寄存器初始化 [5:4]=10
GPIOB->MODER |= (0x1 << 5);
GPIOB->MODER &= (~(0x1 << 4));
//GPIOB_AFRL设置引脚的复用功能模式[11:8]=1000
GPIOB->AFRL |= (0x1 << 11);
GPIOB->AFRL &= (~(0x7 << 8));
//GPIOG寄存器初始化 [23:22]=10
GPIOG->MODER |= (0x1 << 23);
GPIOG->MODER &= (~(0x1 << 22));
//GPIOG_AFRH设置引脚的复用功能模式[15:12]=0110
GPIOG->AFRH |= (0xF << 15);
GPIOG->AFRH &= (~(0x9 << 15));
//~~~~~~~~~~~~~UART章节初始化~~~~~~~~~~~~~~~~~~~~~~//
//0.设置串口UE=0 [0]=0
USART4->CR1 &= (~(0x1));
//1.设置1位的起始位,8位数据位 [28]=0 [12]=0
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 28));
//2.没有校验位 CR1[10]=0
USART4->CR1 &= (~(0x1 << 10));
//3.设置1位停止位 CR2[13:12] =00
USART4->CR2 &= (~(0x3 << 13));
//4.设置16倍采样率 CR1[15]=0
USART4->CR1 &= (~(0x1 << 15));
//5.设置串口不分频 0000
USART4->PRESC &= (~(0xF));
//6.设置串口波特率为0x22b 时钟源/波特率 64000000/115200
USART4->BRR = 0x22b;
//7.设置串口发送器使能
USART4->CR1 |= (0x1 << 3);
//8.设置串口接收器使能
USART4->CR1 |= (0x1 << 2);
//9.设置串口使能
USART4->CR1 |= (0x1);
}
//发送一个字符
void hal_put_char(const char str)
{
//1.判断发送数据寄存器是否为空ISR[7]
//特点:为空才可以发送下一位数据,为满则需要等待
//读0:满,等待 读1:发送数据
while(!(USART4->ISR & (0x1 << 7)));
//2.将发送的内容,赋值给发送给数据寄存器
USART4->TDR &= 0;
USART4->TDR = str;
//3.判断一帧数据是否发送完成 ISR[6]
while(!(USART4->ISR & (0x1 << 6)));
//读0:没有发送完成,需要等待 读1:发送完成
}
//接收一个字符
char hal_get_char()
{
//1.判断接收数据寄存器是否接收到数据 ISR[5]
while(!(USART4->ISR & (0x1 << 5)));
//2.将接收数据寄存器中的内容读出来
char ch = USART4->RDR;
return ch;
}
//发送一个字符串
void hal_put_string(const char* string)
{
//判断字符串输入完成标志'\0'
const char *p = string;
while(*p != '\0')
{
hal_put_char(*p);
p++;
}
//一个字符一个字符进行发送
hal_put_char('\n');
}
//接收一个字符串
char* hal_get_string()
{
//循环进行接收
static char string[32] = {0};
int i;
for(i = 0;i < 32; i++)
{
string[i] = 0;
}
i = 0;
while(1)
{
string[i] = hal_get_char();
hal_put_char(string[i]);
if(string[i] == '\r')
{
break;
}
i++;
}
hal_put_char('\n');
return string;
//当键盘的回车键按键之后,代表字符串输出完成'\r'
}
main.c
#include "uart4.h"
extern void printf(const char *fmt, ...);
void delay_ms(int ms)
{
int i,j;
for(i = 0; i < ms;i++)
for (j = 0; j < 1800; j++);
}
int main()
{
hal_uart4_init();
hal_put_string("----please input--->");
while(1)
{
hal_put_char(hal_get_char()+1);
//hal_put_string(hal_get_string());
}
return 0;
}
hal_put_char(hal_get_char()+1);
hal_put_string(hal_get_string());