stm32 printf用法
时间: 2023-11-18 11:53:50 浏览: 38
在STM32中,可以使用标准库函数printf来进行串口输出。使用printf需要先初始化串口,然后在代码中包含stdio.h头文件。下面是一个简单的例子:
```c
#include "stdio.h"
#include "stm32f4xx.h"
void USART2_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStruct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2);
USART_InitStruct.USART_BaudRate = 115200;
USART_InitStruct.USART_WordLength = USART_WordLength_8b; USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_Init(USART2, &USART_InitStruct);
USART_Cmd(USART2, ENABLE);
}
int main(void)
{
USART2_Init();
printf("Hello World!\n");
while (1)
{
// do something
}
}
```
在上面的例子中,我们初始化了USART2,并使用printf输出了一条字符串。需要注意的是,printf输出的内容会被缓存,直到缓存区满或者遇到换行符才会被发送出去。如果需要立即发送,可以使用fflush(stdout)函数。