概述
这里写目录标题
- 目标要求
- 代码实现
- uart.h
- uart.c
- main.c
目标要求
1.在键盘输入一个字符,字符+1,并且打印在串口工具上
键盘输入’a’----->串口工具打印’b’
代码实现
uart.h
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_uart.h"
//初始化函数
void uart4_init();
//发送字符
void put_char(const char c);
//接收字符
char get_char();
//发送字符串
void put_string(const char * str);
//接收字符串
char * get_string();
#endif
uart.c
#include "uart4.h"
#include "../common/include/stm32mp1xx_gpio.h"
#include "../common/include/stm32mp1xx_uart.h"
#include "../common/include/stm32mp1xx_rcc.h"
//初始化函数
void uart4_init()
{
//RCC初始化
//使能GPIOB控制器
(RCC->MP_AHB4ENSETR) &=(0x1<<1) ;
//使能GPIOG控制器
(RCC->MP_AHB4ENSETR) &=(0x1<<6) ;
//使能UART4控制器
(RCC->MP_APB1ENSETR) &=(0x1<<16);
//GPIO章节初始化
//PB2--->UART4_Rx
(GPIOB->MODER) &=(~(0x3)<<4);
(GPIOB->MODER) &=(~(0x3)<<22);
(GPIOB->MODER) |= (0x2<<22);
(GPIOB->MODER) |= (0x1<<5);
//PG11------>UART4_Tx
/*(GPIOG->AFRL) &=(~(0xF)<<8);
(GPIOG->AFRL) |= (0x8<<8);
(GPIOG->AFRL) &=(~(0xF)<<12);
(GPIOG->AFRL) |= (0x6<<12);
*/
//UART章节初始化
if(USART4->CR1 & (0x1)<<0)
{
delay_ms(500);
USART4->CR1 &=(~(0x1));
}
//1.串口初始化 8为数据位 无奇偶校验位
USART4->CR1 &= (~(0x1<<28));
USART4->CR1 &= (~(0x1<<12));
USART4->CR1 &= (~(0x1)<<15);
USART4->CR1 &= (~(0x1)<<10);
USART4->CR1 |= ((0x1)<<3);
USART4->CR1 |= ((0x1)<<2);
//2.设置串口一位停止位
USART4->CR2 &= (~(0x3<<12));
//3.设置串口16倍采样率
USART4->CR1 &= (~(0x1<<15));
//4.设置串口不分频
USART4->PRESC &= (~(0xF<<0));
//5.设置串口bps 152000
USART4->BRR &= (~(0xFFFF<<0));
USART4->BRR |= (0x22B<<0);
//6.设置串口发送器使能
USART4->CR1 |= (0x1<<3);
//7.设置串口接收器使能
USART4->CR1 |= (0x1<<2);
//8.设置串口使能
USART4->CR1 |= (0x1<<0);
}
void put_char(const char c)
{
//1.判断发送数据寄存器是否有数据 ISR[7]
//读0:则发送寄存器为满,等待
//读1:则发送寄存器为空,才可以发送下一个字节数据
while(!(USART4->ISR &(0x1<<7)));
//2.将要发送的字符写入发送数据寄存器中
USART4->TDR=c;
//3.判断数据是否发送完成
//读0:发送数据没有完成,需要等待
//读1:发送数据完成,可以发送下一帧
while(!(USART4->ISR &(0x1<<6)));
}
char buf[128] = {0};
char get_char()
{
char c;
//1.判断寄存器是否有数据可读 ISR[5]
//读0:没有数据可读,等待
//读1:有数据可读
while(!(USART4->ISR &(0x1<<5)));
c=(USART4->RDR &(0xFF<<0));
//2.将接收数据寄存器的值读取返回
return c;
}
char * get_string()
{
//1.循环接受
char c;
int i=0;
while(1)
{
c=get_char();
if(c=='r')
break;
buf[i]=c;
i++;
}
//2.当接受一个字符后发送一个字符
//当键盘回车键按下时代表字符串接收结束'r'
buf[i]='r';
buf[i+1]='n';
buf[i+2]='