This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

code execution problem (nrf 51)

I have some very basic code that does not appear to be executing correctly.

There are two versions of code that I would think should have the same result. They do not, and I am trying to figure out why.

Option A:

volatile uint8_t in_pole_flag = 1;    
in_pole_flag = 1;
if(in_pole_flag == 0)    //  <=========== difference point
{
    init_and_loop_funct();
} 

Option B:

volatile uint8_t in_pole_flag = 1;    
in_pole_flag = 0;
if(false)    //  <=========== difference point
{
    init_and_loop_funct();
}

Running the "init_and_loop_funct()" function results in the chip running in a high current mode (many modules initialized and running), while continuing without running the function results in a low current idle mode. Option "A" results in the "init_and_loop_funct()" function executing, while option "B" does not. Why do these two code segments result in different execution?

I would very much like to toggle the execution of the "init_and_loop_funct()" function with a flag, but the above behavior is making this impossible. Any help would be greatly appreciated.

  • As the code is now, option A would not result in the "init_and_loop_funct()" function executing. Are you 100% sure that you are not setting in_pole_flag to 0 somewhere else? or if init_and_loop_funct() is called somewhere else?

  • I agree with Sigurd. Your declaring in_pole_flag as volatile might imply that you think some other thread or peripheral could be writing 1 to it between the time you set it to 0 and the time you check its value. (Or you could be just telling the compiler to not to optimize out any code. You could read the assembly code to make sure it meets your expectations.)

  • Nothing else is modifying in_pole_flag. I added the volatile declaration to try to make sure that optimization was not doing something unexpected, but the result is the same with or without the volatile declaration.

    I have done some more testing: This strange behavior only occurs when the soft-device is loaded and running. Also, the code runs normally if I comment out the body of all of the "APP_ERROR_CHECK()" related functions.

    There appear to be function calls in some of the nordic .h files I have included, and it looks like some of those are skipped depending on how functions are called in code. It looks like explicitly making the if-statement argument false caused the compiler to optimize out some of the .h includes, causing the weird Nordic .h function calls to not happen.

Related