day60:ARMday7,串口实现数据收发字符串

uart.h:

#ifndef __UART_H__
#define __UART_H__
#include "stm32mp1xx_uart.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"

void uart4_init();
void putchar(char c);
char getchar();
void puts(char *c);
char* gets();

#endif

uart.c:

#include "uart.h"

void uart4_init()
{
	//设置UART4的RCC时钟使能
	RCC->MP_APB1ENSETR |=  (0x1<<16);

	//设置GPIOB和GPIOG的时钟使能
	RCC->MP_AHB4ENSETR |= (0x1<<1);
	RCC->MP_AHB4ENSETR |= (0x1<<6);
	//设置PB2和PG11功能复用为UART4功能
	GPIOB->MODER &= (~(0x3<<4));
	GPIOB->MODER |= (0x2<<4);
	GPIOB->AFRL &= (~(0xf<<8));
	GPIOB->AFRL |= (0x8<<8);

	GPIOG->MODER &= (~(0x3<<22));
	GPIOG->MODER |= (0x2<<22);
	GPIOG->AFRH &= (~(0xf<<12));
	GPIOG->AFRH |= (0x6<<12);

	//禁用串口
	USART4->CR1 &= ~(0x1);
	//设置8个数据位
	USART4->CR1 &= (~(0x1<<12));
	USART4->CR1 &= (~(0x1<<28));
	//设置停止位
	USART4->CR2 &= (~(0x3<<12));
	//设置16倍采样	
	USART4->CR1 &= (~(0x1<<15));
	//设置波特率
	USART4->BRR = 0x22B;
	//设置1分频
	USART4->PRESC &= (~(0xf));
	//校验位设置为不校验	
	USART4->CR1 &= (~(0x1<<10));
	//发送器使能
	USART4->CR1 |= (0x1<<3);	
	//接收器使能
	USART4->CR1 |= (0x1<<2);		
	//串口使能
	USART4->CR1 |= 0x1;
}

//串口发送一个字符
void putchar(char c)
{
	//判断发送数据寄存器有没有数据,没有数据时可以发送
	while(!(USART4->ISR&(0x1<<7)));
	USART4->TDR=c;//将要发送的数据保存在发送寄存器中
	while(!(USART4->ISR&(0x1<<6)));//数据传输完成,函数结束
}
//串口接收一个字符
char getchar()
{
	//判断是否有数据准备好
	while(!(USART4->ISR&=(0x1<<5)));
	char c=USART4->RDR;
	return c;
}
//串口发送一串字符串
void puts(char *c)
{

	while(*c)
	{
		putchar(*c++);
	}
	putchar('\n');
	putchar('\r');

}
char s[50];
//串口接收一串字符串
char* gets()
{
	unsigned int i;

	for(i=0;i<49;i++)
	{
		s[i]=getchar();
		putchar(s[i]);
		if(s[i]=='\r')
			break;
	}
	s[i]='\0';
	putchar('\n');
	return s;
}

main.c:

#include "uart.h"

int main()
{
	//char c;
	char *p;
	uart4_init();

	while(1)
	{
		//c = getchar();
		//putchar(c+1);
		p=gets();
		puts(p);
	}
	return 0;
}

现象:

day60:ARMday7,串口实现数据收发字符串_第1张图片

你可能感兴趣的:(arm)