Tag Archives: msp430

“volatile” can cost you!

In an earlier post, I mentioned how I am going to get back into embedded progarmmming using the fantastic launchpad from TI.

Well, I got started with a book and various resources online, using the open source msp430 gcc chain (since i don’t have access to a win machine for IAR tools, the only negative thing for the launchpad in my opinion) with my hello world program (blinking leds).

Though there are plenty of blinking led programs using the Timers on the lanchpad, I really wanted to write a simple program without any timers. Below is the sample code I started with:

#include <io.h>
#include <signal.h>

 /* Program toggles Pin 1.6 in MSP430 */

 void delay()
    int i;
   for(i=0;i < 32000;i++);

void main(void)
   // Stop the watchdog timer
  // Set the direction of PIN1.6
   P1DIR = P1DIR | BIT6;
   P1OUT |= BIT6;
   // Toggle Pin 1.6
   for(;;) //forever
       P1OUT ^=BIT6;

The code seems simple enough! The delay function should provide for sufficient delay to see the blinking of the LED. However on running this code, the LED never blinks!

As a beginner in embedded programming, it took me an hour of debugging and searching to come up with this article . The key point is:

An automatic object declared in a function that calls setjmp and whose value is-changed between the call to setjmp and a corresponding call to longjmp

Changing my delay function to use volatile fixes the issue!

void delay()
    volatile int i;
   for(i=0; i< 32000;i++);

You can compare the objdump between the two, using:

You can check out the objdmp using:

msp430-gcc -S -mmcu=msp430x2012 main.c
msp430-as main.s -mmcu=msp430x2012
msp430-objdump -D a.out