//头文件
#ifndef __UART_H__
#define __UART_H__
#include "stm32mp1xx_uart.h"
/*#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"*/
#define RCC_D ((volatile unsigned int*)0x50000A28)
#define RCC_MP ((volatile unsigned int*)0x50000A00)
#define GPIOB_MD ((volatile unsigned int*)0x50003000)
#define GPIOG_MD ((volatile unsigned int*)0x50008000)
#define GPIOx_AL ((volatile unsigned int*)0x50003020)
#define GPIOx_AH ((volatile unsigned int*)0x50008024)
//初始化串口
void __uart_init();
//发送一个字符
void __uart_putc(const char data);
//发送一个字符串
void __uart_puts(const char *pstr);
//接收一个字符
char __uart_getc(void);
//接收一个字符串
char* __uart_string(void);
#endif
//主函数
#include "./include/uart.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()
{
//初始化串口
__uart_init();
while(1)
{
//__uart_putc(__uart_getc());
__uart_puts(__uart_string());
}
return 0;
}
//功能函数
#include "../include/uart.h"
extern void delay_ms(int ms);
extern void printf(const char *fmt, ...);
//初始化串口
void __uart_init(){
//rcc使能章节
*RCC_D = *RCC_D|(0x1<<1);
*RCC_D = *RCC_D|(0x1<<6);
*RCC_MP = *RCC_MP|(0x1<<16);
//gpio初始化章节
//GPIOB使能
*GPIOB_MD = *GPIOB_MD&(~(0x3<<4));
*GPIOB_MD = *GPIOB_MD|(0x1<<5);
//GPIOG使能
*GPIOG_MD = *GPIOG_MD&(~(0x3<<22));
*GPIOG_MD = *GPIOG_MD|(0x1<<23);
//串口接收
*GPIOx_AL = *GPIOx_AL&(~(0xf<<8));
*GPIOx_AL = *GPIOx_AL|(0x1<<11);
//串口发送
*GPIOx_AH = *GPIOx_AH&(~(0xf<<12));
*GPIOx_AH = *GPIOx_AH|(0x3<<13);
//uart初始化章节
//USART_CR1:设置数据位,设置串口使能,设置发送位使能,设置串口接收位使能
if(USART4->CR1&(0x1)){
delay_ms(500);
USART4->CR1=USART4->CR1&(~(0x1<<0));
}
USART4->CR1=USART4->CR1&(~(0x1<<12));
USART4->CR1=USART4->CR1&(~(0x1<<28));
USART4->CR1=USART4->CR1&(~(0x1<<15));
USART4->CR1=USART4->CR1&(~(0x1<<10));
USART4->CR1=USART4->CR1&(~(0x1<<3));
USART4->CR1=USART4->CR1|(0x1<<3);
USART4->CR1=USART4->CR1&(~(0x1<<2));
USART4->CR1=USART4->CR1|(0x1<<2);
//USART_BRR:设置串口波特率
//USART4->BRR&=(~(0xffff<<0));
USART4->BRR|=0x22b;
//USART_CR2:设置串口停止位位数
USART4->CR2=USART4->CR2&(~(0x3<<12));
//USART_PRESC:设置串口分频器
USART4->PRESC=USART4->PRESC&(~(0xf));
USART4->CR1=USART4->CR1|(0x1<<0);
}
//发送一个字符
void __uart_putc(const char data){
while(!(USART4->ISR & (0x1<<7)));
USART4->TDR=data;
while(!(USART4->ISR & (0x1<<6)));
}
//发送一个字符串
void __uart_puts(const char *pstr){
while (!(USART4->ISR&(0x1<<7)));
while (*pstr)
{
__uart_putc(*pstr++);
}
//*pstr = '\r';
//__uart_putc(*pstr);
__uart_putc('\n');
__uart_putc('\r');
}
//接收一个字符
char __uart_getc(void){
char ch;
while(!(USART4->ISR & (0x1<<5)));
ch = USART4->RDR;
return ch;
}
//接收一个字符串
char buf[50]="";
char* __uart_string(void){
int i;
for(i=0;i<sizeof(buf)-1;i++){
buf[i]=__uart_getc();
__uart_putc(buf[i]);
if(buf[i]=='\r'){
break;
}
}
__uart_putc('\0');
__uart_putc('\n');
return buf;
}