我有两个按钮和五个LEDS接线。在电路中,订单是按钮,五个LED和按钮。 LED从左到右(从第一个按钮后开始)的顺序为红色,绿色,蓝色,绿色和红色。我使用蓝色(中间)LED来区分左侧和右侧。当按下左按钮时,其相应的绿色按钮打开,当释放按钮时,红色按钮亮起。右侧也具有相同的功能。所以我想要做的是当按下两个按钮时,绿色灯保持关闭,蓝色灯亮起。但是,当按下两个按钮时,两个绿灯都亮起,蓝灯亮起。编程错误的电路问题?这是我的代码:
//Using Arduino UNO
int switchL = 0; //Left button
int switchR = 0; //Right button
void setup() { //LED from left to right
pinMode(3, OUTPUT); //Red
pinMode(4, OUTPUT); //Green
pinMode(5, OUTPUT); //Blue
pinMode(6, OUTPUT); //Green
pinMode(7, OUTPUT); //Red
Serial.begin(9600);
}
void loop() {
switchL = digitalRead(2);
switchR = digitalRead(8);
if (switchL == HIGH) {
digitalWrite(4, HIGH);
digitalWrite(3, LOW);
} else {
digitalWrite(4, LOW);
digitalWrite(3, HIGH);
}
if (switchR == HIGH) {
digitalWrite(6, HIGH);
digitalWrite(7, LOW);
} else {
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
}
if (switchL == HIGH && switchR == HIGH){
digitalWrite(5, HIGH);
if (digitalRead(5) == HIGH) {
digitalWrite(4, LOW);
digitalWrite(3, LOW);
digitalWrite(7, LOW);
digitalWrite(6, LOW);
} else {
digitalWrite(5, LOW);
}
}
}
答案 0 :(得分:3)
如果您绘制I / O地图会更容易:
switchL switchR | lR lG mB rG rR
0 0 | 1 0 0 0 1
0 1 | 1 0 0 1 0
1 0 | 0 1 0 0 1
1 1 | 0 0 1 0 0
只是将输出写为输入函数:
digitalWrite(3, !switchL );
digitalWrite(4, switchL && !switchR);
digitalWrite(5, switchL && switchR);
digitalWrite(6, !switchL && switchR);
digitalWrite(7, !switchR);
如果您希望继续使用嵌套IF
,则必须始终牢记每个输出都是两个输入的函数。
答案 1 :(得分:0)
我对你正在使用的功能有一个模糊的理解,但是你的答案让我解决了我的问题。我需要的只是在ifs
的两个中添加另一个条件。
if (switchL == HIGH && switchR == LOW) { //When the left button is pressed but the right button is not
digitalWrite(4, HIGH);
digitalWrite(3, LOW);
} else {
digitalWrite(4, LOW);
digitalWrite(3, HIGH);
}
if (switchR == HIGH && switchL == LOW) { //When the right button is pressed but the left button is not
digitalWrite(6, HIGH);
digitalWrite(7, LOW);
} else {
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
}
答案 2 :(得分:0)
你试图过度思考它。首先,在您的第二次if
测试中,您正在设置D5
HIGH
,然后立即测试它是HIGH
。它不能是其他任何内容,因此最终else
中的if
永远不会被操作。
我要做的就是将你的棘手位(双按钮测试)移到代码的顶部,然后测试上面测试的else
内的其他每个按钮。现在读起来比以前更难。这是代码:
void loop() {
switchL = digitalRead(2);
switchR = digitalRead(8);
// first test if both buttons are pressed
if (switchL == HIGH && switchR == HIGH){
digitalWrite(5, HIGH);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
} else {
// now that's out the way, we test for everything else as a whole here
// first test switchL
if (switchL == HIGH) {
digitalWrite(4, HIGH);
digitalWrite(3, LOW);
} else {
digitalWrite(4, LOW);
digitalWrite(3, HIGH);
} // end if switchL
// then test switchR
if (switchR == HIGH) {
digitalWrite(6, HIGH);
digitalWrite(7, LOW);
} else {
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
} //end if switchR
} //end else of both high
}