1、在键盘输入一个字符,串口工具进行显示
2、在键盘输入一个字符串,串口工具进行显示
代码
uart4.h
#ifndef __UART4_H__
#define __UART$_H__
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_uart.h"
//初始化函数
void hal_uart_init();
//发送一个字符
void hal_put_char(const char str);
//发送一个字符串
void hal_put_string(const char* string);
//接收一个字付
char hal_get_char();
//接收一个字符串
char* hal_get_string();
#endif
uart.c
#include "uart4.h"
//初始化函数
void hal_uart_init()
{
/********RCC章节初始化*********/
RCC->MP_AHB4ENSETR|=(0x1 << 1);
RCC->MP_AHB4ENSETR|=(0x1 << 6);
RCC->MP_APB1ENSETR|=(0x1 << 16);
/********GPIO章节初始化********/
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 << 12));
USART4->CR1 &= (~(0x1 << 28));
USART4->CR1 &= (~(0x1 << 15));
USART4->CR1 &= (~(0x1 << 10));
USART4->CR1 |= (0x3 << 2);
USART4->CR1 |= (0x1 << 0);
USART4->CR2 &= (~(0x3 << 12));
USART4->BRR = 0x22B;
USART4->PRESC = 0x0;
}
//发送一个字符
void hal_put_char(const char str)
{
//1.判断发送数据寄存器是否为空
while(!(USART4->ISR & (0x1 << 7)));
//2.将要发送的数据,放入到发送数据寄存器中
USART4->TDR = 0x0;
USART4->TDR = str;
//3.判断发送数据寄存器是否发送完成
while(!(USART4->ISR & (0x1 << 6)));
}
//接受一个字符
char hal_get_char()
{
static char ch;
//1.判断接收数据寄存器中是否有数据可读
while(!(USART4->ISR & (0x1 << 5)));
//2.将接收数据寄存器中的数值赋值给ch
ch = USART4->RDR;
return ch;
}
//发送一个字符串
void hal_put_string(const char* string)
{
int n = 0;
//判断是否为'\0',一个一个发送
while(1)
{
hal_put_char(*(string+n));
if(*(string+n) == '\r')
{
hal_put_char('\n');
break;
}
n++;
}
}
//接收一个字符串
char* hal_get_string()
{
static char buf[100] = "\0";
int i = 0;
while(1)
{
buf[i] = hal_get_char();
hal_put_char(buf[i]);
if(buf[i] == '\r')
{
hal_put_char('\n');
break;
}
i++;
}
return buf;
}
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()
{
hal_uart_init();
while(1)
{
//hal_put_char(hal_get_char()+1);
hal_put_string(hal_get_string());
}
return 0;
}
运行结果
实验一结果:
实验二结果: