声明:
#include "stdio.h"
#define PUTCHAR_PROTOTYPE char putchar (char c)
#define GETCHAR_PROTOTYPE char getchar (void)
void UART1_Init(void);
实现:
void UART1_Init(void)
{
uint16_t uart_div=8000000/9600; //晶振频率/波特率
uint8_t tmp;
CLK->PCKENR1 |= (1<<2);//UART时钟允许
tmp=uart_div;
tmp&=0x0f;
tmp|=(uart_div>>8)&0xf0;
UART1->BRR1=uart_div>>4;
UART1->BRR2=tmp;
UART1->CR2=UART1_CR2_TEN|UART1_CR2_REN;//发送接收使能
UART1->CR1=0;//UART使能
}
PUTCHAR_PROTOTYPE
{
while (!(UART1->SR & UART1_SR_TXE));
UART1->DR = c;
}
GETCHAR_PROTOTYPE
{
while(!(UART1->SR & UART1_SR_RXNE));
return ((uint8_t)UART1->DR);
}
应用举例:
int main(void)
{
int i=0;
UART1_Init();
while(1)
{
printf("i:%d\r\n",i++);
//...delay
}
|
|