Global Variables Not working When Used in CY_ISR - KBA224452

Author: JobinT_31        Version: **

 

Question:

Global variables used across the main function and a CY_ISR are not working. Why?

 

Answer:

At higher levels of optimization, global variables can get optimized out by the compiler. This happens when the variable is modified only by functions like CY_ISR. Use the volatile keyword to inform the compiler not to optimize out similar variables, as shown in the following code snippet from a Cypress Developer Community member, Bob Marlowe.

 

Example Code:

 

uint8 FlagToCheck = FALSE;

 

CY_ISR(SecHandler)

{

      SecTimer_Stop();

      SecTimer_ReadStatusRegister();

     

      FlagToCheck = TRUE;

}

 

int main(void)

{

    CyGlobalIntEnable; /* Enable global interrupts. */

    Timeout_StartEx(SecHandler);

    SecTimer_Start();

    LED_Write(LEDOFF);

    /* Place your initialization/startup code here (e.g. MyInst_Start()) */

 

    while(!FlagToCheck)

    {

    }

      LED_Write(LEDON);

 

      while(TRUE)

      {

            CyDelay(100);

      }

}

 

In this example, if optimization in the compiler is set to higher levels, LED_Write(LEDON) will never get executed; however, with the volatile keyword added, LED_Write(LEDON) will get executed.