# What is wrong with this MSP430 code?

I am using the MSP-EXP430F5438 evaluation board, which has pushbuttons connected to P2.6 and P2.7 and LEDs connected to P1.0 and P1.1.

I want to make it such that P2.6 sets the LEDs on and P2.7 resets them. To do that, I wrote the following code:

#include  "msp430x54x.h"

int main(void)
{
WDTCTL = WDTPW + WDTHOLD;             // Stop watchdog timer
P1DIR |= BIT0 + BIT1;                 // Set P1.0 and P1.1 to output direction
P2DIR = 0x00;                         // Set the P2 to input direction

P1OUT = 0x00; // Blank all LEDs

while(1)
{
if(P2IN & 0x40) // When P2.6 is pushed
P1OUT = 0x03;
if(P2IN & 0x80) // When P2.7 is pushed
P1OUT = 0x00;
__delay_cycles(100000);
}
}


But it doesn't work properly; sometimes it works erratically (the LEDs turn on when P2.6 is pressed but they don't turn off when P2.7 is pressed), sometimes it doesn't work at all.

Any ideas?

• Check for the switch bounce. – mazurnification Oct 5 '12 at 14:33
• @mazurnification you have a good point; checking the board's schematic, it doesn't provide debouncing for those switches. – Renan Oct 5 '12 at 14:40
• Debouncing is unlikely to be the main problem. Try this: remove the call to delay_cycles() and make sure that the watchdog is not enabled. Then report what you find. – user3624 Oct 5 '12 at 15:22

There are no pullups on P2.6 and P2.7.

The MSP has internal pullup / pulldowns but you have to set them up yourself.

P2REN |= (1<<6) | (1<<7);  // turn on pullups
P2OUT |= (1<<6) | (1<<7);  // set them to pull up


Then the inputs won't float randomly when the switches aren't pressed.

• I can't believe I didn't see that those pins didn't have pullups... that was it! Now it works correctly. Thanks! – Renan Oct 5 '12 at 16:11
• super helpful answer -- I always assume that I have to use my own external pullups and rarely check the datasheet to see if there's something already available that precludes the need for external components. Awesome! – Dave Oct 5 '12 at 20:35

Your code polls the switch pins but then delays. If the switch is pressed and released during the delay time it won't be seen.

Try removing the delay, or using interrupts to catch edges on the switch pins.

• Agreed. Or just hold the button down longer, but offhand I don't know how many seconds a 100000 cycle delay equates to. – Dave Oct 5 '12 at 15:25
• Try toggling an LED with a 100000 cycle delay. If it's visibly flashing, that would be bad – Toby Jaffey Oct 5 '12 at 16:17