首先在MX中配置好端口的底层基本配置,可参考我的上一篇文章:
https://blog.youkuaiyun.com/weixin_46498792/article/details/126431885?spm=1001.2014.3001.5501
法一:使用keil为我们提供的标准输入输出,优点:方便简单,缺点:只能实现单一串口。
在main文件中添加#include “stdio.h”头文件,魔法棒中勾选Use Micro LIB
重定义fputc和fgetc函数:
//重定向fputc函数printf
//int fputc(int ch,FILE *f){
// HAL_UART_Transmit(&huart1,(uint8_t *)&ch,1,HAL_MAX_DELAY);
// return ch;
//}
//或:
//重定向fputc函数
int fputc(int ch,FILE *f){
while((USART1->SR&0X40)==0);//循环发送,直到发送完毕
USART1->DR = ch; //把ch通过usart1发送出去
return ch;
}
//重定向fgetc函数 scanf
int fgetc(FILE *f){
uint8_t ch;
HAL_UART_Receive(&huart1,(uint8_t *)&ch,1,HAL_MAX_DELAY);
return ch;
}
main函数测试:
//测试
int main(void)
{/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART1_UART_Init();
MX_USART2_UART_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
printf("test\n");
HAL_Delay(5000);
/* USER C