代码:uart4.c
#include "uart4.h"void uart4_config()
{//使能GPIO\GPIOG\UART4的外设时钟RCC->MP_AHB4ENSETR |= (0x1<<1);RCC->MP_AHB4ENSETR |= (0x1<<6);RCC->MP_APB1ENSETR |= (0x1<<16);//设置PB2和PG11为管脚复用功能//PB2GPIOB->MODER &= (~(0x3<<4));GPIOB->MODER |= (0x2<<4);//PG11GPIOG->MODER &= (~(0x3<<22));GPIOG->MODER |= (0x2<<22);//设置PG11为UART4_TX功能GPIOG->AFRH &= (~(0xf<<12));GPIOG->AFRH |= (0x6<<12);//设置PB2为UART4_RX功能GPIOB->AFRL &= (~(0xf<<8));GPIOB->AFRL |= (0x8<<8);//设置串口不使能USART4->CR1 &= (~0x1);//设置8位数据位USART4->CR1 &= (~(0x1<<12));USART4->CR1 &= (~(0x1<<28));//设置没有校验位USART4->CR1 &= (-(0x1<<10));//设置时钟频率不分频USART4->CR1 &= (~0xf);//设置16倍过采样USART4->CR1 &= (~(0x1<<15));//设置1位停止位USART4->CR1 &= (-(0x3<<12));//设置波特率为115200USART4->BRR = 0x22B;//使能发送器USART4->CR1 |= (0x1<<3);//使能接收器USART4->CR1 |= (0x1<<2);//使能串口USART4->CR1 |= (0x1<<0);
}
void putchar(char dat)
{//当发送数据寄存器中没有数据时可以发送while(!(USART4->ISR & (0x1<<7))); //当TDR中有数据时阻塞等待没有数据USART4->TDR = dat; //向发送数据寄存器中写入数据//等待传输完成函数结束while(!(USART4->ISR & (0x1<<6)));
}char getchar()
{//当接受数据寄存器中有有效数据时读取while(!(USART4->ISR & (0x1<<5)));//将读取到的数据返回return USART4->RDR;
}//发送字符串
void puts(char *s)
{while(1){if(*s == '\0')break;putchar(*s);s++;}putchar('\n');
}void gets(char *s)
{while(1){if(*s== '\r' )break;*s = getchar();putchar(*s);s++;}*s = '\0';putchar('\n');
}