uart4.h
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_uart.h"
//RCC/GPIO/UART4章节初始化
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
uart4.c
#include "uart4.h"
//RCC/GPIO/USART4章节初始化
void hal_uart4_init()
{
//RCC章节初始化
//1.使能GPIOB组控制器
//2.使能GPIOG组控制器
//3.使能USART4组控制器
RCC->MP_AHB4ENSETR |= (0x1<<1);
RCC->MP_AHB4ENSETR |= (0x1<<6);
RCC->MP_APB1ENSETR |= (0X1<<16);
//GPIO章节初始化
//1.设置PB2引脚为复用功能
//2.设置PB2引脚复用功能为USART4_RX
GPIOB->MODER &= (~(0x3<<4));
GPIOB->MODER |= (0x1<<5);
GPIOB->AFRL &= (~(0xf<<8));
GPIOB->AFRL |= (0x1<<11);
//1.设置PG11引脚为复用功能
//2.设置PG11引脚复用功能为USART4_TX
GPIOG->MODER &= (~(0x3<<22));
GPIOG->MODER |= (0x1<<23);
GPIOG->AFRH &= (~(0xf<<12));
GPIOG->AFRH |= (0x3<<13);
//USART4章节初始化
//8N1 115200使能
//0.设置UE=0,CR1[0]=0
//1.设置USART41位的起始位,8位的数据位CR1[28][12]=00
//2.设置USART4串口没有校验,CR1[10]=0
//3.设置USART4串口1位停止位,CR2[13:12]=00
//4.设置USART4串口16倍采样率,CR1[15]=0
//5.设置USART4串口不分频,PRESC[3:0]=0000
//6.设置USART4串口波特率 115200 BRR = 0x22B
//7.设置USART4串口发送器使能 CR1[3] = 1
//8.设置USART4串口接收器使能 CR1[2] =1
//9.设置USART4串口使能,CR1[0]=1
USART4->CR1 |= (0X1);
USART4->CR1 &= (~(0x1<<28));
USART4->CR1 &= (~(0x1<<12));
USART4->CR1 &= (~(0x1<<10));
USART4->CR2 &= (~(0x3<<12));
USART4->CR1 &= (~(0x1<<15));
USART4->PRESC &= (~(0xf));
USART4->BRR &= (~(0xffff));
USART4->BRR |= (~(0x22B));
USART4->CR1 |= (0x1<<3);
USART4->CR1 |= (0x1<<2);
USART4->CR1 |= (0x1);
}
//发送一个字符函数
void hal_put_char(const char str)
{
//1.判断发送数据寄存器是否为空
//读0:发送数据寄存器满,需要等待
//读1:发送数据寄存器空,可以发送数据
while(!(USART4->ISR & (0x1<<7))); //如果是真则继续,假则阻塞
//2.将要发送的数据,赋值给发送数据寄存器中
USART4->TDR=str;
//3.判断一帧数据是否发送完成
while(!(USART4->ISR & (0x1<<6)));
}
//发送一个字符串函数
void hal_put_string(const char* string)
{
//判断是否为'\0'
//一个一个字符进行发送就可以
for(int i=0;string[i]!=0;i++)
{
hal_put_char(string[i]);
}
}
//接收一个字符函数
char hal_get_char()
{
//判断接收寄存器中,是否接收到数据
while(!(USART4->ISR & (0x1<<5)));
//将接收数据寄存器内容,读出来
return (char)USART4->RDR;
}
//接收一个字符串函数
char* hal_get_string()
{
//循环
//enter='\r'
static char s[32]="";
for(int i=0;i<sizeof(s);i++)
{
s[i]=hal_get_char();
hal_put_char(s[i]);
if(s[i]=='\r')
{
hal_put_char('\n');
s[i+1]='\n';
s[i+2]='\0';
break;
}
}
return s;
}
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()
{
while(1)
{
// hal_put_char(hal_get_char()+1);
hal_put_string(hal_get_string());
}
return 0;
}
现象: