示例代码如下:
#include "stm32f10x.h"
#include <stdio.h>
//UART1初始化
void DebugPrintInit(uint32_t ulWantedBaud)
{
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable USART1 clock */
RCC_APB2PeriphClockCmd( RCC_APB2Periph_USART1, ENABLE );
/* Configure USART1 Rx (PA10) as input floating */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init( GPIOA, &GPIO_InitStructure );
/* Configure USART1 Tx (PA9) as alternate function push-pull */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init( GPIOA, &GPIO_InitStructure );
USART_InitStructure.USART_BaudRate = ulWantedBaud;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No ;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init( USART1, &USART_InitStructure );
USART_Cmd( USART1, ENABLE );
}
int UartPutc (int ch)
{
while (!(USART1->SR & USART_FLAG_TXE));
USART1->DR = (ch & 0x1FF);
return (ch);
}
/*
int UartGetc (void)
{
while (!(USART1->SR & USART_FLAG_RXNE));
return ((int)(USART1->DR & 0x1FF));
} */
struct __FILE
{
int handle; // 自定义变量加在后边
//...
};
FILE __stdout;
int fputc(int ch, FILE *f)
{
return (UartPutc(ch));
}
在主函数(main)中调用如下:
DebugPrintInit(9600);
printf("i:%d\r\n",i++);
.....
|
|