stm32串口3printf
时间: 2023-09-03 19:12:15 浏览: 64
要在STM32中使用串口3进行printf输出,需要先配置好串口3的参数,包括波特率、数据位、校验位、停止位等。以下是一个示例代码:
```
#include "stm32f10x.h"
#include <stdio.h>
#define USART3_DR_Base 0x40004804
void USART3_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOB, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = 115200;
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(USART3, &USART_InitStructure);
USART_Cmd(USART3, ENABLE);
}
int fputc(int ch, FILE *f)
{
USART_SendData(USART3, (uint8_t) ch);
while (USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET);
return ch;
}
int main(void)
{
USART3_Config();
printf("Hello, world!\r\n");
while(1);
return 0;
}
```
在这个示例代码中,我们首先配置了GPIOB的第10位和第11位,将其分别作为USART3的TX和RX引脚。然后,我们初始化了USART3的参数,设置波特率为115200,数据位为8位,停止位为1位,校验位为无校验位,不使用硬件流控制,同时开启接收和发送功能。在fputc函数中,我们使用USART_SendData函数向USART3发送一个字符,然后使用USART_GetFlagStatus函数等待发送完成,最后返回发送的字符。
在main函数中,我们先调用USART3_Config函数进行串口3的初始化,然后使用printf函数输出"Hello, world!",最后进入一个死循环。
阅读全文
相关推荐














