[back to index]

Am I running with a SWD debugger attached?

Sometimes you need to be able to tell whether your Pico is running with a SWD debugger attached or not.

Why?

One very concrete example revolves around OpenOCD and the Pico's dormant mode.
The RP2040 can be configured to switch off all clocks and oscillators, entering the so called "dormant mode", saving power. Works great.
There is, however, a problem: OpenOCD trips up really bad if the Pico suddenly disappears. It will not recover on waking-up from dormant. And your only option is to reset everything and start debugging from the beginning.

Why? (again)

As a work-around, you could produce different binaries, one for active debugging that does not make use of dormant mode, and another for deployment that does.
But that complicates deployment and one particular scenario I kept running into was that I was debugging the code at the lab bench and once satisfied wanted to take it straight into the field for a prototype run.
Having to juggle multiple build variants is nothing short of a big foot gun.

How?

So instead we'd want our program to be able to tell whether OpenOCD (the SWD debugger) is attached. We could then use or not use dormant mode.

If you read the RP2040 datasheet carefully you will see that it allows access to some of the SWD features. In particular, have a look at SYSCFG and DBGFORCE.
While it seems that we cannot read the SWD commands coming in from OpenOCD (those go straight to debug core of the chip), we can observe the response! Look carefully at PROC0_SWDO.

By periodically checking whether the value of PROC0_SWDO has changed we can tell whether there's a debugger attached to our program.

This is what Picoro does in check_debugger_attached().