在IAR Embedded Workbench中实现打印输出

Technical Note

Architectures:

All

Component:

general

Updated:

2023/7/21 7:53

随着嵌入式产品功能越来越强大,嵌入式软件也越来越复杂。调试作为嵌入式软件开发中非常重要的一个环节,帮助工程师找到bug,并修复bug。随着电子技术的飞速发展,调试技术也变得越来越丰富。打印输出作为最早的一种调试方法,用于输出调试信息,至今仍然被广泛使用。

本文主要介绍如何在IAR Embedded Workbench中实现打印输出。

通过printf重定向实现打印输出

在C/C++中,printf可以实现打印输出相关的信息,被广泛用于调试中。在IAR Embedded Workbench中有3种方式实现printf打印输出:

  1. 重定向到MCU外设,比如常用的UART
  2. 利用半主机模式(semihosting)重定向到IAR Embedded Workbench中的Terminal I/O
  3. 利用SWO(Serial Wire Output)重定向到IAR Embedded Workbench中的Terminal I/O

1. 重定向到MCU外设,比如常用的UART

在IAR Embedded Workbench中重定向printf到UART需要提供__write函数的实现重定向到UART。下面是一个简单的__write函数实现重定向到UART示例:

size_t __write(int handle, const unsigned char * buffer, size_t size)
{
/* Sending in normal mode */
if(HAL_OK == HAL_UART_Transmit(&huart2,(uint8_t *)buffer,size,100000))
{
return size;
}
else
{
return _LLIO_ERROR;
}
}

连接好MCU UART到对应的电脑COM口,在串口调试助手工具下面就可以显示通过printf重定向到UART的打印输出:

2. 利用半主机模式(semihosting)重定向到IAR Embedded Workbench中的Terminal I/O

在半主机模式下,printf将重定向到上位机的调试器打印输出:

Project>Options>General Options>Library Configuration>Library low-level interface implementation选项中,选择Semihosted,并选择stdout/stderr选项为Via semihosting:

在调试时,通过View>Terminal I/O打开Terminal I/O窗口显示对应的打印输出:

3. 利用SWO(Serial Wire Output)重定向到IAR Embedded Workbench中的Terminal I/O

Arm Cortex-M提供了基于SWO进行printf打印输出:

Project>Options>General Options>Library Configuration>Library low-level interface implementation选项中,选择Semihosted,并选择stdout/stderr选项为Via SWO:

在调试时,通过View>Terminal I/O打开Terminal I/O窗口显示对应的打印输出:

通过Log断点实现打印输出

在IAR Embedded Workbench中,Log断点提供了一种非常方便的方式来实现打印输出,不需要在用户程序里面添加额外的代码。

在用户程序对应的地方设置Log Breakpoint,然后编辑对应的Log Breakpoint在Message对话框中输入对应的打印信息:

调试运行时,在Debug Log窗口就会输出对应的打印信息:

总结

本文主要介绍了如何在IAR Embedded Workbench中实现打印输出。开发人员可以根据不同情况选择合适的方法实现打印输出。

 

参考文献:

  1. IAR C/C++ Development Guide (Introduction to the runtime environment)
  2. https://pyocd.io/docs/semihosting.html
  3. Advanced Debugging for Cortex-M Microcontrollers
  4. IAR C-SPY® Debugging Guide(semihosting,Log breakpoints)
  5. https://www.iar.com/knowledge/learn/debugging/making-the-best-use-of-the-available-breakpoints/

We do no longer support Internet Explorer. To get the best experience of iar.com, we recommend upgrading to a modern browser such as Chrome or Edge.