实现字符串数据收发函数的封装
源代码:
main.c
#include "gpio.h"
#include "uart4.h"
int main()
{
uart4_config();
while (1)
{
// char a=getchar();
// putchar(a+1);
char s[20];
gets(s);
puts(s);
//putchar('\n');
putchar('\r');
}
return 0;
}
uart4.c
#include "uart4.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_uart.h"
#include "stm32mp1xx_rcc.h"
void uart4_config()
{
//使能
RCC->MP_AHB4ENSETR |= (0x1 << 1);
RCC->MP_AHB4ENSETR |= (0x1 << 6);
RCC->MP_APB1ENSETR |= (0x1 << 16);
//PB2管脚复用
GPIOB->MODER &= (~(0x3 << 4));
GPIOB->MODER |= (0x2 << 4);
//PG11管脚复用
GPIOG->MODER &= (~(0x3 << 22));
GPIOG->MODER |= (0x2 << 22);
// PG11 为 UART4_TX
GPIOG->AFRH &= (~(0xF << 12));
GPIOG->AFRH |= (0x6 << 12);
// PB2 为 UART4_RX
GPIOB->AFRH &= (~(0xF << 8));
GPIOB->AFRH |= (0x8 << 8);
//设置串口不使能
USART4->CR1 &= (~0x1);
//设置8位数据位
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 28));
//设置没有校验位
USART4->CR1 &= (~(0x1 << 10));
//设置时钟频率不分频
USART4->PRESC &= (~0xf);
//设置16倍过采样
USART4->CR1 &= (~(0x1 << 15));
//设置1位停止位
USART4->CR2 &= (~(0x3 << 12));
//设置波特率115200
USART4->BRR = 0x22B;
//使能发送器
USART4->CR1 |= (0x1 << 3);
//使能接收器
USART4->CR1 |= (0x1 << 2);
//使能串口
USART4->CR1 |= (0x1 << 0);
}
void putchar(char dat)
{
while (!(USART4->ISR & (0x1 << 7)))
;
USART4->TDR = dat;
//等待传输完成
while (!(USART4->ISR & (0x1 << 6)))
;
}
char getchar()
{
while (!(USART4->ISR & (0x1 << 5)))
;
return USART4->RDR;
}
void puts(char *s)
{
while (1)
{
if (*s == '\0')
break;
putchar(*s);
s++;
}
putchar('\n');
putchar('\r');
}
void gets(char *s)
{
while (1)
{
*s = getchar();
putchar(*s);
if ((*s) == '\r')
break;
s++;
}
*s = '\0';
putchar('\n');
}