fun.c
cs
#include "my_typ_head.h"
//初始化
void uart_init()
{
//1.使能GPIOB/GPIOG/UART4时钟 RCC_MP_AHB4ENSETR/RCC_MP_APB1ENSETR
//设置GPIOB\GPIOG控制器时钟使能 0X50000A28
(*(unsigned int *)0X50000A28) |= (0X10);
(*(unsigned int *)0X50000A28) |= (0X1<<6);
//设置UART4时钟使能
(*(unsigned int *)0X50000A00) |= (0X1<<16);
//2.设置PG11/PB2为复用功能 GPIOX_MODER
GPIOG->MODER &=(~(0X3<<22));
GPIOG->MODER |=(0X2<<22);
GPIOB->MODER &=(~(0X3<<4));
GPIOB->MODER |=(0X2<<4);
//3.PG11/PB2为uart4复用功能 GPIOX_AFRL/GPIOX_AFRH
GPIOB->AFRL |=(0X1000<<8);
GPIOG->AFRH |=(0X0110<<12);
//4.设置数据位宽为8位 USART_CR1
USART4->CR1 &= (~(0X1<<28));
USART4->CR1 &= (~(0X1<<12));
//5.设置16倍过采样USART_CR1
USART4->CR1 &=(~(0X1<<15));
//6.设置无校验 USART_CR1
USART4->CR1 &=(~(0X1<<10));
//7.设置停止位 USART_CR2
USART4->CR1 &=(~(0X3<<12));
//8.设置波特率 USART_BRR
USART4->BRR |=(0X22B);
//9.发送器使能 USART_CR1
USART4->CR1 |=(0X1<<3);
//10.接收器使能 USART_CR1
USART4->CR1 |=(0X1<<2);
//11.串口使能 USART_CR1
USART4->CR1 |=(0X1);
}
char readchar()
{
char c;
//1.判断接收数据寄存器数据是否准备好 USART_ISR[5]
while(!(USART4->ISR&(0X1<<5)));
//2.如果准备好就读取 USART_RDR
c=USART4->RDR;
//3.返回
return c;
}
void sendchar(char c)
{
//1.判断发送数据寄存器是否不满USART_ISR[7]
while(!(USART4->ISR&(0X1<<7)));
//2.如果不满就写入 USART_TDR
USART4->TDR=c;
//3.等到发送完成后函数结束 USART_ISR[6]
while(!(USART4->ISR&(0X1<<6)));
}
main.c
cs
#include "my_typ_head.h"
int main()
{
//初始化
uart_init();
char c='A';
while(1)
{
//2.接收一个字节数据
readchar();
//3.发送一个字节数据
sendchar(c);
}
return 0;
}
head.h
cs
#ifndef __GPIO_H__
#define __GPIO_H__
#include "/home/ubuntu/xiangmu/kaifaban_c/02-c/common/include/stm32mp1xx_gpio.h"
#include "/home/ubuntu/xiangmu/kaifaban_c/02-c/common/include/stm32mp1xx_rcc.h"
#include "/home/ubuntu/xiangmu/kaifaban_c/02-c/common/include/stm32mp1xx_uart.h"
void uart_init();
char readchar();
void sendchar(char c);
#endif //__GPIO_H__