1

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.

  • Other than with the ! operator? – Ignacio Vazquez-Abrams May 5 '16 at 10:41
  • 1
    Commenting instead of replying because you asked for code, but this could be done in hardware. If you wire in a PNP transistor to switch the second LED, it will free up the second DIO pin. – KJP May 5 '16 at 16:06
  • Can I ask why you don't want to use if and else? Is this just hypothetical fun? – Zach Mierzejewski May 5 '16 at 16:37
  • @KJP if you add an x amount of shift registers, you'll free up an (x*8)-6 amount of in/outputs? ;D – Paul May 16 '16 at 19:53
7

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
  • You can also use ! with int values. – Kroltan May 5 '16 at 14:26
  • 1
    You don't say.... – Majenko May 5 '16 at 14:27
  • 2
    Wasn'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. – Kroltan May 5 '16 at 15:03
  • in C, bool and int are interchangeable. – rkosegi May 5 '16 at 16:36
  • 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 '16 at 10:39
0

You could do it with only a switch/case statement. You do not even need to de-bounce the switch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.