代码:
cpp
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_uart.h"
void delay_ms(int ms)
{
int i,j;
for(i=0;i<ms;i++)
{
for(j=0;j<2000;j++);
}
}
void init();
char getc();
void putc(char data);
void puts(char *data);
char *gets(void);
int main()
{
init();//初始化
puts("jntm test");
while(1){
puts(gets());
}
return 0;
}
void init(){
/*RCC章节*/
//设置UART4的RCc时钟使能
//RCC_MP_APB1ENSETR[16]->1
RCC->MP_APB1ENSETR |= (0x1<<16);
//设置GPIOB和GPIOG的时钟使能
//RCC_MP_AHB4ENSETR[6]->1
//RCC_MP_AHB4ENSETR[1]->1
RCC->MP_AHB4ENSETR |= (0x1<<1);
RCC->MP_AHB4ENSETR |= (0X1<<6);
/*-- GPIO章节--*/
//设置PG11和PB2功能复用为UART4功能
//PG11
//GPIOG_MODER[23:22]->10
GPIOG->MODER &= (~(0X3<<22));
GPIOG->MODER |= (0X2<<22);
//GPIOG_AFRH[15:12]->0110
GPIOG->AFRH &= (~(0xf<<12));
GPIOG->AFRH |= (0x6<<12);
//PB2
//GPIOB_MODER[5:4]->10
//GPIOB_AFRL[11:8]->1000
GPIOB->MODER &= (~(0x3<<4));
GPIOB->MODER |= (0X2<<4);
GPIOB->AFRL &= (~(0xF<<8));
GPIOB->AFRL |= (0x8<<8);
/*--UART4章节--*/
//禁用串口
if(USART4->CR1 & 0X1){
delay_ms(500);
USART4->CR1 &=(~(0x1 << 0));
}
//设置数据8个数据位 CR1[28]->0 CR1[12]-》0
USART4->CR1 &= (~(0X1<<28));
USART4->CR1 &= (~(0X1<<12));
//设置没有校验位CR1[10]->0
USART4->CR1 &= (~(0X1<<10));
//设置1个停止位CR2[13:12]->00
USART4->CR2 &= (~(0x3<<12));
//设置16倍采样 CR1[15]->0
USART4->CR1 &= (~(0X1<<15));
//设置波特率为115200 BRR=0X22B
USART4->BRR |= 0X22B;
//设置1分频 PRESC[3:0]->0000
USART4->PRESC &= (~(0XF << 0));
//使能发送器 CR1[3]->1
USART4->CR1 |= (0X1<<3);
//使能接收器 CR1[2]->1
USART4->CR1 |= (0X1<<2);
//使能串口 CR1[0]->1
USART4->CR1 |= (0X1);
}
void putc(char data)
{
//判断发送数据寄存器有没有数据,没有数据时可以发送
while(!(USART4->ISR&(0X1<<7)));
USART4->TDR=data;//将要发送的数据保存在发送寄存器中
while(!(USART4->ISR&(0X1<<6)));//数据传输完成,函数结束
}
char getc(void)
{
char ch;
while(!(USART4->ISR & (0x1 << 5)));
ch = USART4->RDR;
return ch;
}
void puts(char *data){
char *c=data;
for(;*c!='\0';c++){
putc(*c);
}
putc(*c);
putc('\n');
putc('\r');
}
char data[50]="";
char *gets(void){
int i;
for(i=0;i<49;i++){
data[i]=getc();
putc(data[i]);
if(data[i]=='\r')
break;
}
data[i]='\0';
putc('\n');
return data;
}
what a pity,can't run
now,it can run