# Help me on writing a code

Hello

I have a problem coding a program, and i would like to take your help :(

My program is. We have A0 A1 A2 A3 as inputs on the arduino, and they are representing binary, like 1 2 4 8 connected to ground(LOW 0) or 5V (HIGH 1). and I would like to use the pins from 8 to 13 as my LEDs outputs.

I will put LED on the pins, and my equation for the output is A=3*(my binary result) depending on which input is High to represent binary 1 or LOW to represent 0. like if i want the number 4, my binary must be 0010, then A=3*4=12 so LED on pin 12 will Light, if i want LED on output pin 9 to light, my binary set must be 1100 then A=3*3=9. like that

How can i write a code for that program

Thanks

digitalWrite(8 + (digitalRead(A0) && 1) + 2 * (digitalRead(A1) && 1) + 4 * (digitalRead(A2) && 1) + 8 * (digitalRead(A3) && 1), HIGH);

Mind you that gives you 16 possibilities and you have only 6 LEDs.

@Paul__B, you have used “&&” there, the boolean operator. Did you mean “&” the bitwise operator?

Paul__B: digitalWrite(8 + (digitalRead(A0) && 1) + 2 * (digitalRead(A1) && 1) + 4 * (digitalRead(A2) && 1) + 8 * (digitalRead(A3) && 1), HIGH);

Mind you that gives you 16 possibilities and you have only 6 LEDs.

Ignoring the & vs && (while different, both will behave the same in this case) this is abusing the digitalRead() API since it is assuming that digitalRead() is returning 1 or 0 (or actually a true or false) when the API says it returns HIGH or LOW. While it will "work" with the cores currently shipped with the arduino.cc IDE, it is never the less abusing the API by taking advantage of internal implementation knowledge that it shouldn't. It is possible that it could break in the future should that coding implementation change. (consider a simple case where digitalRead() were to change its declaration or use a typed enum) It is also possible that other cores may implement HIGH and LOW with values other than 1 and 0.

I think it is a disservice to show and demonstrate programming practices to less technical users that are unlikely understand or realise that it is using techniques (abusing an API) that are not recommend in general programming.

I.e. for newbies, I prefer to show simple examples that use "best practices" programming techniques.

--- bill

PaulRB: @Paul__B, you have used "&&" there, the boolean operator. Did you mean "&" the bitwise operator?

I did actually. I was in a bit of a hurry, and the Arduino reference was not helpful.

bperrybap: Yada yada ... It is also possible that other cores may implement HIGH and LOW with values other than 1 and 0.

And the earth may be flat.

bperrybap: I.e. for newbies, I prefer to show simple examples that use "best practices" programming techniques.

It was a joke.

Or at least, very tongue-in-cheek, for which this forum fails to offer an icon. :astonished: