1.实验串口收发一个字符
2.实验串口收发一个字符串
头文件:
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_uart.h"
//串口初始化
void uart_init();
//发送一个字符
void uart_put_char(const char str);
//发送一个字符串
void uart_put_string(const char* str);
//接收一个字符
char uart_get_char();
//接收一个字符串
char* uart_get_string();
#endif
源文件:
#include "../include/uart4.h"
//串口初始化
void uart_init()
{
/******RCC章节初始化******/
RCC->MP_AHB4ENSETR |=(0x1<<1);
RCC->MP_AHB4ENSETR |=(0x1<<6);
RCC->MP_APB1ENSETR |=(0x1<<16);
/******GPIO章节初始化*****/
GPIOB->MODER &=(~(0x3<<4));
GPIOB->MODER |=(0x2<<4);
GPIOG->MODER &=(~(0x3<<22));
GPIOG->MODER |=(0x2<<22);
GPIOB->AFRL &=(~(0xf<<8));
GPIOB->AFRL |=(0x8<<8);
GPIOG->AFRH &=(~(0xf<<12));
GPIOG->AFRH |=(0x6<<12);
/******UATR4章节初始化****/
USART4->CR1 &=(~(0x1));
USART4->CR1 &=(~(0x1<<28));
USART4->CR1 &=(~(0x1<<12));
USART4->CR1 &=(~(0x1<<15));
USART4->CR1 &=(~(0x1<<10));
USART4->CR1 |=(0x1<<3);
USART4->CR1 |=(0x1<<2);
USART4->CR2 &=(~(0x3<<12));
USART4->BRR|=0x22B;
USART4->PRESC &=(~(0xf));
USART4->CR1 |=(0x1);
}
//发送一个字符
void uart_put_char(const char str)
{
//1.判断发送数据寄存器是否为空,为空,才可以发送下一个字节
//ISR[7]
//读0:发送数据寄存器满,需要等待
//读1:发送数据寄存器空,才可以发送下一个字节
while(!(USART4->ISR & (0x1<<7)));
//2.将要发送的字符,写到发送数据寄存器中
USART4->TDR = str;
//3.判断发送数据是否完成
while(!(USART4->ISR &(0x1<<6)));
}
//发送一个字符串
void uart_put_string(const char* str)
{
//判断是否为'\0',一个字符一个字符发送
while(!(USART4->ISR & (0x1<<7)));
int i=0;
while(str[i]!='\0')
{
USART4->TDR = str[i];
i++;
}
while(!(USART4->ISR &(0x1<<6)));
}
//接收一个字符
char uart_get_char()
{
char ch;
//1.判断接收数据寄存器是否有数据可读 ISR[5]
while(!(USART4->ISR & (0x1<<5)));
//2.将接收的数据读出来
ch=USART4->RDR;
return ch;
}
//接收一个字符串
char buffer[50] ={0};
char* uart_get_string()
{
//for循环
int i=0;
for(i=0;i<47;i++)
{
buffer[i]=uart_get_char();
if(buffer[i]=='\r')
break;
}
//当键盘的回车键'\r'按下之后,字符串输入完成
//字符串补'\0'
buffer[i+1]='\n';
buffer[i+2]='\0';
return buffer;
}
测试文件:"
#include "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()
{
//串口初始化
//实现串口数据收发
uart_init();
uart_put_string("USART4 test !!!!");
while(1)
{
//uart_put_char(uart_get_char()+1);
uart_put_string(uart_get_string());
}
return 0;
}