Reputation: 129
I'm trying out a tutorial program for the MSP-EXP430G2 to blink the LED using Code Composer Studio. Originally, it had an infinite loop for the blinking:
for(;;)
// This empty for-loop will cause the lines of code within to loop infinitely
{
P1OUT ^= 0x01;
// Toggle P1.0 using exclusive-OR operation (^=)
// P1OUT is another register which holds the status of the LED.
// '1' specifies that it's ON or HIGH, while '0' specifies that it's OFF or LOW
// Since our LED is tied to P1.0, we will toggle the 0 bit of the P1OUT register
for(i=0; i< 20000; i++);
// Delay between LED toggles. This for-loop will run until the condition is met.
//In this case, it will loop until the variable i increments to 20000.
}
}
This was copy and pasted from a tutorial, and it worked as intended. I then wanted to see if I could get it to be a finite loop, so I changed the for loop to:
for (j = 0; j<10; j++)
with j declared earlier in the code. However, the LED doesn't blink anymore, and when I step through the program with the debugger, it now skips the for(i=0; i< 20000; i++);
line completely. This only happens when I set the j<10 condition but not if I set it to j>-1. The same issue happens when I make a decrementing loop from 10 to 0, which makes me think that it only happens when the loop is made finite.
Am I missing something obvious?
Upvotes: 0
Views: 117
Reputation: 8537
The compiler is allowed to optimize away code with no side effects. The inner for
loop where a counter is incremented and not used afterwards is an example of such a code.
To avoid this behavior, introduce side effects in the loop. One way is to declare i
as volatile
. Then the compiler will be forced to write the value of i
back in the memory after each time it changes, and the loop will run the exact times until the condition becomes false.
Alternatively, often the embedded platform or the compiler provides delay()
and / or sleep()
functions. It's a better coding practice to use those instead of busy looping - for one, you'll get more deterministic execution time irrespective of the hardware and MCU speed.
Upvotes: 5