#ifdef __GNUC__ /* With GCC/RAISONANCE, 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__ */ /** * @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 EVAL_COM1 and Loop until the end of transmission */ HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
return ch; }
这样就可以在stm32中使用printf函数输出了(#include "stdio.h")。
CLion便捷设置
每次配置串口时,这样ctrl+c和ctrl+v串口重定向又很繁琐,可以使用CLion的便捷设置。
文件->设置,搜索实时模板,在C/C++一栏添加实时模板
缩写为$printf,描述可不写,然后把重定向函数复制到模板文件
点击下面的定义(define),勾选C
这样以后直接输入命令$printf,就可以生成串口重定向函数了。
中文乱码
转换编码格式,UTF-8—>GBK
重新烧录
中断方式
NVIC 设置
在main.c
定义
1 2 3
/* USER CODE BEGIN PV */ uint8_t RxBuff[10]; /* USER CODE END PV */
主函数中打开接收中断
1 2 3
/* USER CODE BEGIN 2 */ HAL_UART_Receive_IT(&huart1, RxBuff,1); /* USER CODE END 2 */
添加中断回调函数
1 2 3 4 5 6 7 8 9 10
/* USER CODE BEGIN 4 */ voidHAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { if(huart->Instance==USART1) { HAL_UART_Transmit(&huart1,RxBuff,1,1000); HAL_UART_Receive_IT(&huart1,RxBuff,1); } } /* USER CODE END 4 */