uart串口实验
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()
{
while(1)
{
// put_char(get_char()+1);
put_string(get_string());
}
return 0;
}
uart4.c
#include "uart4.h"
//1.初始化函数
void uart4_init()
{
/********RCC章节********/
RCC->MP_APB4ENSETR |= (0x1 << 1);
RCC->MP_APB4ENSETR |= (0x1 << 6);
RCC->MP_APB1ENSETR |= (0x1 << 16);
/********GPIO章节********/
GPIOB->MODER &= (~(0x3 <<4));
GPIOB->MODER |= (0x1 <<5);
GPIOG->MODER &= (~(0x3 << 22));
GPIOG->MODER |= (0x1 << 23);
GPIOB->AFRL &= (~(0xf << 8));
GPIOB->AFRL |= (0x1 << 11);
GPIOG->AFRL &= (~(0xf << 12));
GPIOG->AFRL |= (0x3 <<13);
/********GPIO章节********/
if(USART4->CR1 & (0X1 << 0))//将UE为禁止
{
USART4->CR1 |= (0x1 << 0);
}
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 28));
USART4->CR1 &= (~(0x1 << 10));//串口初始化 8位数据位 无奇偶校验位
USART4->CR2 &= (~(0x3 << 12));//设置串口1位停止位
USART4->CR1 &= (~(0x1 << 15));//设置串口16倍采样率
USART4->PRESC &= (~(0xf << 0));//设置串口不分频
USART4->BRR &= (~(0xffff << 0));//设置波特率为115200
USART4->BRR |= (0x22b);//设置串口发送器使能
USART4->CR1 |= (0x1 <<3);//设置串口接收器使能
USART4->CR1 |= (0x1 <<2);//设置串口使能
USART4->CR1 |= (0x1 <<0);//设置UE
}
//2.发送一个字符
void put_char(const char str)
{
while(!(USART4->ISR & (0x1 << 7)));//判断发送数据寄存器是否有数据
USART4->TDR &= (~(0xff << 0));
USART4->TDR = str;//将要发送的字符,写入到发送数据寄存器中
while(!(USART4->ISR & (0x1 <<6)));//判断发送数据是否完成
}
//3.发送一个字符串
void put_string(const char* str)
{
//判断是否为'\0'
while(*str!='\0')
{
put_char(*str);
str++;
}
//一个一个字符的进行发送
put_char('\n');
put_char('\r');
}
//4.接收一个字符
char get_char()
{
char ch;
while(!(USART4->ISR & (0x1 << 5)));//判断接受寄存器是否有数据可读
ch = USART4->RDR;//将接受寄存器中的内容读出来
return ch;
}
char buffer[50] = {0};
//5.接收一个字符串
char* get_string()
{
//1.循环进行接收
//2.循环实现:接受一个字符之后,发送一个字符
while(!(USART4->ISR & (0x1 <<5)));
int i=0;
while((buffer[i] = get_char())!='\r')
{
put_char(buffer[i]);
i++;
}
put_char('\n');
put_char('\r');
buffer[i+1]='\0';
return buffer;
}
uart4.h
#ifndef __URAT4_H__
#define __URAT4_H__
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_uart.h"
#include "stm32mp1xx_rcc.h"
//1.初始化函数
void uart4_init();
//2.发送一个字符
void put_char(const char str);
//3.发送一个字符串
void put_string();
//3.接收一个字符
char get_char();
//4.接收一个字符
char get_char();
//5.接收一个字符串
char* get_string();
#endif