Beware that this post is related to an SDK in maintenance mode
More Info: Consider nRF Connect SDK for new designs
This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

NRF_LOG_INFO issues when formatting strings

Hi, I'm using nRF52840PDK and SDK 14.2.0. I started from the SAADC example and tried to use NRF_LOG_INFO to print some strings through the UART. I have this:

char test[5] = "test";
char data[8] = "data";

...

NRF_LOG_INFO("%c*%X*%X*%s*%s", test[0], test[0], test, test, data);

And the output in the UART is:

<info> app: t*74*2003FF14*DU*Y1Z

The first 3 values are ok because the first character is 't', which hex code is 0x74 and is stored at 0x2003FF14 in memory, but when I try to print the whole string, those weird characters appears. This also happened when I tried to form a string using sprintf and using it in NRF_LOG_INFO.

  • Hi Gustavo,

    Not sure if this will fix it but in general when using %s, strings (char arrays) should be null terminated with "\0".

    /Erik

  • Thanks Erik for your response. Actually when you declare "test" it includes the null terminator '\0'. For this reason the array should be initiated for 5 elements. Also, sprintf includes the null terminator when storing a formatted string in an array. You must be sure that the array is long enough to store the formatted output. I learnt that the hard way: A critical bug found in production.

  • I found a solution. The problem is present when char arrays are declared within the function, this is what I had when post the question (file nRF5_SDK_14.2.0/examples/peripheral/saadc/main.c):


    void saadc_callback(nrf_drv_saadc_evt_t const * p_event)
    {
    
    char test[5] = "test";
    char data[8] = "data";
    
    ...
    
    NRF_LOG_INFO("%c*%X*%X*%s*%s", test[0], test[0], test, test, data);
    
    ...
    
    }

    But it was solved declaring the buffers outside the function, it is, at file level:

    char test[5] = "test";
    char data[8] = "data";
    
    void saadc_callback(nrf_drv_saadc_evt_t const * p_event)
    {
    ...
    
    NRF_LOG_INFO("%c*%X*%X*%s*%s", test[0], test[0], test, test, data);
    ...
    
    }

    In this case, the output of the UART is:

    <info> app: t*74*20000054*test*data

    The difference I see is that the memory location for the variables is in another range (previous: 0x2003FF14, now: 0x20000054).

Related