初始化
/******rcc章节初始化********/ |
//1.使能gpiob组控制器 |
RCC->MP_AHB4ENSETR |=(0X1<<1); |
//2.使能gpiog组控制器 |
RCC->MP_AHB4ENSETR |=(0x1<<6); |
//3.使能uart4组寄存器 |
RCC->MP_APB1ENSETR |=(0X1<<16); |
/******gpio章节初始化********/ |
//1.GPIO引脚为PB2和PG11设置为复用功能模式 |
GPIOB->MODER &=~(0X3<<4);//先清零 |
GPIOB->MODER |=(0X1<<5); //再置1 |
GPIOG->MODER &=~(0X3<<22);//先清零 |
GPIOG->MODER |=(0X1<<23); //再置1 |
|
//2.设置PB2引脚的复用功能为UART4_RX |
GPIOB->AFRL &=~(0XF<<8);//先清零 |
GPIOB->AFRL |=(0X1<<11);//再置1 |
|
//3.设置PG11引脚的复用功能为UART4_TX |
GPIOG->AFRH &=~(0XF<<12);//先清零 |
GPIOG->AFRH |=(0X3<<13);//再置1 |
|
/******uart章节初始化********/ |
//很多都是ue=0才能设置,所以串口先设置为0 |
USART4->CR1 &=~(0X1); |
//1.设置8位数据位 |
USART4->CR1 &=~(0X1<<28); |
USART4->CR1 &=~(0X1<<12); |
//2.设置16倍采样率 |
USART4->CR1 &=~(0X1<<15); |
//3.设置无校验位 |
USART4->CR1 &=~(0X1<<10); |
//4.设置发送位使能 |
USART4->CR1 |=(0X1<<3); |
//5.设置接收位使能 |
USART4->CR1 |=(0X1<<2); |
//6.设置停止位 |
USART4->CR2 &=~(0X3<<12); |
//7.设置分频器 |
USART4->PRESC &=~(0XF); |
//8.设置波特率 |
USART4->BRR &=~(0xffff); |
USART4->BRR |=0x22b; |
//9.设置串口使能 |
USART4->CR1 |=(0X1); |
|
|
功能函数
// 发送一个字符
void hal_put_char(const char str)
{
while(!(USART4->ISR&(0X1<<7)));
USART4->TDR=str;
while(!(USART4->ISR&(0X1<<6)));
}
// 发送字符串
void hal_put_string(const char *s)
{
while(*s)
{
hal_put_char(*s);
s++;
}
hal_put_char('\r');
hal_put_char('\n');
}
// 接收字符
char hal_get_str()
{
char a;
while(!(USART4->ISR&(0x1<<5)));
a=USART4->RDR;
return a;
}
// 接收字符串
void hal_get_string()
{
int i=0;
char s[100];
while(1)
{
s[i]=hal_get_str();
if(s[i]=='\r')
{
break;
}
hal_put_char(s[i]);
i++;
}
s[i]='\0';
hal_put_char('\r');
hal_put_char('\n');
hal_put_string(s);
}
实验现象:
字符
字符串