ARM DAY6 TDR RDR 发送字符与字符串

#include "uart4.h"

//串口初始化函数
void hal_uart4_init()
{
	//RCC章节初始化
	//1.使能GPIOB组控制器,MP_AHB4ENSETR[1]=1
	RCC->MP_AHB4ENSETR |= (0x1<<1);

	//2.使能GPIOG组控制器,MP_AHB4ENSETR[6]=1
	RCC->MP_AHB4ENSETR |= (0x6<<1);

	//3.使能USART4组控制器,MP_APB1ENSETR[16]=1
	RCC->MP_APB1ENSETR |= (0x1<<16);


	//GPIO章节初始化
	//1.设置PB2引脚为复用功能模式 GPIOB->MODER[5:4]=10 
	GPIOB->MODER |= (0x1<<5);
	GPIOB->MODER &= ~(0x1<<4);
	//2.设置PB2引脚复用功能为UART4_RX GPIOB->AFRL[11:8]=1000 
	GPIOB->AFRL &= ~(0xf<<8);
	GPIOB->AFRL |= (0x1<<11);
		
	//3.设置PG11引脚为复用功能模式 GPIOG->MODER[23:22]=10 
	GPIOG->MODER |= (0x1<<23);
	GPIOG->MODER &= ~(0x1<<22);
	//2.设置PG11引脚复用功能为UART4_TX  GPIOG->AFRH[15:12]=0110
	GPIOG->AFRH &= ~(0xf<<12);
	GPIOG->AFRH |= (0x3<<13);


	//UART4章节初始化

	//1.USART_CR1寄存器初始化
	//CR1[28][12]=00 ------> 设置串口1位起始位,8位数据位
	USART4->CR1 &= ~(0X1<<12);
	USART4->CR1 &= ~(0X1<<28);

	//CR1[15] = 0 ------> 设置串口16倍采样率
	USART4->CR1 &= ~(0X1<<15);
	
	//CR1[10] = 0 ------> 设置串口无奇偶检验位
	USART4->CR1 &= ~(0X1<<10);


	//2.USART_CR2寄存器初始化:设置停止位
	//CR2[13:12]=00 ------> 设置串口1位停止位
	USART4->CR2 &= ~(0X3<<12);
	
	//3.USART_BRR寄存器初始化:设置串口波特率
	//BRR=64000000/115200=0x22b
	USART4->BRR=0x22b;

	//CR1[3] = 1 ------> 设置串口TE位使能
	USART4->CR1 |= (0X1<<3);

	//CR1[2] = 1 ------> 设置串口RE位使能
	USART4->CR1 |= (0X1<<2);

	//CR1[0] = 1 ------> 设置串口UE位使能
	USART4->CR1 |= 0X1;
}

//发送一个字符
void hal_put_char(const char str)
{
	//1.判断发送数据寄存器是否为空
	while( !(USART4->ISR & (0x1<<7)) );
	//2.发送数据
	USART4->TDR=str;
	//3.判断一帧数据是否发送完成
	while( !(USART4->ISR & (0x1<<6)) );
}

//发送一个字符串
void hal_put_string(const char* string)
{
	//1.判断是否为'\0'
	while(*string)
	{
		//2.发送一个字符
		hal_put_char(*string++);
	}
	hal_put_char('\n');
	hal_put_char('\r');
}

//接收一个字符
char hal_get_char()
{
	char e;
	//1.判断接收数据寄存器中,是否接收到数据
	while(!(USART4->ISR & (0x1<<5)));
	//2.接收到数据,才可以读数据
	e=USART4->RDR;
	return e;
}

char buf[128]={0};
//接收一个字符串
char *hal_get_string()
{
	unsigned int i=0;
	for(i=0;i<127;i++)
	{
		buf[i]=hal_get_char();
		hal_put_char(buf[i]);

		//判断键盘'\r'是否按下
		if(buf[i]=='\r')
		{
			break;
		}
	}

	//字符串以'\0'结尾
	buf[i]='\0';
	hal_put_char('\n');
	return buf;	
}



你可能感兴趣的:(arm开发,单片机,stm32)