Search code examples
cmicrocontrollermsp430texas-instrumentscode-composer

MSP430 Function Call Being Skipped


I am programming an MSP430 microcontroller with the MSP430 LaunchPad Dev Kit and I am running into some problems on this simple code.

#include <msp430.h>

void Delay(void);

#define LED1 BIT0                   //define LED1 as bit 0 (0x00)
#define LED2 BIT6                   //define LED2 as bit 6 (0x40)
#define delayTime 20000             //define iTime as 20000

int main(void)
{
    WDTCTL = WDTPW | WDTHOLD;       //stop watchdog timer
    P1DIR |= (LED1|LED2);           //set P1.0 and P1.6 to output direction (P1.3 is naturally an input)
    P1OUT |= LED1;                  //set P1.0 high so the LEDs will blink alternatively

    while(1)
    {
        Delay();
        P1OUT ^= (LED1|LED2);       //toggle P1.0 using exclusive-OR
    }
}

void Delay(void)
{
    int i = 0;
    while(delayTime > i)
    {
        i++;
    }
}

This code compiles fine, but when debugging the code, the function call 'Delay()' is skipped entirely and the function is never entered. However, when I give the function a return type of 'unsigned int' like this:

unsigned int Delay(void)
{
    int i = 0;
    while(delayTime > i)
    {
        i++;
    }
    return 1;
}

I can call the Delay function in an if statement like the one below and the debugger will enter the function.

if(Delay() == 1)
{
    P1OUT ^= (LED1|LED2);       //toggle P1.0 using exclusive-OR
}

I'm sure there is some simple oversight that I'm making. I can't for the life of me figure out why the debugger is skipping my first void function call. Any wisdom?


Solution

  • swineone has responded with the following correct solution in a comment:

    "Try changing the declaration int i = 0; to volatile int i = 0; in the Delay() function. This tells the optimizer not to touch that variable, and may be the difference between the optimizer optimizing the code away or not."

    Thanks for the help!