本帖最后由 TL-LED 于 2023-9-22 14:01 编辑
这篇测试下ST-LINK串口printf测试。
一、硬件电路
ST-LINK仿真器自带虚拟串口,电路图如下
虚拟串口连接到STM32的PC6和PC7引脚
查看手册,看下PC6和PC7映射的串口
二、程序
2.1、usart.c
#include "usart/usart.h"
UART_HandleTypeDef g_usart6_handle;
int fputc(int ch, FILE *f)
{
while ((USART_UX->ISR & 0X40) == 0);
USART_UX->TDR = (uint8_t)ch;
return ch;
}
void usart_init(uint32_t baudrate)
{
GPIO_InitTypeDef gpio_init_struct;
USART_UX_CLK_ENABLE();
USART_TX_GPIO_CLK_ENABLE();
USART_RX_GPIO_CLK_ENABLE();
gpio_init_struct.Pin = USART_TX_GPIO_PIN;
gpio_init_struct.Mode = GPIO_MODE_AF_PP;
gpio_init_struct.Pull = GPIO_PULLUP;
gpio_init_struct.Speed = GPIO_SPEED_FREQ_HIGH;
gpio_init_struct.Alternate = USART_TX_GPIO_AF;
HAL_GPIO_Init(USART_TX_GPIO_PORT, &gpio_init_struct);
gpio_init_struct.Pin = USART_RX_GPIO_PIN;
gpio_init_struct.Alternate = USART_RX_GPIO_AF;
HAL_GPIO_Init(USART_RX_GPIO_PORT, &gpio_init_struct);
g_usart6_handle.Instance = USART_UX;
g_usart6_handle.Init.BaudRate = baudrate;
g_usart6_handle.Init.WordLength = UART_WORDLENGTH_8B;
g_usart6_handle.Init.StopBits = UART_STOPBITS_1;
g_usart6_handle.Init.Parity = UART_PARITY_NONE;
g_usart6_handle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
g_usart6_handle.Init.Mode = UART_MODE_TX_RX;
HAL_UART_Init(&g_usart6_handle);
}
2.2、usart.h
#ifndef _USART_H
#define _USART_H
#include "stdio.h"
#include "stm32f7xx_hal.h"
#define USART_TX_GPIO_PORT GPIOC
#define USART_TX_GPIO_PIN GPIO_PIN_6
#define USART_TX_GPIO_AF GPIO_AF8_USART6
#define USART_TX_GPIO_CLK_ENABLE() do{ __HAL_RCC_GPIOC_CLK_ENABLE(); }while(0)
#define USART_RX_GPIO_PORT GPIOC
#define USART_RX_GPIO_PIN GPIO_PIN_7
#define USART_RX_GPIO_AF GPIO_AF8_USART6
#define USART_RX_GPIO_CLK_ENABLE() do{ __HAL_RCC_GPIOC_CLK_ENABLE(); }while(0)
#define USART_UX USART6
#define USART_UX_CLK_ENABLE() do{ __HAL_RCC_USART6_CLK_ENABLE(); }while(0)
void usart_init(uint32_t baudrate);
#endif
2.3、main.c
int main(void)
{
MPU_Config(); /* Configure the MPU attributes */
CPU_CACHE_Enable(); /* Enable the CPU Cache */
HAL_Init();
SystemClock_Config(); /* Configure the system clock to 216 MHz */
usart_init(115200);
while(1)
{
HAL_Delay(100);
printf("https://bbs.eeworld.com.cn/\r\n");
}
}
三、运行
3.1、查看串口
3.2、编译后,下载程序到开发板,运行串口