关于ITM的介绍参见:https://blog.csdn.net/hanchaoman/article/details/102494914
Debug (printf) Viewer可以通过ITM0输出printf内容,通过以下步骤可以打开显示串口输出。
1.将ITM端口寄存器定义添加到源代码中。同时在源代码中添加一个写入ITM Port 0寄存器的fputc函数。 fputc函数允许printf输出消息。
#include "stdio.h"
#define ITM_Port8(n) (*((volatile unsigned char *)(0xE0000000+4*n)))
#define ITM_Port16(n) (*((volatile unsigned short*)(0xE0000000+4*n)))
#define ITM_Port32(n) (*((volatile unsigned long *)(0xE0000000+4*n)))
#define DEMCR (*((volatile unsigned long *)(0xE000EDFC)))
#define TRCENA 0x01000000
struct __FILE { int handle; /* Add whatever you need here */ };
FILE __stdout;
FILE __stdin;
int fputc(int ch, FILE *f) {
if (DEMCR & TRCENA) {
while (ITM_Port32(0) == 0);
ITM_Port8(0) = ch;
}
return(ch);
}
2.打开 View - Serial Windows - Debug (printf) Viewer window.
3.启动debug模式,全速运行,就可以查看printf函数的输出了。
注意:官方文档有说需要打开ITM0,关闭其他通道,但我建立的工程是CM3内核,没有配置这部分,依然能够观察到输出。下图分别是官方截图和我的配置。
另外,建立一个仅用来调试的工程,keil5默认没有启动文件,不像keil3会自动添加,或者是STM32有现成的startup.s文件,需要在manage run页面添加,如下图所示。
参考了这篇文章的解决方法:https://blog.csdn.net/qq_45745192/article/details/104979678