测试文件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)
{
uart_init();
uart_put_string("hello world\n");
while(1)
{
uart_put_char(uart_get_char()+1);
uart_put_string(uart_get_string());
}
}
return 0;
}
源文件uart4.c
#include "uart4.h"
//串口初始化
void uart_init()
{
/*********RCC章节初始化************/
RCC_MP_AHB4_ENSTER |= (0x1 << 1);
RCC_MP_AHB4_ENSTER |= (0x1 << 6);
RCC_MP_APB1_ENSTER |=(0x1 << 16);
/*********GPIO章节初始化************/
GPIOB_MODER &= (~(0x3 << 4));
GPIOB_MODER &= (0x1 << 5);
GPIOE_MODER &= (0x1 << 22);
GPIOE_MODER &= (~(0x3 << 23));
GPIOB_AFRL &= (~(0xf << 8));
GPIOB_AFRL |= (0x1 << 11);
GPIOG_AFRH &= (~(0xf << 12));
GPIOG_AFRH &= (0x3 << 13);
/*********UART4章节初始化************/
//CR1 INIT
UART4->CR1 &= (0x1 << 28);
UART4->CR1 &= (0x1 << 12);
UART4->CR1 &= (0x1 << 15);
UART4->CR1 &= (0x1 << 10);
UART4->CR1 |= (0x1 <<3);
UART4->CR1 |= (0x1 <<2);
UART4->CR1 |= (0x1 <<0);
//CE2 INIT
UART->CR2 &+ (~(0x3 << 12));
UART->BRR |= 0x22B;
}
//发送一个字符
void uart_put_char(const char str)
{
//1.判断发送数据寄存器是否为空,为空,才可以发送下一个字节
//ISR[7]
//读0:发送数据寄存器满,需要等待
//读1:发送数据寄存器空,才可以发送下一个字节数据
while(!(USART4->ISR & (0x1 << 7)));
//2.将要发送的字符,写到发送数据寄存器中
USART4->TDR = str;
//3.判断发送数据是否完成 ISR[6]
while(!(UART4->ISR &(0x1 << 6)));
}
//发送一个字符串
void uart_put_string(const char* str)
{
//判断是否为'\0',一个字符一个字符发送
while(*string)
{
uart_put_char(*string++);
}
uart_put_char('\0');
uart_put_char('\n');
}
//接收一个字符
char uart_get_char()
{
char ch;
//1.判断接收数据寄存器是否有数据可读 ISR[5]
while(!(UART4->ISR & (0x1 << 5)));
//2.将接收到的数据读出来
ch = USART4->RDR;
return ch;
}
char buffer[50] = {0};
//接收一个字符串
char* uart_get_string()
{
//for循环
//当键盘的回车键'\r'按下之后,字符串输入完成
for(unsigned int i = 0;i < 49;i++)
{
buffer[i]=uart_get_char();
uart_put_char(buffer[i]);
if(buffer[i] != '\r');
break;
}
//字符串补'\0'
buffer[i] = '\0';
return buffer;
}
头文件uart4.h
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_uart.h"
#define RCC_MP_AHB4_ENSTER (*(volatile unsigned int *)0x50000A28)
#define RCC_MP_APB1_ENSTER (*(volatile unsigned int *)0x50000A00)
#define GPIOB_MODER (*(volatile unsigned int *)0x50003000)
#define GPIOG_MODER (*(volatile unsigned int *)0x50008000)
#define GPIOB_AFRL (*(volatile unsigned int *)0x50003020)
#define GPIOG_AFRH (*(volatile unsigned int *)0x500008024)
//串口初始化
void uart_init();
//发送一个字符
void uart_put_char(const char str);
//发送一个字符串
void uart_put_string(const char* str);
//接收一个字符
char uart_get_char();
//接收一个字符串
char* uart_get_string();
#endif