串口实验
分析
原理图
通过分析电路图可知: UART4_RX------>PB2 UART4_TX------>PG11
芯片手册
RCC章节
通过RCC_MP_AHB4ENSETR设置GPIOB和GPIOG控制器使能
通过RCC_MP_APB1ENSETR寄存器设置UART4控制器使能
GPIO章节
通过GPIOx_MODER寄存器,设置PB2和PG11引脚为复用功能
通过GPIOB_AFRL寄存器,设置PB2引脚为复用功能UART4_Rx
UART章节
通过以上分析可知,设置寄存器: 1.USART_CR1:设置数据位宽度,以及将相应位进行使能 2.USART_CR2:设置停止位 3.USART_BRR:设置波特率---->设置的采样率有关 4.USART_RDR :设置接收数据寄存器 5.USART_TDR :设置发送数据寄存器 6.USART_ISR:设置状态寄存器 7.USART_PRESC :设置时钟分频器
实现代码
A7核
uart4.h
#ifndef __UART4_H__
#define __UART4_H__
#include "stm32mp1xx_gpio.h"
#include "stm32mp1xx_rcc.h"
#include "stm32mp1xx_uart.h"
void uart4_init();
void put_string(const char* str);
char* get_string();
#endif
uart4.c
#include "uart4.h"
void uart4_init()
{
RCC->MP_APB1ENSETR |=(0x1<<16);
RCC->MP_AHB4ENSETR |=(0x1<<1);
RCC->MP_AHB4ENSETR |=(0x1<<6);
GPIOB->MODER |=(0x1<<5);
GPIOB->MODER &=(~(0x1)<<4);
GPIOG->MODER |=(0x1<<23);
GPIOG->MODER &=(~(0x1)<<22);
GPIOB->AFRL &=(~(0x7<<8));
GPIOB->AFRL |=(0x1<<11);
GPIOG->AFRH &=(~(0x9<<12));
GPIOG->AFRH |=(0x3<<13);
if(USART4->CR1&(0x1<<0))
{
USART4->CR1&=(~(0x1));
}
USART4->CR1&=(~(0x1<<12));
USART4->CR1&=(~(0x1<<28));
USART4->CR1&=(~(0x1<<15));
USART4->CR1&=(~(0x1<<10));
USART4->CR1 |=(0x1<<2);
USART4->CR1 |=(0x1<<3);
USART4->CR2 &=(~(0x3<<12));
USART4->PRESC &=(~(0xf));
USART4->BRR=0x22B;
USART4->CR1 |=0x1;
}
void put_string(const char* str)
{
const char *p=str;
while(*p!='\0')
{
while(!(USART4->ISR&(0x1<<7)));
USART4->TDR=*p;
while(!(USART4->ISR&(0x1<<6)));
p++;
}
}
char buf[32]={0};
char* get_string()
{
buf[0]='\n';
char ch='\0';
int n=1;
while(ch!='\r')
{
while(!(USART4->ISR&(0x1<<5)));
ch = USART4->RDR;
while(!(USART4->ISR&(0x1<<7)));
USART4->TDR=ch;
while(!(USART4->ISR&(0x1<<6)));
buf[n]=ch;
n++;
}
buf[n]='\n';
buf[n+1]='\0';
return buf;
}
main.c
#include "uart4.h"
int main()
{
uart4_init();
while(1)
{
put_string(get_string());
}
return 0;
}
M4核
使用CubMX创建工程 并完成上述分析过程中的寄存器相应位的修改 生成代码,并加入fputc函数
int fputc(int ch,FILE* stream)
{
while(!(huart4.Instance->ISR & (0x1 << 7)));
huart4.Instance->TDR = ch;
if(ch == '\n')
{
while(!(huart4.Instance->ISR & (0x1 << 7)));
huart4.Instance->TDR = '\r';
}
return ch;
}
运行结果
|