实验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/GRCC->MP_AHB4ENSETR |= (0X1 << 1);RCC->MP_AHB4ENSETR |= (0X1 << 6);//使能UART4RCC->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;
}
运行结果