本帖最后由 慕容雪花 于 2024-2-5 11:37 编辑
本次来体验一下UART模块在STM32CubeIDE中的使用,以及如何开启printf打印调试信息。
查看开发板手册,PA9和PA10是默认的USART1收发引脚。
在CubeIDE中分配相关引脚功能:
查看GPIO设置:
设置USART1工作模式和具体参数:
点击保存,自动生成代码。在主函数中:
/* USER CODE BEGIN 0 */
uint8_t uart1Buffer[] = "Hello EEWORLD!\n";
/* USER CODE END 0 */
然后调用USART1发送函数即可:
MX_USART1_UART_Init();
HAL_UART_Transmit(&huart1, uart1Buffer, strlen(uart1Buffer),HAL_MAX_DELAY );
接下来将开发使用printf打印功能:
/* USER CODE BEGIN Includes */
#include <string.h>
#include <stdio.h>
/* USER CODE END Includes */
然后添加如下代码:
/* USER CODE BEGIN 4 */
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#define GETCHAR_PROTOTYPE int __io_getchar(FILE *f)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#define GETCHAR_PROTOTYPE int fgetc(FILE *f)
#endif /* __GNUC__ */
PUTCHAR_PROTOTYPE
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
GETCHAR_PROTOTYPE
{
uint8_t ch = 0;
HAL_UART_Receive(&huart1,(uint8_t *)&ch, 1, 0xFFFF);
if (ch == '\r')
{
__io_putchar('\r');
ch = '\n';
}
return __io_putchar(ch);
}
/* USER CODE END 4 */
在上一篇帖子呼吸灯的代码中加入printf打印函数:
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
static uint16_t dcycle_pulse = 0;
//htim3.Init.Period = 999
while(dcycle_pulse <htim3.Init.Period){
__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_2, dcycle_pulse);
dcycle_pulse += 50;
printf("\nLight Phase, Current DutyCycle = %u", dcycle_pulse*100/htim3.Init.Period);
HAL_Delay(100);
}
while(dcycle_pulse > 0){
__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_2, dcycle_pulse);
dcycle_pulse -= 50;
printf("\nDim Phase, Current DutyCycle = %u", dcycle_pulse*100/htim3.Init.Period);
HAL_Delay(100);
}
}
实物效果:
串口调试助手sscom32_trg8ZU3Ax7