Electronic – MSP430 blinking led

msp430

I started using MSP430 Launchpad and as I was examining the code for blinking a led I found something odd. The code is this and is a ready example:

#include  <msp430g2553.h>

 unsigned int i = 0;                         

void main(void)
{
  WDTCTL = WDTPW + WDTHOLD;                 

  P1DIR |= 0x01;                            

  for (;;)                                  
  {

    P1OUT ^= 0x01;                         

    for(i=0; i< 20000; i++);               

  }
}

In the beginning you have to initialize P1DIR so to set the pin in which the led is connected to output. I searched a lot and everywhere is says that the specific register is just to set the direction. So then I deleted a part of the code and the remaining was this one:

#include  <msp430g2553.h>

 unsigned int i = 0;                         

void main(void)
{
  WDTCTL = WDTPW + WDTHOLD;                 

  P1DIR |= 0x01;                            

  for (;;)                                  
  {            

  }
}

Here is the odd part. The led is on!Shouldn't be off? The line of code with P1OUT isn't going to say to MSP if the led is on or off? With only P1DIR nothing should happening. What am I doing wrong?

Best Answer

You can download some code I wrote at:

ZIP file containing an LED Tutorial for MSP430

It covers everything from just turning an LED on, to causing it to evenly (to the eye) diminish and increase in intensity (which requires a geometric progression to achieve.)

In the meantime, what you didn't realize is the power-on value for P1OUT. Try two different statements BEFORE your for(;;) statement:

P1OUT &= ~0x01;

and

P1OUT |= 0x01;

And apply one or the other of the above with your latter code example (the one with the deleted code.) You will see two different behaviors. I'm not certain as I haven't researched it lately, but I suspect the P1OUT values are "random" upon power-on-reset. Regardless, it matters and you need to make sure that P1OUT values are "known" before starting your code.

In the case of your first code example that blinks the LED, the initial value didn't matter since the loop XORs the value over and over. You would never notice if it started as ON or OFF, because it is toggling all the time.