串口实验 ..

uart4.h

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

//初始化
void uart4_init();

//发送一个字符
void put_char(const char ch);

//接受一个字符
char get_char();

//发送一个字符串
void put_string(const char *ch);

//接受一个字符串
char *get_string();

#endif

uart4.c

#include "uart4.h"
extern void delay_ms(int ms);
//初始化函数
void uart4_init()
{
	//******RCC章节初始化******
	//RCC使能
	RCC->MP_AHB4ENSETR |= (0x1 << 1);
	RCC->MP_AHB4ENSETR |= (0x1 << 6);
	RCC->MP_APB1ENSETR |= (0x1 << 16);

	//******GPIO章节初始化******
	//PB2引脚设置复用
	GPIOB->MODER &= (~(0x1 << 4));
	GPIOB->MODER |= (0x1 << 5);
	GPIOB->AFRL &= (~(0xf << 8));
	GPIOB->AFRL |= (0x1 << 11);

	//PG11引脚设置复用
	GPIOG->MODER &= (~(0x1 << 22));
	GPIOG->MODER |= (0x1 << 23);
	GPIOG->AFRH &= (~(0xf << 12));
	GPIOG->AFRH |= (0x3 << 13);

	//******UART章节初始化******
	//禁用UE
	if(USART4->CR1 & (0x1<<0))
	{
		delay_ms(500);
		USART4->CR1 &= (~(0x1));
	}
	// 设置数据长度为8位   USART_CR1  
	USART4->CR1 &= (~(0x1 << 12));
	USART4->CR1 &= (~(0x1 << 28));

	USART4->CR1 &= (~(0x1 << 10));
	
	// 停止位1位
	USART4->CR2 &= (~(0x3 << 12));
	// 采样率为16位 
	USART4->CR1 &= (~(0x1 << 15));
	// 设置波特率为115200bps 
	USART4->PRESC &= (~(0xf));
	USART4->BRR |= (0x22B);
	
	// 使能USART的发送或者接收功能 
	USART4->CR1 |= (0x3 << 2);
//	USART4->CR1 |= (0x1 << 2);	
	// 使能USART串口 
	USART4->CR1 |= (0x1);

}

//发送一个字符
void put_char(const char ch)
{
	//判断ISR寄存器是否有数据ISR[7]
	//读0满,读1空
	while(!(USART4->ISR & (0x1 << 7)));
	USART4->TDR = ch;

	//判断发送数据是否完成
	while(!(USART4->ISR & (0x1 << 6)));
}

//接受一个字符
char get_char()
{
	char ch;
	//判断ISR寄存器是否有数据可读ISR[5]
	//读0没有,读1有
	while(!(USART4->ISR & (0x1 << 5)));

	ch = USART4->RDR;

	return ch;
}

//发送一个字符串
void put_string(const char *ch)
{
	const char *p = ch;
	while(*p != '\0')
	{
		while(!(USART4->ISR & (0x1 << 7)));
		USART4->TDR = *p;
		while(!(USART4->ISR & (0x1 << 6)));
		p++;
	}
}

char str[50] = {0};
//接受一个字符串
char *get_string()
{
	str[0] = '\n';
	int i = 1;
	while(1)
	{
		while(!(USART4->ISR & (0x1 << 5)));
		put_char(get_char());
		str[i] = USART4->RDR;
		i++;
		if(USART4->RDR == '\r')
		break;
	}
	str[i++] = '\n';
	str[i] = '\0';

	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(void)
{
	uart4_init();

	while(1)
	{
//		put_char(get_char()+1);
		put_string(get_string());
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值