1、串口实验一:在键盘输入一个字符,字符进行+1,并在串口中进行打印
2、串口实验二:键盘输入字符串,串口回显字符串
uart4.h:
#ifndef __UART4_H__
#define __UART4_H__
#include "../common/include/stm32mp1xx_uart.h"
#include "../common/include/stm32mp1xx_gpio.h"
#include "../common/include/stm32mp1xx_rcc.h"
//uart4初始化
void hal_uart4_init();
// 发送一个字符
void put_char(const char ch);
// 发送一个字符串
void put_string(const char *str);
// 接收一个字符
char get_char();
// 接收一个字符串
char *get_string();
#endif
uart4.c:
#include "../include/uart4.h"
extern void delay_ms(int ms);
//uart4初始化
void hal_uart4_init()
{
/*******RCC章节初始化*******/
//使能GPIOB和GPIOG组的时钟
RCC->MP_AHB4ENSETR |= (0x1 << 1);
RCC->MP_AHB4ENSETR |= (0x1 << 6);
// 使能UART控制器的时钟
RCC->MP_APB1ENSETR |= (0x1 << 16);
/*******GPIO章节初始化*******/
// 设置PG11为复用模式
GPIOG->MODER &= (~(0x3 << 22));
GPIOG->MODER |= (0x2 << 22);
//设置PB2为复用模式
GPIOB->MODER &= (~(0x3 << 4));
GPIOB->MODER |= (0x2 << 4);
//设置PG11为UART4_TX复用功能
GPIOG->AFRH &= (~(0xf << 12));
GPIOG->AFRH |= (0x6 << 12);
//设置PB2为UART4_RX复用功能
GPIOB->AFRL &= (~(0xf << 8));
GPIOB->AFRL |= (0x8 << 8);
/*******UART章节初始化*******/
//判断UE位是否使能,如果使能将其禁止
if(USART4->CR1 & 0x1){
delay_ms(500);
USART4->CR1 &= ~0x1;
}
//设置UART4传输数据宽度为8位
USART4->CR1 &= (~(0x1 << 28));
USART4->CR1 &= (~(0x1 << 12));
//设置UART4串口16倍采样率
USART4->CR1 &= (~(0x1 << 15));
//设置UART4串口无奇偶校验位
USART4->CR1 &= (~(0x1 << 10));
//设置UART4串口发送寄存器和接收寄存器使能
USART4->CR1 |= (0x3 << 2);
//设置UART4串口1位停止位
USART4->CR2 &= (~(0x3 << 12));
//设置UART4串口不分频
USART4->PRESC &= ~0xf;
//设置UART4串口波特率为115200
USART4->BRR &= ~0xffff;
USART4->BRR |= 0x22b;
//设置UART4串口使能
USART4->CR1 |= 0x1;
}
// 发送一个字符
void put_char(const char ch)
{
while(1){
if(USART4->ISR & (0x1<<7))
break;
}
USART4->TDR = ch;
if(ch=='\n')
put_char('\r');
}
// 发送一个字符串
void put_string(const char *str)
{
while(*str){
if(USART4->ISR & (0x1<<6)){
put_char(*str);
str++;
}
}
put_char('\n');
}
// 接收一个字符
char get_char()
{
char ch;
while (1)
{
if(USART4->ISR & (0x1<<5))
break;
}
for (int i = 0; i < 8;i++){
if(USART4->RDR & (0x1<<i)){
ch |= (0x1 << i);
}else{
ch &= (~(0x1 << i));
}
}
return ch;
}
// 接收一个字符串
char *get_string()
{
static char data[64] = "";
int i;
for (i = 0; i < 63;i++){
data[i] = get_char();
put_char(data[i]);
if(data[i]=='\r')
break;
}
data[i] = '\0';
put_char('\n');
return data;
}
main.c:
#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()
{
hal_uart4_init();
put_string("uasrt testing....\n");
while(1)
{
put_char(get_char() + 1);
//put_string(get_string());
}
return 0;
}
效果图: