一、练习
uart.c
#include "uart4.h"
void uart4_config()
{
//使能GPIOB\G\UART4的外设时钟
RCC->MP_AHB4ENSETR |=(0x1<<1);
RCC->MP_AHB4ENSETR |=(0x1<<6);
RCC->MP_APB1ENSETR |=(0x1<<16);
//设置PG11和PB2的管脚复用功能
GPIOB->MODER &=(~(0x3<<4));
GPIOB->MODER |=(0x2<<4);
GPIOG->MODER &=(~(0x3<<22));
GPIOG->MODER |=(0x2<<22);
//设置PG11为uart_tx功能
GPIOG->AFRH &=(~(0xf<<12));
GPIOG->AFRH |=(0x6<<12);
//设置PB2为uart_rx功能
GPIOB->AFRL &=(~(0xf<<8));
GPIOB->AFRL |=(0x8<<8);
//设置串口不使能
USART4->CR1 &=(~0x1);
//设置8位数据位
USART4->CR1 &=(~(0x1<<12));
USART4->CR1 &=(~(0x1<<28));
//设置没有校验位
USART4->CR1 &=(~(0x1<<10));
//设置时钟频率不分频
USART4->PRESC &=(~0xf);
//设置16倍过采样
USART4->CR1 &=(~(0x1<<15));
//设置1位停止位
USART4->CR2 &=(~(0x3<<12));
// 设置波特率为115200
USART4->BRR =0x22b;
//使能发射器
USART4->CR1 |=(0x1<<3);
//使能接收器
USART4->CR1 |=(0x1<<2);
//使能串口
USART4->CR1 |=(0x1<<0);
}
void putchar(char date)
{
while (!(USART4->ISR &(0x1<<7)));
USART4->TDR=date;
while (!(USART4->ISR &(0x1<<6)));
}
char getchar()
{
while (!(USART4->ISR &(0x1<<5)));
return USART4->RDR;
}
void puts(char *str)
{
while(1)
{
if(*str=='\0' || *str=='\r')
{
break;
}
else{
putchar(*str);
str++;
}
}
putchar('\r');
}
void gets(char *str)
{
char c='\0';
int i=0;
while (1)
{
c= getchar();
if(c=='\0' || c=='\r')
{
break;
}
else{
str[i]=c;
i++;
}
}
str[i]='\0';
str[i+1]='\r';
}
main.c
#include "uart4.h"
int main()
{
uart4_config();
char *str="";
while (1)
{
gets(str);
puts(str);
}
return 0;
}
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_uart.h"
char *gets();
void puts(char *str);
char getchar();
void putchar(char date);
void uart4_config();
void SP_CTRL(int flag);
#endif