简体   繁体   中英

MSP430FR6989 button and led toggle

Working on a school project and I am stuck on my last bit of code. Let's say S1 is held down and the red LED is on. If, in the meanwhile, S2 is pushed, the green LED remains off and the red LED continues to be on. This state persists until S1 is released. Now, S2 has the chance to turn on the green LED. And, likewise, if S2 is held down with the green LED on, S1 is ignored when pushed, until S2 is released.

I am currently stuck in the forever loop. I cannot get my code to do as what is described in the above paragraph. Once both BUT1 and BUT2 are held down both green and red led lights turn off.

#include <msp430fr6989.h>
#define redLED BIT0 // Red LED at P1.0
#define greenLED BIT7 // Green LED at P9.7
#define BUT1 BIT1 // Button S1 at P1.1
#define BUT2 BIT2 // Button S2 at P1.2

void main(void) {

    WDTCTL = WDTPW | WDTHOLD; // Stop the Watchdog timer
    PM5CTL0 &= ~LOCKLPM5; // Enable the GPIO pins


    // Configure and initialize LEDs
    P1DIR |= redLED; // Direct pin as output
    P9DIR |= greenLED; // Direct pin as output
    P1OUT &= ~redLED; // Turn LED Off
    P9OUT &= ~greenLED; // Turn LED Off



    // Configure buttons1
    P1DIR &= ~(BUT1 | BUT2); // Direct pin as input
    P1REN |=  (BUT1 | BUT2); // Enable built-in resistor
    P1OUT |=  (BUT1 | BUT2); // Set resistor as pull-up






    // Polling the button in an infinite loop
    for(;;) {

        if((P1IN & (BUT1|BUT2))==BUT2){
                 P1OUT |= redLED;   // Turn red LED on
        }

        if((P1IN & (BUT1|BUT2))==BUT1){
                 P9OUT |= greenLED;     // Turn green LED on
        }
       if (P1IN & (BUT1 | BUT2) == (BUT1|BUT2))
                   P1OUT &= ~redLED;
                   P9OUT &= ~greenLED;

    }
}

You've got a bit inconsistent with your brackets and braces. Try this for the last section:

if ((P1IN & (BUT1 | BUT2)) == (BUT1|BUT2)) {
    P1OUT &= ~redLED;
    P9OUT &= ~greenLED;
}

Notice the brackets round P1IN & (BUT1 | BUT2) so that it's evaluated first. Not also the braces round the two lines so they are both dependant on the condition, rather than just the first line. Essentially it now matches you first two.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM