HWD32F407-HAL_串口

串口基本配置如下:

/*Usage:
 * UART_HandleTypeDef huart = {0};
 * huart.Instance = USART1;
 * uart_base_init(GPIOB, GPIO_PIN_14, GPIO_AF4_USART1, GPIOB, GPIO_PIN_15, GPIO_AF4_USART1, &huart);
 */
void uart_base_init(GPIO_TypeDef *tx_port, uint16_t tx_pin, uint32_t tx_af, GPIO_TypeDef *rx_port, uint16_t rx_pin, uint32_t rx_af, UART_HandleTypeDef *huart)
{
    //e.g.:__HAL_RCC_USART1_CLK_ENABLE();
    rcc_uartx_clk_enable(huart->Instance); 
    
    //e.g.:__HAL_RCC_GPIOA_CLK_ENABLE();
    rcc_gpiox_clk_enable(tx_port); 
    rcc_gpiox_clk_enable(rx_port);
    
    GPIO_InitTypeDef GPIO_InitStruct = {
        .Mode = GPIO_MODE_AF_PP,
        .Pull = GPIO_NOPULL,
        .Speed = GPIO_SPEED_FREQ_VERY_HIGH
    };
    GPIO_InitStruct.Pin = tx_pin;
    GPIO_InitStruct.Alternate = tx_af; 
    HAL_GPIO_Init(tx_port, &GPIO_InitStruct);
    
    GPIO_InitStruct.Pin = rx_pin;
    GPIO_InitStruct.Alternate = rx_af;
    HAL_GPIO_Init(rx_port, &GPIO_InitStruct);

    huart->Init.BaudRate               = 115200;
    huart->Init.WordLength             = UART_WORDLENGTH_8B;
    huart->Init.StopBits               = UART_STOPBITS_1;
    huart->Init.Parity                 = UART_PARITY_NONE;
    huart->Init.Mode                   = UART_MODE_TX_RX;
    huart->Init.HwFlowCtl              = UART_HWCONTROL_NONE;
    huart->Init.OverSampling           = UART_OVERSAMPLING_16;
    huart->Init.OneBitSampling         = UART_ONE_BIT_SAMPLE_DISABLE;
    huart->AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
    
    if (HAL_UART_Init(huart3) != HAL_OK)
    {
        Error_Handler();
    }
}
HAL_串口基本配置

从器件的数据手册上可以查到哪些GPIO可以当串口使用。

 

#ifndef __PRINTF_H
#define __PRINTF_H

#include "main.h"
#include <stdio.h>

extern UART_HandleTypeDef *g_huart_print;


#endif
printf.h
#include "printf.h"

UART_HandleTypeDef *g_huart_print = NULL;;

#include <stdio.h>
#ifdef __GNUC__
/* With GCC, small printf (option LD Linker->Libraries->Small printf
   set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
PUTCHAR_PROTOTYPE
{
    if(g_huart_print){
        /* Place your implementation of fputc here */
        /* e.g. write a character to the EVAL_COM1 and Loop until the end of transmission */
        HAL_UART_Transmit(g_huart_print, (uint8_t *)&ch, 1, 0xFFFF);
    }
  return ch;
}
printf.c

在Keil工程中勾选“Use MicroLIB”后,可以输出printf("%s\r\n", "test")类似的代码,但需要自己实现PUTCHAR_PROTOTYPE,实现方式如上。

 

void main(void)
{
    UART_HandleTypeDef huart = {0};
    huart.Instance = USART1;

    uart_base_init(GPIOB, GPIO_PIN_14, GPIO_AF4_USART1, GPIOB, GPIO_PIN_15, GPIO_AF4_USART1, &huart);

    g_huart_print = &huart;
    printf("test\r\n");
}
HAL_串口printf示例

当要在软件工程中使用printf时,完整例程如上。

 

posted on 2026-03-30 10:49  LiveWithACat  阅读(1)  评论(0)    收藏  举报