实验1
1. 在键盘输入字母,串口工具显示
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 c;
char *str;
hal_uart_init();
hal_put_string("\n这是UART4实验\n\r");
while(1)
{
#if 0
c = hal_get_char();
hal_put_char((c + 1));
#endif
#if 1
str = hal_get_string();
hal_put_string(str);
#endif
}
return 0;
}
UART.c
#include "uart4.h"
//初始化函数
void hal_uart_init()
{
/*RCC章节初始化*/
//GPIOB和GPIOG使能(第一位和第六位写1)
RCC->MP_AHB4ENSETR |= (0x1 << 1);
RCC->MP_APB4ENSETR |= (0x1 << 6);
//UART4使能
RCC->MP_APB1ENSETR |= (0x1 << 16);
/*GPIO章节初始化*/
GPIOB->MODER &= (~(0x3 << 4));
GPIOB->MODER |= (0x2 << 4);
GPIOB->AFRL &= (~(0xf << 8));
GPIOB->AFRL |= (0x8 << 8);
GPIOG->MODER &= (~(0x3 << 4));
GPIOG->MODER |= (0x2 << 22);
GPIOG->AFRH &= (~(0xf << 8));
GPIOG->AFRH |= (0x6 << 12);
/*UART章节初始化*/
//将CR1[0] UE 设置为0
USART4->CR1 &= (~(0x1 << 0));
//将CR1[28][12] 设置为8位数据位置为00
USART4->CR1 &= (~((0x1 << 12)|(0x1 << 28)));
//将CR1[10] 设置为无奇偶校验位 置为0
USART4->CR1 &= (~(0x1 << 10));
//将CR1[15] 设置波特率为16倍采样率 置为0
USART4->CR1 &= (~(0x1 << 15));
//将CR2[13:12] 设置为1位停止位 置为00
USART4->CR2 &= (~(0x3 << 12));
//将PRESC[3:0] 设置为不分频 置为0000
USART4->PRESC &= ~(0xF << 0);
//将BRR 波特率设置为115200
USART4->BRR = 0x22b;
//使能串口
USART4->CR1 |= (0x1 << 0);
//使能串口接收器
USART4->CR1 |= (0x1 << 2);
//使能串口发送器
USART4->CR1 |= (0x1 << 3);
}
//发送一个字符
void hal_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 hal_put_string(const char *string)
{
//判断是否为'\0',如果是则退出,break
while(*string != '\0')
{
hal_put_char(*string);
string++;
}
}
//接收一个字符
char hal_get_char()
{
char ch;
//1.判断接收寄存器是否有数据可读
while(!(USART4->ISR & (0x1 << 5)));
//2.将接收数据寄存器中内容,赋值给ch
ch = (char)USART4->RDR;
return ch;
}
//接收一个字符串
char buf[50] = {0};
char *hal_get_string()
{
//循环进行接收
unsigned int i;
for(i=0; i<49; i++)
{
buf[i] = hal_get_char();
hal_put_char(buf[i]);
if(buf[i] == '\r')
break;
}
buf[i] = '\0';
hal_put_char('\n');
return buf;
//判断字符是否为'\r',break
}
UART.h
```c
#ifndef __UART4__H__
#define __UART4__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 ```
实验2
- 输入输出字符串