cotex-A7核UART总线实验
1. 键盘输入一个字符‘a’,串口工具显示‘b’
2. 键盘输入一个字符串"nihao",串口工具显示“nihao”
uart.h
#ifndef __UART4_H__
#define __UART4_H__#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_uart.h"//RCC/GPIO/UART4章节初始化
void hal_uart4_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"
extern void delay_ms(int ms);
//RCC/GPIO/UART4章节初始化void hal_uart4_init()
{
//RCC章节初始化://1. 使能GPIOB组控制器,MP_AHB4ENSETR[1] = 1//2. 使能GPIOG组控制器,MP_AHB4ENSETR[6] = 1//3. 使能UART4组控制器,MP_APB1ENSETR[16] = 1RCC->MP_AHB4ENSETR |= (0x1<<1); //GPIOB使能RCC->MP_AHB4ENSETR |= (0x1<<6); //GPIOG使能RCC->MP_APB1ENSETR |= (0x1<<16); //UART4使能//GPIO章节初始化: //1.设置PB2引脚为复用功能 MODER[5:4] = 10//2.设置PB2复用功能为UART4_RX, AFRL[11:8]=1000 GPIOB->MODER &= (~(0x3<<4)) ; //复用GPIOB->MODER |= (0x1<<5);GPIOB->AFRL &= (~(0xf<<8));GPIOB->AFRL |= (0x1<<11);//1.设置PG11引脚为复用功能 MODER[23:22] = 10 //2.设置PG11复用功能为UART4_TX.AFRH[15:12]=0110GPIOG->MODER &= (~(0x3<<22));GPIOG->MODER |= (0X1<<23);GPIOG->AFRH &= (~(0xf<<12));GPIOG->AFRH |= (0x3<<13);//UART4章节初始化:8N1 115200 使能//0.设置UE=0, CR1[1] = 0if(USART4->CR1 & (0x1)){delay_ms(1000);USART4->CR1 &= (~0x1);}//1.设置UART4串口1位起始位,8位数据位 CR1[28][12] = 00USART4->CR1 &= (~(0x1<<28));USART4->CR1 &= (~(0x1<<12));//2.设置UART4串口没有校验位 CR1[10] = 0USART4->CR1 &= (~(0x1<<10));//3.设置UART4串口1位停止位 CR2[13:12] = 00USART4->CR2 &= (~(0x3<<12));//4.设置UART4串口16倍采样率 CR1[15] = 0USART4->CR1 &= (~(0x1<<15));//5.设置UART4串口不分频 PRESC[3:0] = 0000USART4->PRESC &= (~0xF);//6.设置UART4串口波特率为115200, BRR = 0x22BUSART4->BRR |= 0x22B;//7.设置UART4串口发送器使能 CR1[3] = 1USART4->CR1 |= (0x1<<3);//8.设置UART4串口接收器使能 CR1[2] =1USART4->CR1 |= (0x1<<2);//9.设置UART4串口使能 CR1[0] = 1USART4->CR1 |= (0x1);}void hal_put_char(const char str) //发送一个字符
{//1.判断发送数据寄存器是否为空 ISR[7]//读0:发送数据寄存器满,需要等待//读1:发送数据寄存器不满,可以发送数据while(!(USART4->ISR & (0x1<<7)));//2.将要发送的数据,赋值给发送数据寄存器中USART4->TDR = str;//3.判断一帧数据是否发送完成 ISR[6] = 1while(!(USART4->ISR & (0x1<<6)));
}void hal_put_string(const char* string) //发送一个字符串
{//判断是否为'\0',字符串结束标志//一个一个字符进行发送while(*string){hal_put_char(*string++);}hal_put_char('\n'); //换行hal_put_char('\r'); //回到行首
}char hal_get_char() //接收一个字符
{//判断接收数据寄存器中,是否接收到数据 ISR[5]=1,接收到数据,可以读while(!(USART4->ISR & (0x1<<5)));//将接收数据寄存器中内容,读出来return USART4->RDR;
}char buf[50]={0};
char* hal_get_string() //接收一个字符串
{int i;for(i=0;i<49;i++){buf[i]=hal_get_char(); //接收一个字符hal_put_char(buf[i]); //发送一个字符,回显到串口工具if(buf[i] == '\r') //当enter按键按下时{break;}}buf[i] = '\0';hal_put_char('\n');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_uart4_init(); //初始化while(1){//hal_put_char(hal_get_char()+1);hal_put_string(hal_get_string());}return 0;
}
运行结果1:
运行结果2: