Debugging issues whe using Mbed Studio on Linux

Just in case someone else faced this same issue recently, I have the following workaround.
I’m using a Nucleo-L476RG and the Mbed OS 6.17.0

I’ve started from the simple blinky example. On the first debug session everything worked fine till the debugger reached the sleep_for line. Here is the blinky standard code (simplified):

#include "mbed.h"

int main()
{
    DigitalOut led(LED1);

    while (true) {
        led = !led;
        ThisThread::sleep_for(500ms); // here the debugging session crashes
    }
}

You actually don’t need to reboot your machine. As far as I could understand, once this crash happens the pyOCD server (the debugging tool server) does not finish as it should. Killing the process associated with the pyOCD allows you to start a new debugging session properly. However, this is not a robust troubleshooting; the new debugging session will fail again on the sleep_for line.

Using the Debug build profile, on build the ‘flag’ MBED_DEBUG is defined. Beyond that, the wait_us function do not crash the debug session, then I suggest the following:

#include "mbed.h"

int main()
{
    DigitalOut led(LED1);
    while (true) {
        led = !led;
#ifdef MBED_DEBUG
        wait_us(1000000);
#else
        ThisTread::sleep_for(1s);
#endif
    }
}

It’s advisable to use sleep_for on non-debug builds, as noted by the mbed_wait_api.h:

/** Waits a number of microseconds.
 *
 *  @param us the whole number of microseconds to wait
 *
 *  @note
 *    This function always spins to get the exact number of microseconds.
 *    This will affect power and multithread performance. Therefore, spinning for
 *    millisecond wait is not recommended, and ThisThread::sleep_for should
 *    be used instead.
 *
 *  @note You may call this function from ISR context, but large delays may
 *    impact system stability - interrupt handlers should take less than
 *    50us.
 */
void wait_us(int us);

Plus: as suggested by bthebaudeau’s comment, another workaround (maybe clever than mine’s) is:

#include "mbed.h"

int main()
{
#ifdef MBED_DEBUG
    HAL_DBGMCU_EnableDBGSleepMode();
#endif

    DigitalOut led(LED1);
    while (true) {
        led = !led;
        ThisThread::sleep_for(500ms);
    }
}