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).

CleanShot 2024-10-02 at 23.56.59@2x.png

To use printf inside your code, you need to do three things:

  1. include <stdio> and "stm32l432xx.h"
  2. define the _write function as shown below
    1. this function is called by printf and used to send your string to the debugger
  3. call printf 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!

CleanShot 2024-10-03 at 00.10.27@2x.png