uart4.h
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_uart.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"
//初始化
void uart4_init();
//发送一个字符
void put_char(const char ch);
//接受一个字符
char get_char();
//发送一个字符串
void put_string(const char *ch);
//接受一个字符串
char *get_string();
#endif
uart4.c
#include "uart4.h"
extern void delay_ms(int ms);
//初始化函数
void uart4_init()
{
//******RCC章节初始化******
//RCC使能
RCC->MP_AHB4ENSETR |= (0x1 << 1);
RCC->MP_AHB4ENSETR |= (0x1 << 6);
RCC->MP_APB1ENSETR |= (0x1 << 16);
//******GPIO章节初始化******
//PB2引脚设置复用
GPIOB->MODER &= (~(0x1 << 4));
GPIOB->MODER |= (0x1 << 5);
GPIOB->AFRL &= (~(0xf << 8));
GPIOB->AFRL |= (0x1 << 11);
//PG11引脚设置复用
GPIOG->MODER &= (~(0x1 << 22));
GPIOG->MODER |= (0x1 << 23);
GPIOG->AFRH &= (~(0xf << 12));
GPIOG->AFRH |= (0x3 << 13);
//******UART章节初始化******
//禁用UE
if(USART4->CR1 & (0x1<<0))
{
delay_ms(500);
USART4->CR1 &= (~(0x1));
}
// 设置数据长度为8位 USART_CR1
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 28));
USART4->CR1 &= (~(0x1 << 10));
// 停止位1位
USART4->CR2 &= (~(0x3 << 12));
// 采样率为16位
USART4->CR1 &= (~(0x1 << 15));
// 设置波特率为115200bps
USART4->PRESC &= (~(0xf));
USART4->BRR |= (0x22B);
// 使能USART的发送或者接收功能
USART4->CR1 |= (0x3 << 2);
// USART4->CR1 |= (0x1 << 2);
// 使能USART串口
USART4->CR1 |= (0x1);
}
//发送一个字符
void put_char(const char ch)
{
//判断ISR寄存器是否有数据ISR[7]
//读0满,读1空
while(!(USART4->ISR & (0x1 << 7)));
USART4->TDR = ch;
//判断发送数据是否完成
while(!(USART4->ISR & (0x1 << 6)));
}
//接受一个字符
char get_char()
{
char ch;
//判断ISR寄存器是否有数据可读ISR[5]
//读0没有,读1有
while(!(USART4->ISR & (0x1 << 5)));
ch = USART4->RDR;
return ch;
}
//发送一个字符串
void put_string(const char *ch)
{
const char *p = ch;
while(*p != '\0')
{
while(!(USART4->ISR & (0x1 << 7)));
USART4->TDR = *p;
while(!(USART4->ISR & (0x1 << 6)));
p++;
}
}
char str[50] = {0};
//接受一个字符串
char *get_string()
{
str[0] = '\n';
int i = 1;
while(1)
{
while(!(USART4->ISR & (0x1 << 5)));
put_char(get_char());
str[i] = USART4->RDR;
i++;
if(USART4->RDR == '\r')
break;
}
str[i++] = '\n';
str[i] = '\0';
return str;
}
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(void)
{
uart4_init();
while(1)
{
// put_char(get_char()+1);
put_string(get_string());
}
return 0;
}