Sunday, 12 May 2024

How to implement printf in Stm32 Arm Cortex-M3/4/7 Microcontrollers

Using printf in STM32 ARM Cortex-M3/M4/M7 microcontrollers requires setting up a few things before you can start printing out messages. Firstly, you need to configure the ITM (Instrumentaton Trace Macrocell) unit to send its FIFO buffer content through the SWO (Serial Wire Output) pin of the SWD (Serial Wire Debug) Interface. This can be done by the follwoing code:


//Debug Exception and Monitor Control Register base address
#define DEMCR        *((volatile uint32_t*) 0xE000EDFCU )

/* ITM register addresses */
#define ITM_STIMULUS_PORT0    *((volatile uint32_t*) 0xE0000000 )
#define ITM_TRACE_EN          *((volatile uint32_t*) 0xE0000E00 )

void ITM_SendChar(uint8_t ch)
{

//Enable TRCENA
DEMCR |= ( 1 << 24);

//enable stimulus port 0
ITM_TRACE_EN |= ( 1 << 0);

// read FIFO status in bit [0]:
while(!(ITM_STIMULUS_PORT0 & 1));

//Write to ITM stimulus port0
ITM_STIMULUS_PORT0 = ch;

}

And by changing the write function in the syscalls.c source file as follows:

__attribute__((weak)) int _write(int file, char *ptr, int len)

{

(void)file;

int DataIdx;


for (DataIdx = 0; DataIdx < len; DataIdx++)

{

//__io_putchar(*ptr++);

ITM_SendChar(*ptr++);

}

return len;

}


In the STM32cubeide the SWV(Serial Wire Viewer) will then receive the printf statements and

display it in the console. In the SWV ITM Data Console, set the ITM Stimulus Port to '0',

and before running the application press on 'start trace'. As can be seen on the following

picture.













With these steps in place, you can easily utilize printf for debugging and communication purposes in your STM32 ARM Cortex-M3/M4/M7 projects.


Written By: Musaab Taha

No comments:

Post a Comment