STM32F103串口配置,并且使用printf进行打印

首先要配置串口时钟:

    // USART1 clock enable 
    RCC_APB2PeriphClockCmd(
    RCC_APB2Periph_USART1 |
    RCC_APB2Periph_GPIOA |
    RCC_APB2Periph_AFIO, ENABLE);

然后再配置端口,在配置串口,再使能即可。

 

void USART1_Init(void)
{
/// config the gpio
    GPIO_InitTypeDef GPIO_InitStructure;
    
    /* PA9 USART1_Tx */ 
    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); 
    /* PA10 USART1_Rx  */ 
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; //配置接收端口
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;// 
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    
//
    
    USART_InitTypeDef USART_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;//
    
    //config clock
    USART_ClockInitTypeDef   USART_ClockInitStructure;
    
    USART_ClockInitStructure.USART_Clock = USART_Clock_Disable;     
    USART_ClockInitStructure.USART_CPOL = USART_CPOL_Low;      

    USART_ClockInitStructure.USART_CPHA = USART_CPHA_2Edge;      
    USART_ClockInitStructure.USART_LastBit = USART_LastBit_Disable; 
    
    USART_ClockInit(USART1, &USART_ClockInitStructure);

    /* Configure USART1 */ 
    USART_Init(USART1, &USART_InitStructure);//
    
    /* Enable the USART1 */ 
    USART_Cmd(USART1, ENABLE);//??1? 
    
}

串口配置完毕,为了使得能够使用 printf 进行打印,需要进行重定向:

在 stm32f10x_usart.c 中添加如下代码:

int fputc(int ch, FILE *f)
{
 /* 给USART写一个字符 */
 USART_SendData(USART1, (uint8_t) ch);
 
 /* 循环直到发送完成 */
 while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
 
 return ch;
}

在 stm32f10x_usart.h 中添加stdio.h头文件,然后,添加声明 int fputc(int ch, FILE *f);

最后,在设置里面 Target 下面 勾选“Use MicroLIB” 就可以了。

 

posted @   荒原狼的技术博客  阅读(85)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示