头文件
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_uart.h"
//UART4串口初始化
void hal_uart_init();
//发送一个字符
void put_char(const char str);
//发送一个字符串
void put_string(const char* string);
//接收一个字符
char get_char();
//接收一个字符串
char* get_string();
#endif
功能文件
#include "uart4.h"
extern void delay_ms(int ms);
//UART4串口初始化
void hal_uart_init()
{
/********RCC相关寄存器初始化************/
RCC->MP_AHB4ENSETR |= (0x1 << 1);
RCC->MP_AHB4ENSETR |= (0x1 << 6);
RCC->MP_APB1ENSETR |= (0x1 << 16);
/********GPIO相关寄存器初始化************/
GPIOB->MODER &= (~(0x3 << 4));
GPIOB->MODER |= (0x1 << 5);
GPIOG->MODER &= (~(0x3 << 22));
GPIOG->MODER |= (0x1 << 23);
GPIOB->AFRL &= (~(0xf) << 8);
GPIOB->AFRL |= (0x1 << 11);
GPIOG->AFRH &= (~(0xf << 12));
GPIOG->AFRH |= (0x3 << 13);
/********UART4相关寄存器初始化************/
//USART4_CR1
USART4->CR1 &= (~(0x1 << 28));
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 15));
USART4->CR1 &= (~(0x1 << 10));
USART4->CR1 |= (0x1 << 3);
USART4->CR1 |= (0x1 << 2);
USART4->CR1 |= 0x1;
//CR2
USART4->CR2 &= (~(0x3 << 12));
//BRR
USART4->BRR = 0x22b;
//PRESC
USART4->PRESC &= (~0xf);
}
//发送一个字符
void put_char(const char str)
{
//满则等待
while(!(USART4->ISR &=(0x1 << 7)));
USART4->TDR = str;
//没发完一直发
while(!(USART4->ISR &=(0x1 << 6)));
}
//发送一个字符串
void put_string(const char* string)
{
while(*string != '\0')
{
put_char(*string);
string++;
}
put_char('\r');
put_char('\n');
}
//接收一个字符
char get_char()
{
char flag;
while(!(USART4->ISR &=(0x1 << 5)));
flag = USART4->RDR;
return flag;
}
char buf[20] = {0};
//接收一个字符串
char* get_string()
{
int i = 0;
for(i=0; i<20-1; i++)
{
buf[i] = get_char();
put_char(buf[i]);
if(buf[i] == '\r')
{
break;
}
}
buf[i] = '\0';
put_char('\n');
return buf;
}
测试文件
#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_uart_init();
while(1)
{
// put_char(get_char()+1);
put_string(get_string());
}
return 0;
}
现象:
1、字符+1
输入:abcdef
输出:bcdefg
2、字符串显性打印