main.c
#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()
{
while(1)
{
//put_char(get_char()+1);
put_string(get_string());
}
return 0;
}
uart4.h
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_uart.h"
void uart4_init();
void put_string(const char *buf);
void put_char(const char buf);
char* get_string();
char get_char();
#endif
uart4.c
#include "uart4.h"
void uart4_init()
{
//rcc初始化
//使能gpiob
RCC->MP_AHB4ENSETR |= (0x1<<1);
//使能gpiog
RCC->MP_AHB4ENSETR |= (0x1<<6);
//使能uart4
RCC->MP_APB1ENSETR |= (0x1<<16);
//gpio初始化
//设置pb2
GPIOB->MODER &= (~(0x3)<<4);
GPIOB->MODER |= (0x2<<4);
GPIOB->OTYPER &= (~(0X1<<2));
GPIOB->OSPEEDR &= (~(0X3<<4));
GPIOB->PUPDR &= (~(0X3<<4));
GPIOB->AFRL &= (~(0XF<<8));
GPIOB->AFRL |= (0X8<<8);
//设置pg11
GPIOG->MODER &= (~(0x3)<<22);
GPIOG->MODER |= (0x2<<22);
GPIOG->OTYPER &= (~(0X1<<11));
GPIOG->OSPEEDR &= (~(0X3<<22));
GPIOG->PUPDR &= (~(0X3<<22));
GPIOG->AFRH &= (~(0XF<<12));
GPIOG->AFRH |= (0X6<<12);
//uart4初始化
//设置cr1 ue位不使能
USART4->CR1 |= ~0X1;
//WORD LENGTH
USART4->CR1 &= (~(0X1<<12));
USART4->CR1 &= (~(0X1<<28));
//设置16倍采样
USART4->CR1 &= (~(0X1<<15));
//不分频
USART4->PRESC &= (~0XF);
//设置波特率
USART4->BRR &= (~0XFFFF);
USART4->BRR |= 0X22B;
//设置cr2停止位
USART4->CR2 &= (~(0X3<<12));
//设置无校验
USART4->CR1 &= (~(0X1<<10));
//设置cr1 ue位使能
USART4->CR1 |= 0X1;
//设置cr1 te位使能
USART4->CR1 |= ~(0X1<<3);
//设置cr1 re位使能
USART4->CR1 |= ~(0X1<<2);
}
void put_string(const char *buf)
{
for(int i=0;buf[i]!=0;i++)
{
put_char(buf[i]);
}
}
void put_char(const char buf)
{
while((USART4->ISR & (0X1<<7)) != (0X1<<7));
USART4->TDR = buf;
while((USART4->ISR & (0X1<<6)) != (0X1<<6));
}
char* get_string()
{
static char str[32];
for(int i=0;i<sizeof(str)-2;i++)
{
str[i] = get_char();
put_char(str[i]);
if(str[i] == '\r')
{
put_char('\n');
str[i+1] = '\n';
str[i+2] = '\0';
break;
}
}
return str;
}
char get_char()
{
while((USART4->ISR & (0X1<<5)) != (0X1<<5));
return (char)USART4->RDR;
}
1.输入a输出b
2.输入“nihao”,输出“nihao”