实现串口收发字符/字符串
uart4.c
#include "uart4.h"
void hal_uart_init()
{
//rcc初始化
//使能CPIOB组控制器
RCC->MP_AHB4ENSETR |= (0x1 << 1);
//使能CPIOG组控制器
RCC->MP_AHB4ENSETR |= (0x1 << 6);
//使能UART4控制器
RCC->MP_APB1ENSETR |= (0x1 << 16);
//gpio
GPIOG->MODER &= (~(0x3 << 4));
GPIOG->MODER |= (0x1 << 5 );
GPIOG->MODER &= (~(0x3 << 22));
GPIOG->MODER |= (0x1 << 23);
GPIOG->AFRL &= (~(0xf << 8));
GPIOG->AFRL |= (0x1 << 11);
GPIOG->AFRH &= (~(0xf << 12));
GPIOG->AFRH |= (0x1 << 13);
GPIOG->AFRH |= (0x1 << 14);
//uart
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 28));
USART4->CR1 &= (~(0x1 << 15));
USART4->CR1 &= (~(0x1 << 10));
USART4->CR1 |= (0x1 << 3);
USART4->CR1 |= (0x1 << 2);
USART4->CR1 |= (0x1);
USART4->CR2 &= (~(0x3 << 12));
USART4->BRR = 0x22B;
USART4->PRESC &= (~(0xf));
}
//输出一个字符
void hal_put_char(const char str)
{
while(!(USART4->ISR & (0x1 << 7)));
USART4->TDR = str;
}
//输出一个字符串
void hal_put_string(const char *str)
{
while(*str!='\0')
{
hal_put_char(*str);
str++;
}
hal_put_char('\r');
hal_put_char('\n');
}
//接收一个字符
char hal_get_char()
{
while(!(USART4->ISR & (0x1 << 5)));
return USART4->RDR;
}
char str[256]="";
//输出一个字符串
char* hal_get_string()
{
int i=0;
while(1)
{
while(!(USART4->ISR & (0x1 << 5)));
if(USART4->RDR == '\r')
{
str[i]='\0';
break;
}
str[i]=USART4->RDR;
//键盘输入时的打印
hal_put_char(str[i]);
i++;
}
hal_put_char('\r');
hal_put_char('\n');
return str;
}
uart4.h
#ifndef __LED_H__
#define __LED_H__
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_uart.h"
//初始化函数
void hal_uart_init();
//发送字符
void hal_put_char(const char str);
//发送字符串
void hal_put_string(const char *string);
//接受字符
char hal_get_char();
//接受字符串
char * hal_get_string();
#endif
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()
{
hal_uart_init();
hal_put_string("put string test success");
while(1)
{
// hal_put_char(hal_get_char()+1);
hal_put_string(hal_get_string());
}
return 0;
}