by

Using Bytes and Bitmasks to Control Multiple Arduino Digital Outputs

A fine way to compactly control multiple Arduino digital output pins is to use a byte in conjunction with a bitmap. The byte provides the structure (eight bits) to compactly specify which digital pins are turned on and which are turned off. Let’s consider an example. Suppose you have eight digital output pins to control, Arduiono pins 2, 3, 4, 5, 6, 7, 8, and 9 for example. More specifically, let’s say you want pins 2, 3, 5, and 8 to be turned on (high) and pins 4, 6, 7, and 9 to be turned off (low). The following code will accomplish this.

int myPins[] = {2, 3, 4, 5, 6, 7, 8, 9};
int onPins = B11010010; 

void setup() {
   for (int ii = 0; ii <= 7; ii++) {
      pinMode(myPins[ii],OUTPUT);
      digitalWrite(myPins[ii],LOW);
   }
}

void loop() {
   for (int ii = 0; ii <= 7; ii++) {
      if (onPins & (B10000000 >> ii)) {
         digitalWrite(myPins[ii],HIGH);
      }
      else {
         digitalWrite(myPins[ii],LOW);
      }
   }
}

The B10000000 >> ii portion of the code uses a right bit shift operator to shift each bit in B10000000 exactly ii places to the right. For each rightward shift, the least significant bit falls off and the most significant bit is replaced by a zero. For example B10000000 >> 4 would yield B00001000.

The conditional part of the if statement uses the bitwise AND compare. Each bit of the byte contained by onPins is compared to the corresponding bit of the byte resulting after the bit shift operator (what is often referred to as the bitmask). If any of the bitwise compares evaluates true then the entire if statement evaluates true and the if statement code is executed. If none of the bitwise compares evaluate true then the if statement evaluates false and the code in the else statement is executed.

Note that the result of the bitmask is to turn on all of the pins corresponding to the 1s in onPins and turn off all the other pins.

I hope you found this quick tutorial helpful. Happy programming.

Leave a Reply

Your email address will not be published.