Hitchhiker's Guide to Printf in Mbed 6

Actually, no ITM initialization is needed for STM targets. It seems that it’s sufficient to define a dummy ‘itm_init’ function as below and redirect the Mbed CONSOLE to the SWO:

#include "mbed.h"
#include "SerialWireOutput.h"

DigitalOut  led1(LED1);

extern "C" void itm_init() { }

FileHandle* mbed::mbed_override_console(int)
{
    static SerialWireOutput swo;
    return &swo;
}

int main()
{
    printf("Hello, SWO!\r\n");

    while (true) {
        led1 = !led1;
        printf("blink\r\n");
        ThisThread::sleep_for(500);
    }
}

After adding an ITM device in the mbed_app.json file as below, printf should print over the SWO:

{
    "target_overrides": {
        "*": {
            "target.device_has_add": ["ITM"]
        }
    }
}

A modified STM-Link V 2 probe can be used to program and debug STM custom target boards. The SWO wire shall be connected to the target MCU’s PB_3 pin (but it’s better to check also the related datasheet).

On the NUCLEO boards the SWO wire is available at the pin #6 on the CN4 (SWD) connector. To print over the SWO connect it to the PB_3 pin with a wire.

Printf messages can be then displayed with the STM32CubeProgrammer by switching to the SWV page.

2 Likes