STM32重定向printf()和scanf()到UART

开发环境:

Ubuntu16.04 + SW4STM32 + STM32CubeMX + STM32F103C8T6

 

说明:scanf()函数有个bug,那就是当我们想要获取一个int时,如果输入了数字,就会导致scanf()永远获取不到用户的输入,除非重启mcu。

 

STM32CubeMX配置:

203753_yKyB_1041082.png

main.c中添加:

/* With GCC, small printf (option LD Linker->Libraries->Small printf
   set to 'Yes') calls __io_putchar() */
#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
{
  /* Place your implementation of fputc here */
  /* e.g. write a character to the USART2 and Loop until the end of transmission */
  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);
//  return ch;
}

复制SW4STM32安装目录中的syscalls.c到自己的project,并按如下修改"__read()"函数。

 	for (DataIdx = 0; DataIdx < len; DataIdx++)
 	{
-		*ptr++ = __io_getchar();
+		*ptr = __io_getchar();
+		if (*ptr++ == '\n') break;
 	}
  
-return len;
+    return ++DataIdx;
}

 

转载于:https://my.oschina.net/igiantpanda/blog/1611419

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值