main.c
cpp
#include "uart4.h"
//封装延时函数
void delay_ms(int ms)
{
int i,j;
for(i=0;i<ms;i++)
{
for(j=0;j<2000;j++)
{
}
}
}
int main()
{
//使能外设时钟
hal_uart4_init();
for(int i=0;i<10;i++)
{
hal_put_char(hal_get_char());
hal_put_string("Zzzz\n");
}
return 0;
}
UART4.C
cpp
#include "uart4.h"
void hal_uart4_init()
{
//RCC初始化
RCC->MP_AHB4ENSETR |= (0x1 << 1);//GPIOB使能
RCC->MP_AHB4ENSETR |= (0X1 << 6);//GPIOG使能
RCC->MP_APB1ENSETR |= (0X1 << 16);//UART4使能
//GPIO初始化
GPIOB->MODER &= (~(0x3 << 4));//PB2清零
GPIOB->MODER |= (0x2 << 4);//PB2置位10
GPIOG->MODER &= (~(0x3 << 22));//PG11清零
GPIOG->MODER |= (0x2 << 22);//PG11置位10
GPIOB->AFRL &= (~(0XF << 8));//PB2_AFRL清零
GPIOB->AFRL |= (0X8 << 8);//PB2_AFRL置1000
GPIOG->AFRH &= (~(0XF << 12));//PB2_AFRL清零
GPIOG->AFRH |= (0X6 << 12);//PB2_AFRL置0110
//UART初始化
USART4->CR1 &= (0XFFFF);//CR1全置零
USART4->CR1 |= (0XD);//CR1中发送,接收串口使能
USART4->CR2 &= (~(0x3)<<12);//CR2 置位串口一位停止位
USART4->PRESC &= (~(0xF));//PRESC 设置不分频
USART4->BRR=0X22B;//初始化BBR寄存器
}
void hal_put_char(const char str)
{
while(!(USART4->ISR&=(0X4<<5)))//判断发送数据为不为空
{
USART4->TDR=str;
}
}
void hal_put_string(const char *string)
{
for(int i=0;i<100;i++)
{
char t=string[i];
hal_put_char(t);
if(!t)break;
}
}
char hal_get_char()
{
while (!(USART4->ISR&=(0x1<<5)));
char str = USART4->RDR;
char c;
int a;
a = (int)str;
a++;
c=(char)a;
return c;
}
char *hal_get_string()
{
static char t[100];
for(int i=0;i<100;i++)
{
t[i] = hal_get_char();
if(!t[i])break;
}
return t;
}
uart4.h
cpp
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_uart.h"
void hal_uart4_init();//uart4初始化
void hal_put_char(const char str);//发送一个字符串
void hal_put_string(const char* string);//发送一个字符串
char hal_get_char();//接收一个字符
char* hal_get_string();//接收一个字符串
#endif