1.串口发送单个字符
2.串口发送字符串
uart4.h
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_uart.h"
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
//初始化相关操作
void hal_uart4_init();
//发送一个字符
void hal_put_char(const char str);
//发送一个字符串
void hal_put_string(const char* string);
//接收一个字符
char hal_get_char();
//接收一个字符串
char* hal_get_string(char* arr);
uart4.c
#include "uart4.h"
//初始化相关操作
void hal_uart4_init()
{
//----------RCC章节初始化----------//
//(GPIOB,GPIOG,UART4)
RCC->MP_AHB4ENSETR |= (0x1 << 1);
RCC->MP_AHB4ENSETR |= (0x1 << 6);
RCC->MP_APB1ENSETR |= (0x1 << 16);
//---------GPIO章节初始化----------//
//PB2引脚设置复用功能模式
GPIOB->MODER &= (~(0x3 << 4));
GPIOB->MODER |= (0x2 << 4);
//设置为RX
GPIOB->AFRL &= (~(0xf << 8));
GPIOB->AFRL |= (0x8 << 8);
//PG11引脚设置复用功能模式
GPIOG->MODER &= (~(0x3 << 22));
GPIOG->MODER |= (0x2 << 22);
//设置为TX
GPIOG->AFRH &= (~(0xf << 12));
GPIOG->AFRH |= (0x6 << 12);
//----------UART章节初始化----------//
//设置串口UE = 0
USART4->CR1 &= (~(0x1));
//数据位宽度(1个起始位,8个数据位,n个停止位)
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 28));
//采样率(16倍)
USART4->CR1 &= (~(0x1 << 15));
//无奇偶校验
USART4->CR1 &= (~(0x1 << 10));
//接收器使能
USART4->CR1 |= (0x1 << 2);
//发射器使能
USART4->CR1 |= (0x1 << 3);
//设置1位停止位
USART4->CR2 &= (~(0x3 << 12));
//设置串口不分频
USART4->PRESC &= (~(0xf));
//设置串口波特率为115200
USART4->BRR = 0x22b;
//设置串口使能
USART4->CR1 |= (0x1);
}
//发送一个字符
void hal_put_char(const char str)
{
//判断发送寄存器是否为空
while(!(USART4->ISR & (0x1 << 7)));
//将发送的内容赋值给发送寄存器
USART4->TDR = str;
//判断一帧数据是否发送完成
while(!(USART4->ISR & (0x1 << 6)));
}
//发送一个字符串
void hal_put_string(const char* string)
{
hal_put_char('\n');
while(*string != '\0')
{
//判断发送寄存器是否为空
while(!(USART4->ISR & (0x1 << 7)));
//将发送的内容赋值给发送寄存器
USART4->TDR = *string;
string++;
//判断一帧数据是否发送完成
while(!(USART4->ISR & (0x1 << 6)));
}
hal_put_char('\r');
hal_put_char('\n');
}
/*
//接收一个字符
char hal_get_char()
{
//判断接收数据寄存器中是否有数据
while(!(USART4->ISR & (0x1 << 5)));
//将接收数据寄存器中的数据读取出来
char str = USART4->RDR;
return str;
}
*/
//接收一个字符串
char* hal_get_string(char* arr)
{
//循环进行接收
//当键盘输入回车之后,代表字符串输出完成
char *p = arr;
while(1)
{
while(!(USART4->ISR & (0x1 << 5)));
*p = USART4->RDR;
hal_put_char(*p);
while(!(USART4->ISR & (0x1 << 6)));
if(*p == '\r')
break;
p++;
}
*p = '\0';
return arr;
}
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()
{
char arr[20] = "";
hal_uart4_init(); //初始化
while(1)
{
//hal_put_char(hal_get_char()+1); //单个字符
hal_put_string(hal_get_string(arr)); //字符串
}
return 0;
}
实验现象