工程建立
1、打开stm32cubeIDE,从菜单File->New->STM32project呼出新建工程界面:
2、如下图所示,在Commercial Part Number输入c031c6,在弹出的下拉菜单中选中STM32C031C6T6,然后在Display similar的Board下选中NUCLEO-C031C6。
3、选中开发板后,点击next:
4、选中文件夹,输入工程名称,如下图:
5、点击finish,完成工程创建
串口配置
1、配置usart2为串口输出。
2、参数为如下,配置为115200的波特率
3、保存,并且生成代码,我们看到uart2的初始化配置如下:
/**
* @brief USART2 Initialization Function
* @param None
* @retval None
*/
static void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart2.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
串口重定向
为了实现串口重定向我们插入如下printf重定向代码:
/* USER CODE BEGIN 2 */
/* Output a message on Hyperterminal using printf function */
printf("\n\r UART Printf Example: retarget the C library printf function to the UART\n\r");
printf("** Test finished successfully. ** \n\r");
/* USER CODE END 2 */
/ USER CODE BEGIN 4 /
/**
- @brief Retargets the C library printf function to the USART.
- @param None
- @retval None
/
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(&huart2, (uint8_t )&ch, 1, 0xFFFF);
return ch;
}
/ USER CODE END 4 /
编译后下载。打开串口助手,我们收到如下数据:
【小结】stm32cubeIDE 可以实现图形化配置,并且生成配置代码,用户只要添加少量代码就可以实现所需要的功能。 |