#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_uart.h"
//函数功能:初始化
//RCC初始化
//GPIO初始化
void hal_uart4_init( );
//写入
void hal_get_char(const char str);
//发送
char hal_put_char();
#endif
.c文件
#include "uart4.h"
void hal_uart4_init( )
{
//RCC章节
//使能GPIOB MP_AHB4ENSETR[1]=1
RCC->MP_AHB4ENSETR |= ( 0x1 << 1 );
//GPIOG MP_AHB4ENSETR[6]=1
RCC->MP_AHB4ENSETR |= ( 0x1 << 6 );
//UART4 MP_APB1ENSETR[16]=1
RCC->MP_APB1ENSETR |= ( 0x1 << 16 );
//GPIO章节
//GPIOB
//1)复用功能 MODER[5:4] = 10;
GPIOB->MODER &= (~( 0x3 << 4));
GPIOB->MODER |= (0x1 << 5 );
//2复用功能模式 UART4_RX AFRL[11:8]=1000
GPIOB->AFRL &= (~ (0xf << 8));
GPIOB->AFRL |= (0x1 << 11);
//GPIOG
//1)复用功能 MODER[23:22] = 10 ;
GPIOG->MODER &= (~(0x3 << 22 ));
GPIOG->MODER |= (0x1 << 23 );
//2)复用功能模式 UART4_RX AFRH[15:12] =0110
GPIOG->MODER &= (~( 0xf << 12));
GPIOG->MODER |= (0x3 <<13);
//UART4章节
//初始化 数据收发
//写入步骤
//一
//USART_CR1
//写入 1 start bit, 8 Data bits,n Stop bit
//条件1)UE为0 UE Bits 0
USART4->CR1 &= (~(0x1));
// M[1:0]='00':1 start bit,8 Data bits,n Stop bit
// 2) M1=[1:0] M1 Bits 28
// M0=[1:0] M0 Bits 12
USART4->CR1 &= (~(0x1 << 28));
USART4->CR1 &=(~(0x1 << 12 ));
//补充
//没有奇偶位
USART4->CR1 &=(~(0x1 << 10));
//设置16倍采样率
USART4->CR1 &= (~(0x1 << 15 ));
//设置串口不分频
USART4->PRESC &= (~( 0xf ));
//二
//USART_BRR
//该寄存器只能在UE=0时写入,31-16位保持不变,0-15位写入波特率
USART4->BRR &= (~( 0xff ));
USART4->BRR |= 0x22B;
//三
//USART_CR2
//Bits 13:12 STOP[1:0]: stop bits
//00: 1 stop bit
USART4->CR2 &= (~(0x3 << 12 ));
//四
//USART_CR1中的UE=1 UE Bits 0
USART4->CR1 |= 0x1 ;
//五
//串口发送器使能
USART4->CR1 |= (0x1 << 3);
//串口接受器使能
USART4->CR1 |= (0x1 << 2);
}
//写入一个字符
void hal_get_char(const char str)
{
//判断是否为空 ISR中 TXE Bits 7
//0:满 1:未满
while(!(USART4->ISR & (0x01<<7)));
//在USART_TDR寄存器中写入要发送的数据。
USART4->TDR=str;
// 当最后一个数据写入USART_TDR寄存器时,等待TC=1 TC Bits 6
while(!(USART4->ISR & (0x01 << 6)));
//当FIFO模式被禁用时,这表明最后一帧的传输完成。
}
//接收一个字符
char hal_put_char()
{
//判断接受数据寄存器是否接收到数据ISR[5]
while(!(USART4->ISR & (0x1 << 5)));
//接收数据寄存器中的内容读出来
char c =USART4->RDR;
return c;
}
main
#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_uart4_init();
while(1)
{
hal_get_char(hal_put_char());
}
return 0;
}