Using the debugger with breakpoints to pause your program and look at the state of registers and variables, however it can also be helpful to let your program run continuously and while logging the state of internal variables. This is where printf
comes in!
printf
can be used send formatted strings to your laptop using the debugger. See this wiki page for a guide on how to write formatted strings and include variables: https://cplusplus.com/reference/cstdio/printf/
There are a few things you need to do to use printf. When you create a new project, make sure to enable any printf features (floating point and integer support are generally most useful, width/precision support is used to round numbers).
To use printf
inside your code, you need to do three things:
<stdio>
and "stm32l432xx.h"
_write
function as shown below
printf
and used to send your string to the debuggerprintf
where you want to log information// Necessary includes for printf to work
#include <stdio.h>
#include "stm32l432xx.h"
// Function used by printf to send characters to the laptop
int _write(int file, char *ptr, int len) {
int i = 0;
for (i = 0; i < len; i++) {
ITM_SendChar((*ptr++));
}
return len;
}
int main(void) {
int i;
for (i = 0; i < 100; i++) {
// printf function call
printf("Hello World %d!\\n", i);
}
do {
i++;
} while (1);
}
you only need to define _write
in one file of your project. It is best practice to create a separate debug.h
and debug.c
file that has the relevant includes and function definitions.
When you are ready to debug your code, start the debugger and look at the debug terminal panel to see the printouts!