当前位置:首页 > 单片机 > 单片机
[导读]一、MDK设置在工程的Target中MicroLib二、main函数之前添加如下编译代码:#define COM USART1//串口选择初始化,USART1为串口1,USART2为串口2#ifdef __GNUC__#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)#el

一、MDK设置

在工程的Target中MicroLib



二、main函数之前添加如下编译代码:

#define COM USART1//串口选择初始化,USART1为串口1,USART2为串口2

#ifdef __GNUC__

#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif

PUTCHAR_PROTOTYPE
{
USART_SendData(COM, (uint8_t) ch); //此处用到了 COM宏定义为了 USART1

//注意:这里可以定义printf()使用板载的任意USART(COM1或者COM2均可)

while (USART_GetFlagStatus(COM, USART_FLAG_TC) == RESET)
{}
return ch;
}

三、程序配置

时钟使能

RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA| RCC_APB2Periph_GPIOB,ENABLE);


RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);//串口2时钟初始化
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);//串口1时钟初始化

IO脚配置

void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;

//USART1管脚初始化
//USART1发送TX=PA9管脚初始化

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);
//USART1接收RX=PA10管脚初始化

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);

//USART2管脚初始化

//USART2发送TX=PA2管脚初始化

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//USART2接收RX=PA3管脚初始化
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);

}

串口参数设置

void USART_Configuration(void)
{
USART_InitTypeDef USART_InitStructure;


USART_InitStructure.USART_BaudRate = 115200; // 设置了USART传输的波特率 ;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;// 8位数据 ;
USART_InitStructure.USART_StopBits = USART_StopBits_1; // 在帧结尾传输1个停止位 ;
USART_InitStructure.USART_Parity = USART_Parity_No ; // 奇偶失能 ;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;// RTS和CTS失能 ;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;// 接收发送使能 ;
USART_Init(COM, &USART_InitStructure); // 根据USART_InitStruct中指定的参数初始化外设USART寄存器 ;

USART_Cmd(COM, ENABLE); // 使能USART外设,此处COM为USART1,在宏定义中,可以设置

while(NbrOfDataToTransfer--) //测试用,初始化发送数据,NbrOfDataToTransfer为输出字符串的长度
{
USART_SendData(USART2, TxBuffer[TxCounter++]); // 通过外设USART发送单个数据 ;
while(USART_GetFlagStatus(COM, USART_FLAG_TXE) == RESET); // 检查发送数据寄存器空标志位;
}


}

3、在main中添加

printf("nrSTM32 USART2:%d n",10);

即可实现C库printf函数的正常使用


本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭