How do I write a program to wait (delay) until one out of two buttons pressed? I have written a program to wait until a single button is pressed. It's working fine. However, if I extend it to second button it's not working. Pls help on this.
while (digitalRead(bt_Select) == HIGH) {}
-- working.while (digitalRead(bt_Select) == HIGH || digitalRead(bt_Reject) == HIGH) {}
-- Not working.
Complete code:
const int bt_Select = 2;
const int bt_Reject = 3;
void setup() {
Serial.begin(9600);
pinMode(bt_Select, INPUT_PULLUP);
pinMode(bt_Reject, INPUT_PULLUP);
}
void loop() {
Serial.println("Pl input:");
while (digitalRead(bt_Select) == HIGH {} // This is the line I change
if (digitalRead(bt_Select) == LOW) {
Serial.println("Select Button pressed:");
delay(250);
Serial.println("");
}
if (digitalRead(bt_Reject) == LOW) {
Serial.println("Reject Button pressed:");
delay(250);
Serial.println("");
}
}
1 Answer 1
while (digitalRead(bt_Select)==HIGH||digitalRead(bt_Reject)==HIGH){}
should be
while (digitalRead(bt_Select)==HIGH&&digitalRead(bt_Reject)==HIGH){}
The first loop would break only if you press both buttons at once. I believe you are trying to break if either button is pressed.
-
yes I try to break if either button is pressed.Ak Rikas– Ak Rikas2021年03月03日 15:36:07 +00:00Commented Mar 3, 2021 at 15:36
-
Thank you it's working.. 5nAk Rikas– Ak Rikas2021年03月03日 15:37:38 +00:00Commented Mar 3, 2021 at 15:37
-
however i confused how it could works?!*Ak Rikas– Ak Rikas2021年03月03日 15:39:09 +00:00Commented Mar 3, 2021 at 15:39
-
@AkRikas Your code stays in the while loop when one of the buttons is
HIGH
and the other code when both areHIGH
. Does this answer your question?Python Schlange– Python Schlange2021年03月03日 17:43:04 +00:00Commented Mar 3, 2021 at 17:43 -
@Ak Rikas - The condition in the while loop is a continue condition, not a break condition. You want the loop to break when one OR the other is pressed. That means it should continue when both are not pressed. In order to test that both are not pressed you need to use AND.Delta_G– Delta_G2024年06月03日 18:25:28 +00:00Commented Jun 3, 2024 at 18:25