在一个学校项目上工作,我被困在最后的代码中。假设S1处于按下状态并且红色LED亮起。如果同时按下S2,则绿色LED保持熄灭,而红色LED继续点亮。此状态持续到释放S1为止。现在,S2有机会打开绿色LED。同样,如果在绿色LED点亮的情况下按住S2,则按下S1时将忽略S1,直到释放S2。
我目前陷入了永远的循环。我无法按照上一段中的描述执行代码。一旦同时按住BUT1和BUT2,绿色和红色LED指示灯都会熄灭。
#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;
}
}
最佳答案
您的括号和花括号有点不一致。在最后一节中尝试以下操作:
if ((P1IN & (BUT1 | BUT2)) == (BUT1|BUT2)) {
P1OUT &= ~redLED;
P9OUT &= ~greenLED;
}
注意括号
P1IN & (BUT1 | BUT2)
,以便首先对其进行评估。大括号不仅围绕两行,因此它们都取决于条件,而不仅仅是第一行。从本质上讲,它现在与您的前两个匹配。关于c - MSP430FR6989按钮和LED拨动开关,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54372866/