这篇测试下串口printf输出。
一、串口硬件部分
1.1、MCU串口端口
1.2、串口连接到仿真器
二、代码
使用cubemx软件配置时钟和串口代码
2.1、配置时钟
stm32c031芯片的外接时钟晶振是48MHz,配置时钟选择外部
生成的代码
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSE;
RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
{
Error_Handler();
}
}
2.2、配置串口
在生成的代码上进行修改
void init_usart(uint32_t baudrate)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
__HAL_RCC_USART2_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**USART2 GPIO Configuration
PA2 ------> USART2_TX
PA3 ------> USART2_RX
*/
GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF1_USART2;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
g_usart2.Instance = USART2;
g_usart2.Init.BaudRate = baudrate;
g_usart2.Init.WordLength = UART_WORDLENGTH_8B;
g_usart2.Init.StopBits = UART_STOPBITS_1;
g_usart2.Init.Parity = UART_PARITY_NONE;
g_usart2.Init.Mode = UART_MODE_TX_RX;
g_usart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
g_usart2.Init.OverSampling = UART_OVERSAMPLING_16;
g_usart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
g_usart2.Init.ClockPrescaler = UART_PRESCALER_DIV1;
g_usart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
HAL_UART_Init(&g_usart2);
}
2.3、添加MicoLIB
添加代码
#if defined (__ICCARM__) || defined (__ARMCC_VERSION)
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#elif defined(__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)
#endif /* __ICCARM__ || __ARMCC_VERSION */
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */
/* e.g. write a character to the USART2 and Loop until the end of transmission */
HAL_UART_Transmit(&g_usart2, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
2.4、main.c
#include "main.h"
void SystemClock_Config(void);
int main(void)
{
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
init_led();
init_usart(115200);
while (1)
{
printf("https://shequ.stmicroelectronics.cn/stm32c031!\r\n");
led4_tog();
HAL_Delay(100);
}
}
三、运行
编译后,下载程序到开发板
串口输出乱码
修改时钟频率,时钟为配置的48M。修改内容如下:
重新编译,下载后,串口输出
串口输出正常。 |
学到了