Bitwise shift left operator

Im testing out the Adafruit 1188 capacitive touch breakout and it comes with example code. In this code they use bitwise shift left to cycle thru the array of touch pads and print out the pad number when it's touched:

for (uint8_t i=0; i<8; i++) {
    if (touched & (1 << i)) {
      Serial.print("C"); Serial.print(i+1); Serial.print("\t");
    }
  }

Could anyone explain how this works?

Im familiar with cycling thru an array of buttons in this way:

for(i = 0; i<8, i++) {
  if (button[i] = LOW) {
    // do something
  }
}

This gives me the option to write specific functions for the different buttons in the array because im using the if (button[ i ] = LOW) to know exactly which button in the array was pressed. How would i be able to know which pad is pressed using the bitshifting method so that i can write functions for each pad when it's touched? Any help would be greatly appreciated!

You have to look at the place in the code where variable "touched" is assigned a value.

touched is a variable that holds the states of the 8 touchpads, one bit for each touchpad.

This line

if (touched & (1 << i))

tests the value of the bit at position i

Similar to

if ( bitRead( touched, i ) )

By the way this line is wrong:

if (button[i] = LOW)

= is for assignment, use == for comparison.

Thanks Guix.

guix:
touched is a variable that holds the states of the 8 touchpads, one bit for each touchpad.

So just to check, would the touched variable look something like

00000000

instead of an array which would be 0,0,0,0,0,0,0,0?

Nice catch on the = btw, totally missed the ==.

Yes :slight_smile:

ah, ok. Gotcha. That's awesome. So by using BitRead and i I can get the cap that's active. That's super cool! Thanks bud

From the library example:

void loop() {
  uint8_t touched = cap.touched();

  if (touched == 0) {
    // No touch detected
    return;
  }
  
  for (uint8_t i=0; i<8; i++) {
    if (touched & (1 << i)) {
      Serial.print("C"); Serial.print(i+1); Serial.print("\t");
    }
  }
  Serial.println();
  delay(50);
}

'touched' is not an array but a uint8_t (byte). For the rest, see the above replies.

You can also use BitRead(), an easier to read method of accessing individual bits in a byte.