1. 程式人生 > 其它 >使用SWO列印除錯資訊

使用SWO列印除錯資訊

在使用STM32過程中,剛開始經常使用UART作為除錯資訊輸出的通道,之後看到SEGGER RTT的方式搭配JLINK,直接使用SWD除錯口輸出除錯資訊,速度快,效率高但是RTT的方式存在一個問題,產品釋出後,為了防止程式被惡意讀出,除錯口基本會被禁用掉,所以考慮使用SWO的方式作為備選。

SWO框圖如下,涉及到Coretx-M內的ITM、TPIU等

在使用IDE開發時,可直接通過配置IDE使能SWO輸出,程式中不需要額外設定,我的開發環境沒有使用IDE,需要在程式中顯示的使能SWO,

參考https://community.st.com/s/question/0D53W00000IWs2gSAD/how-to-enable-swo-with-stlink-utility-on-stm32f407gdisc1?t=1637668120413

具體程式如下:

void swoInit (uint32_t portMask, uint32_t cpuCoreFreqHz, uint32_t baudrate)
{
uint32_t SWOPrescaler = (cpuCoreFreqHz / baudrate) - 1u ; // baudrate in Hz, note that cpuCoreFreqHz is expected to match the CPU core clock

CoreDebug->DEMCR = CoreDebug_DEMCR_TRCENA_Msk; // Debug Exception and Monitor Control Register (DEMCR): enable trace in core debug
DBGMCU->CR = 0x00000027u ; // DBGMCU_CR : TRACE_IOEN DBG_STANDBY DBG_STOP DBG_SLEEP
TPI->SPPR = 0x00000002u ; // Selected PIN Protocol Register: Select which protocol to use for trace output (2: SWO)
TPI->ACPR = SWOPrescaler ; // Async Clock Prescaler Register: Scale the baud rate of the asynchronous output
ITM->LAR = 0xC5ACCE55u ; // ITM Lock Access Register: C5ACCE55 enables more write access to Control Register 0xE00 :: 0xFFC
ITM->TCR = 0x0001000Du ; // ITM Trace Control Register
ITM->TPR = ITM_TPR_PRIVMASK_Msk ; // ITM Trace Privilege Register: All stimulus ports
ITM->TER = portMask ; // ITM Trace Enable Register: Enabled tracing on stimulus ports. One bit per stimulus port.
DWT->CTRL = 0x400003FEu ; // Data Watchpoint and Trace Register
TPI->FFCR = 0x00000100u ; // Formatter and Flush Control Register

// ITM/SWO works only if enabled from debugger.
// If ITM stimulus 0 is not free, don't try to send data to SWO
if (ITM->PORT [0].u8 == 1)
{
bItmAvailable = 1 ;
}
}

通過實驗發現,單純使用上述程式初始化SWO後,呼叫ITM_SendChar週期傳送字元,使用示波器在SWO引腳上並未測量到任何訊號,

使用命令列JLinkSWOViewerCL -swoattach on -swofreq 4000000 -device xxxx -itmport 0xF可以接收到SWO輸出的資訊,懷疑偵錯程式還是去配置了內部的暫存器

通過邏輯分析儀抓取SWD的訊號,發現在上述命令列期間,偵錯程式去遍歷除錯相關的ROM表,並沒有去配置暫存器

所以猜測STM32的debug模組預設是不上電電的,在通過命令列請求其上電之後SWO的訊號就可以在引腳上測量到了。

stay hungry,stay foolish