Basic code refresh sesh

So EEEnthusiast from YouTube wrote this pretty nifty code that cycles through all the outputs generated from using a 4:16 demultiplexer. I modified it a bit to quadruple the the output potential and it works great :slight_smile: No worries there, I only want to understand this very neat and concise code so that I can hopefully re-use the tips and tricks within when I need to write my own specialized code.

Anyway, I highlighted a portion of code below and I was hoping someone on here could help explain what it is doing

int Outputs[] = {4,5,6,7,8,9};
void setup()
{
pinMode (Outputs[0], OUTPUT);
pinMode (Outputs[1], OUTPUT);
pinMode (Outputs[2], OUTPUT);
pinMode (Outputs[3], OUTPUT);
pinMode (Outputs[4], OUTPUT);
pinMode (Outputs[5], OUTPUT);
}
void loop()
{
for (byte binary =0;binary<=63; binary++)
{
BinaryOut(binary);
delay(20);
}
}
[color=yellow]void BinaryOut(byte number)
{
for (int i =0;i<6;i++)               
{
if (bitRead(number, i)==1){
digitalWrite(Outputs[i], HIGH);
}else{
digitalWrite(Outputs[i], LOW);
}
}[/color]
}

I gather that the variable “i” must be the output pin representation but what is "if(bitRead(number,i)==1) saying exactly?

bitRead is a macro that lets you look at the individual bits of a byte. number is the byte you're looking at, i is which bit to look at. All it is saying is, "if the i'th bit of number is 1."

When in doubt, RTFM:

http://www.arduino.cc/en/Reference/BitRead

Ah ok, thank you! very useful that is…

Of course

{
  if (bitRead(number, i)==1){
    digitalWrite(Outputs[i], HIGH);
  }else{
    digitalWrite(Outputs[i], LOW);
}

can be simplified to:

{
    digitalWrite(Outputs[i], bitRead(number, i));
}

Per the documentation, only the first bunch of johnwasser's code is legitimate.

In reality, the second bunch of johnwasser's code works fine.

[Explanation: The API docs only refer to using the opaque constants LOW and HIGH in digitalWrite. While 1 and 0 work just fine, the API docs don't support this usage.]

vaj4088: Per the documentation, only the first bunch of johnwasser's code is legitimate. In reality, the second bunch of johnwasser's code works fine. [Explanation: The API docs only refer to using the opaque constants LOW and HIGH in digitalWrite. While 1 and 0 work just fine, the API docs don't support this usage.]

Unfortunately its true, however we can still keep a single call, while keeping it simple. The conditional operator can sometimes help make intentions clearer.

digitalWrite(Outputs[ i ], bitRead(number, i) ? HIGH : LOW );