This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

MSP430FR5969: Question about the use of volatile in the Blink the LED example

Part Number: MSP430FR5969

Tool/software:

All,

I am rather new to embedded programming, but I am familiar with C. I managed to get the simple Blink the LED example to work on my MSP430FR5969 TI Launchpad.

#include <msp430.h>

void main(void)
{
    WDTCTL = WDTPW | WDTHOLD;               // Stop watchdog timer
    PM5CTL0 &= ~LOCKLPM5;                   // Disable the GPIO power-on default high-impedance mode to activate previously configured port settings
    P1DIR |= 0x01;                          // Set P1.0 to output direction

    volatile unsigned int i;                // volatile to prevent optimization
    //unsigned int i;

    for (;;)
    {
        P1OUT ^= 0x01;                      // Toggle P1.0 using exclusive-OR
        i = 10000;                          // SW Delay

        while (i != 0)
        {
            i--;
        }
    }
}

I am a bit curious about the use of the volatile keyword for i. When I tried it without the volatile keyword, the LED would not blink at all, but rather stay ON effectively. Based upon what I've read on several embedded-related websites, the volatile keyword is used for these situations.

  1. Global variables in ISR or multi-threaded applications
  2. Memory-mapped registers

However, i, to my knowledge, does not fit under those situations. So I am kind of confused as to why it is being optimized by the compiler. Is it because it is being reset to 10000 again in each loop iteration?

Thank you,

Andy

  • For further information, I also ran through the CCS debugger. When I kept i as volatile, the code did step into the while loop, causing i to decrement. But when I left the volatile out, it did not even decrement i.

  • Optimizers have this nasty habit of noticing that you don't use a variable for anything after changing it. Then remove that code. Since "i" isn't used outside of that delay loop...

**Attention** This is a public forum