I was wondering how to write a code that would do this, WITHOUT using IF and ELSE: when the button is pressed, one LED is on and the other one is off, but when the button is not pressed, the LED that was on turns off and the other one turns on.
2 Answers
Just use the return value of digitalRead
(which is 1 or 0) as the input to digitalWrite
:
int btnVal = digitalRead(3);
digitalWrite(4, btnVal); // On when button is HIGH
digitalWrite(5, 1 - btnVal); // Off when button is HIGH
Or using boolean instead:
bool btnVal = digitalRead(3);
digitalWrite(4, btnVal); // On when button is HIGH
digitalWrite(5, !btnVal); // Off when button is HIGH
-
-
1
-
2Wasn't necessarily telling that to you, but leaving that comment as a note to the OP, which seems to be a beginner, or to any future reader.– KroltanMay 5, 2016 at 15:03
-
-
1@EdgarBonet It may be called a _Bool but it's still an integer:
Boolean values still behave as integers, can be stored in integer variables, and used anywhere integers would be valid, including in indexing, arithmetic, parsing, and formatting. This approach ("Boolean values are just integers") has been retained in all later versions of C.
– Majenko ♦May 16, 2016 at 10:39
You could do it with only a switch
/case
statement. You do not even need to de-bounce the switch.
!
operator?if
andelse
? Is this just hypothetical fun?