目录
题目:1)在键盘上输入一个,字符,字符+1,并且打印在串口工具上
题目:1)在键盘上输入一个,字符,字符+1,并且打印在串口工具上
2)串口工具输入一个字符串,按下回车,会显示输入的字符串
uart4.h
#ifndef __GPIO_H__
#define __GPIO_H__
#include "stm32mp1xx_uart.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"
//初始化函数
void uart4_init();
//发送一个字符
void put_char(const char str);
//接收一个字符
char get_char();
//发送字符串
void put_string(const char *str);
//接收字符串
char *get_string();
#endif
uart4.c
#include "gpio.h"
void uart4_init()
{
/**********RCC章节初始化*********/
RCC->MP_AHB4ENSETR |= (0x1 << 1);
RCC->MP_AHB4ENSETR |= (0x1 << 6);
RCC->MP_APB1ENSETR |= (0x1 << 16);
/*********GPIO章节初始化*********/
// GPIOB2 设置为复用功能
GPIOB->MODER &= (~(0x3 << 4));
GPIOB->MODER |= (0x2 << 4);
GPIOB->AFRL &= (~(0xF << 8));
GPIOB->AFRL |= (0x8 << 8);
// GPIOG11 设置为复用功能
GPIOG->MODER &= (~(0x3 << 22));
GPIOG->MODER |= (0x2 << 22);
GPIOG->AFRH &= (~(0xF << 12));
GPIOG->AFRH |= (0x6 << 12);
/*********UART章节初始化*********/
if(USART4->CR1 & (0x1 << 0))
{
//将UE禁止
USART4->CR1 &= (~(0x1 << 0));
}
// 设置数据长度为8位 USART_CR1
USART4->CR1 &= (~(0x1 << 28));
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 10));
// 停止位1位
USART4->CR2 &= (~(0x3 << 12));
// 采样率为16位
USART4->CR1 &= (~(0x1 << 15));
//设置串口不分频
USART4->PRESC &= (~(0xf));
// 设置波特率为
USART4->BRR &= (~(0xffff));
USART4->BRR = 0x22b;
// 使能USART的发送或者接收功能
USART4->CR1 |= (0x1 << 3);
USART4->CR1 |= (0x1 << 2);
// 使能USART串口
USART4->CR1 |= (0x1 << 0);
}
//发送一个字符
void put_char(const char str)
{
while (!(USART4->ISR & (0x1 << 7)));
USART4->TDR &= (~(0xff));
USART4->TDR = str;
while (!(USART4->ISR & (0x1 << 6)));
}
//接收一个字符
char get_char()
{
char ch;
while(!(USART4->ISR & (0x1 << 5)));
ch = USART4->RDR;
return ch;
}
//发送字符串
void put_string(const char *str)
{
while(*str != '\0')
{
put_char(*str);
str++;
}
put_char('\n');
put_char('\r');
}
char buf[50] = {0};
//接收字符串
char *get_string()
{
while(!(USART4->ISR & (0x1 << 5)));
int i = 0;
while((buf[i] = get_char()) != '\r')
{
put_char(buf[i]);
i++;
}
buf[i] = '\0';
return buf;
}
main.c
#include "gpio.h"
extern void printf(const char *fmt, ...);
int main()
{
uart4_init();
put_char('\n');
put_char('\t');
while(1)
{
//put_char(get_char()+1);
put_string(get_string());
}
return 0;
}
执行结果: