3.串C1实验(A7核/M4核)
.h
#ifndef __CHUANKOU__
#define __CHUANKOU__
//1.初始化函数
void uart4_init();
//2.发送一个字符
void put_char(const char str);
//3.接收一个字符
char get_char();
//4.接收一个字符串
void get_string();
//发送一个字符串
void put_string();
#endif
.c
#include "chuankou.h"
#include "stm32mp1xx_uart.h"
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"
//1.初始化函数
void uart4_init()
{
/********RCC章节初始化********/
//1.使能GPIOB控制器
RCC->MP_AHB4ENSETR |= (0x1 << 1);
//2.使能GPIOG控制器
RCC->MP_AHB4ENSETR |= (0x1 << 6);
//3.使能UART4控制器
RCC->MP_APB1ENSETR |= (0x1 << 16);
/********GPIO章节初始化*******/
//PB2----->UART4_RX
GPIOB->MODER &= (~(0x3 << 4));
GPIOB->MODER |= (0x1 << 5); //设置为复用功能模式
//PG11---->UART4_TX
GPIOB->MODER &= (~(0x3 << 22));
GPIOB->MODER |= (0x1 << 23); //设置为复用功能模式
GPIOB->AFRL &= (~(0xf << 8));
GPIOB->AFRL |= (0x1 << 11);
GPIOG->AFRH &= (~(0xf << 12));
GPIOG->AFRH |= (0x6 << 12);
/********UART章节初始化*******/
if(USART4->CR1 & (0x1 << 0))
{
//将UE禁止
USART4->CR1 &= (~(0x1 << 0));
}
//1.串口初始化 8位数据 无奇偶校验位
USART4->CR1 &= (~(0x1 << 28));
USART4->CR1 &= (~(0x1 << 12));
USART4->CR1 &= (~(0x1 << 10)); //设置无奇偶校验位
//2.设置串口一位停止位
USART4->CR2 &= (~(0x3 << 12));
//3.设置串口16倍采样率
USART4->CR1 &= (~(0x1 << 15));
//4.设置串口不分频
USART4->PRESC &= (~(0xf << 0));
//5.设置串口波特率为115200
USART4->BRR &= (~(0xffff << 0));
USART4->BRR |= (0x22b << 0);
//6.设置串口发送器使能
USART4->CR1 |= (0x1 << 3);
//7.设置串口接收器使能
USART4->CR1 |= (0x1 << 2);
//8.设置串口使能
USART4->CR1 |= (0x1 << 0);
}
//2.发送一个字符
void put_char(const char str)
{
//1.判断发送数据寄存器是否有数据 ISR[7]
//读0: 发送数据寄存器满,需要等待
//读1: 发送寄存器为空,才可以发送下一字节数据
while(!(USART4->ISR & (0x1 << 7)));
//2.将要发送的字符,写入到发送数据寄存器中
USART4->TDR = str;
//3.判断发送数据是否发送完成
//读0: 发送数据没有完成,需要等待
//读1: 发送数据完成,可以发送下一帧数据
while(!(USART4->ISR & (0x1 << 6)));
}
//3.接收一个字符
char get_char()
{
char ch;
//1.判断接收寄存器是否有数据可读 ISR[5]
//读0: 没有数据可读, 需要等待
//读1: 有数据可读
while(!(USART4->ISR & (0x1 << 5)));
//将接收寄存器里的内容读出来
ch = USART4->RDR;
return ch;
}
char buf[50] = "";
//4.接收一个字符串
void get_string()
{
int i = 0;
//while(!(USART4->ISR & (0x1 << 5)));
while((buf[i] = get_char()) != '\r')
{
put_char(buf[i]);
i++;
}
buf[i] = '\0';
}
//发送一个字符串
void put_string()
{
//while(!(USART4->ISR & (0x1 << 7)));
int i = 0;
while(buf[i] != '\0')
{
put_char(buf[i]);
i++;
}
put_char('\n');
put_char('\r');
}
main.c
lude "chuankou.h"
lude "stm32mp1xx_uart.h"
lude "stm32mp1xx_gpio.h"
lude "stm32mp1xx_rcc.h"
rn void printf(const char *fmt, ...);
delay_ms(int ms)
int i,j;
for(i = 0; i < ms;i++)
for (j = 0; j < 1800; j++);
main()
uart4_init(); //初始化串口
while(1)
{
put_char(get_char() + 1);
//get_string();
//put_string();
}
return 0;