# stear 4 digital pins as binary group in an easy way

Is there an easy way to stear 4 digital pins as a binary increasing number.

I need something like
digitalWrite(D0,LOW); digitalWrite(D1,LOW); digitalWrite(D2,LOW); digitalWrite(D3,LOW);
until
digitalWrite(D0,HIGH); digitalWrite(D1,HIGH); digitalWrite(D2,HIGH); digitalWrite(D3,HIGH);

so from 0,0,0,0
til 1,1,1,1

Idealy I run a funtion like stear(15)
where the function void stear (bin number)

triggers
digitalWrite(D0,number[0]); digitalWrite(D1,number[1]); digitalWrite(D2,number[2]) digitalWrite(D3,number[3]);

where number[0]) is the first bit of the binary ....

Do want to do this in a few microseconds, or what? Do you want to do this only once?

Paul

maybe something like this :

``````for( int i = 0; i < 16 ; i++ ) {
digitalWrite ( D0, i & 8 ) ;
digitalWrite ( D1, i & 4 ) ;
digitalWrite ( D2, i & 2 ) ;
digitalWrite ( D3, i & 1 ) ;
}
``````

Thanks, I still do not understand it completely but I do understand what you try to do. Something like the modulo operator but in binary mode.

I think this is what I need but I need to play a bit with it. Thanks a lot.

This would make the code a lot easier and avoid to use 16 case statements or 32, 48, 64, when I want to extend my analog read project.

so close. I get this when i print it
0: 0,0,0,0
1: 0,0,0,1
2: 0,0,2,0
3: 0,0,2,1
4: 0,4,0,0
5: 0,4,0,1
6: 0,4,2,0
7: 0,4,2,1
8: 8,0,0,0
9: 8,0,0,1
10: 8,0,2,0
11: 8,0,2,1
12: 8,4,0,0
13: 8,4,0,1
14: 8,4,2,0
15: 8,4,2,1
all 0 are 0's
all other number should become 1

I did it like this :
Serial.print(i);Serial.print(": ");Serial.print((i & 8) /8);Serial.print(",");Serial.print((i & 4)/4);Serial.print(",");Serial.print((i & 2)/2);Serial.print(",");Serial.print(i & 1);Serial.println("");

I have the feeling that your proposal works for digital write. Everything above 0 is High I think but still need to test it.

Thanks

You are correct. For digitalWrite important is zero or non-zero. Zero is LOW. Non-zero is HIGH.

Maybe this makes it clearer

``````for( int i = 0; i < 16 ; i++ ) {
digitalWrite ( D0, i & 8 ? HIGH : LOW ) ;
digitalWrite ( D1, i & 4 ? HIGH : LOW ) ;
digitalWrite ( D2, i & 2 ? HIGH : LOW ) ;
digitalWrite ( D3, i & 1 ? HIGH : LOW ) ;
}
``````

but should have the same effect or even

``````for( int i = 0; i < 16 ; i++ ) {
digitalWrite ( D0, i & 0b1000 ? HIGH : LOW ) ;
digitalWrite ( D1, i & 0b0100 ? HIGH : LOW ) ;
digitalWrite ( D2, i & 0b0010 ? HIGH : LOW ) ;
digitalWrite ( D3, i & 0b0001 ? HIGH : LOW ) ;
}
``````

Reading example digitalWrite ( D1, i & 0b0100 ? HIGH : LOW ) means that if bit 2 in variable ‘i’ is set to 1, then pin D1 is HIGH otherwise it is LOW. Bits are counted from right to left. The rightmost bit is bit 0.