串口工具输入一个字符串,按下回车键,会显示输入的字符串
uart.h
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_uart.h"
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
void uart4_init();
void put_char(const char str);
void put_string(const char* str);
char get_char();
char* get_chat();
#endif
uart.c
#include "uart4.h"
void uart4_init()
{
//rcc初始化
//1.使能GPIO控制器
RCC->MP_AHB4ENSETR |= (0x1 << 1);
RCC->MP_AHB4ENSETR |= (0x1 << 6);
RCC->MP_APB1ENSETR |= (0x1 << 16);
//GPIO初始化
//1.PB2,PG11引脚复用
//2.设置为UART4_RX,UART4_TX
GPIOB->MODER &= (~(0x3 << 4));
GPIOB->MODER |= (0x1 << 5);
GPIOG->MODER &= (~(0x3 << 22));
GPIOG->MODER |= (0x1 << 23);
GPIOB->AFRL &= (~(0xf << 8));
GPIOB->AFRL |= (0x1 << 11);
GPIOG->AFRH &= (~(0xf << 12));
GPIOG->AFRH |= (0x3 << 13);
//UART章节初始化
USART4->CR1 &= (~(0x1 << 28));
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 15));
USART4->CR1 &= (~(0x1 << 10));
USART4->CR1 |= (0x1 << 3);
USART4->CR1 |= (0x1 << 2);
USART4->CR1 |= (~(0x1 << 1));
USART4->CR2 &= (~(0x3 << 12));
USART4->BRR &= (~(0xffff));
USART4->BRR |= 0x22b;
}
void put_char(const char str)
{
while(!(USART4->ISR & (0x1 << 7)));
USART4->TDR &= (~(0xff));
USART4->TDR = str;
while(!(USART4->ISR & (0x1 << 6)));
}
void put_string(const char* str)
{
while(*str != '\0')
{
put_char(*str);
str++;
}
put_char('\n');
put_char('\r');
}
char get_char()
{
char cn;
while(!(USART4->ISR & (0x1 << 5)));
cn = USART4->RDR;
return cn;
}
char buffer[50] = {0};
char* get_chat()
{
while(!(USART4->ISR & (0x1 << 5)));
int i=0;
while((buffer[i]=get_char())!='\r' )
{
put_char(buffer[i]);
i++;
}
buffer[i] = '\0';
return buffer;
}
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)
{
uart4_init();
put_char('\n');
put_char('\t');
while(1)
{
put_char(get_char() + 1);
}
}
return 0;
}