实验1
1.在键盘输入一个字符,串口工具进行显示
2.例如:在在键盘输入一个字符'a',串口工具进行显示'b'
实验2
1.在键盘输入一个字符串,串口工具进行显示
2.例如:在在键盘输入一个字符串“huyue”,串口工具进行显示“huyue”
include/uart4.h
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_uart.h"
//初始化相关操作
void hal_uart4_init();
//发送一个字符
void hal_put_char(const char str);
//接收一个字符
char hal_get_char();
//发送一个字符串
void hal_put_string(const char *string);
//接收一个字符串
char *hal_get_string();
#endif
src/uart4.c
#include "uart4.h"
//初始化相关操作
void hal_uart4_init()
{
/*-----RCC初始化-----*/
//使能GPIOB/G
RCC->MP_AHB4ENSETR |= (0X1 << 1);
RCC->MP_AHB4ENSETR |= (0X1 << 6);
//使能UART4
RCC->MP_APB1ENSETR |= (0x1 << 16);
/*-----GPIO初始化-----*/
//设置引脚为复用功能模式
GPIOB->MODER &= (~(0x3 << 4));
GPIOB->MODER |= (0x1 << 5);
GPIOG->MODER &= (~(0x3 << 22));
GPIOG->MODER |= (0x1 << 23);
//设置PB2引脚为UART4_RX模式
GPIOB->AFRL &= (~(0xf << 8));
GPIOB->AFRL |= (0x1 << 11);
//设置PG11引脚为UART4_TX模式
GPIOG->AFRH &= (~(0xf << 12));
GPIOG->AFRH |= (0x3 << 13);
/*-----UART初始化-----*/
//8位数据位
USART4->CR1 &= (~(0x1 << 28));
USART4->CR1 &= (~(0x1 << 12));
//16倍采样率
USART4->CR1 &= (~(0x1 << 15));
//无奇偶校验
USART4->CR1 &= (~(0x1 << 10));
//1位停止位
USART4->CR2 &= (~(0x3 << 12));
//波特率
USART4->BRR &= (~(0xffff));
USART4->BRR |= (0x22b);
//不分频
USART4->PRESC &= (~(0xf));
//发送器使能
USART4->CR1 |= (0x1 << 3);
//接收器使能
USART4->CR1 |= (0x1 << 2);
//串口使能
USART4->CR1 |= (0x1);
}
//发送一个字符
void hal_put_char(const char str)
{
//判断发送数据寄存器是否为空
while(!(USART4->ISR & (0x1 << 7)));
//将发送的内容赋值给寄存器
USART4->TDR = str;
//判断发送是否完成
while(!(USART4->ISR & (0x1 << 6)));
}
//接收一个字符
char hal_get_char()
{
//判断是否接收到数据
while(!(USART4->ISR & (0x1 << 5)));
//将数据从寄存器中读出来
char c = USART4->RDR;
hal_put_char(c);
hal_put_char('\n');
hal_put_char('\r');
return c;
}
//发送一个字符串
void hal_put_string(const char *string)
{
int i = 0;
while(*(string+i) != 0)
{
hal_put_char(*(string+i));
i++;
}
hal_put_char('\n');
hal_get_char('\r');
}
//接收一个字符串
char *hal_get_string()
{
static char str[512];
int i=0;
while(1)
{
str[i] = hal_get_char();
hal_put_char(str[i]);
if(str[i] == '\r')
{
break;
}
i++;
}
str[i+1] = 0;
hal_put_char('\n');
hal_put_char('\r');
return str;
}
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_uart4_init();
char c;
while(1)
{
c = hal_get_char();
hal_put_char(++c);
hal_put_char('\n');
hal_put_char('\r');
}
/*
char *p;
while(1)
{
p = hal_get_string();
hal_put_string(p);
}
*/
return 0;
}
运行结果