Use bitshift cycle with digitalWrite ?

So, the thing is I am trying to transfer a byte to a 8-pin parallel port on a LCD. Due to some space issue, The bit 0~bit 7 is plugged in digital port 28,30,32,...,42 on a Arduino Mega2560. So what I did in code is:

void LCD(byte cmd){
  byte i;
  byte ptr;
  ptr=1;
  for(i=28;i<=42;i+=2)
  {
    if (cmd & ptr == ptr)
    digitalWrite(i,HIGH);
    else
    digitalWrite(i,LOW);
    ptr << 1;
  }
}

So the idea is, if the lowest bit (bit 0) of cmd is 1, then (cmd & ptr) will equal to 0b00000001, (which is equal to ptr itself) so the pin 28 (bit 0) will be high. and vise versa, if the bit 0 is 0, (cmd & ptr) will not equal to ptr and the pin 28 is low. After the lowest bit is done, ptr do a left-shift by 1 bit (which is 0b00000010), then cycle on to check bit 1, 2, ... bit7, hence the whole byte is converted to a series of low and high.

The problem is, it doesn't work as expected, and once there is a bit 1 in the cmd, no matter how many and where it is, multimeter shows all pins are high. Is there anything wrong with my code or digitalWrite shouldn't be used like this ?

P.S. hardware is checked and made sure no short-circuit is happening.

You're never changing ptr. ptr << 1 takes the value of pointer, shifts it left, then throws the result of the shift away. You need to use either ptr <<= 1, so the result of the shift is saved back to ptr.

Regards,
Ray L.

Try some debugging print statements... They are very illuminating

void LCD(byte cmd) {
  byte i;
  byte ptr;
  ptr = 1;
  for (i = 28; i <= 42; i += 2)
  {
    Serial.print("i="); Serial.print(i);
    Serial.print(",ptr="); Serial.print(ptr);
    if (cmd & ptr == ptr) {
      digitalWrite(i, HIGH);
      Serial.println(", HIGH");
    }
    else {
      digitalWrite(i, LOW);
      Serial.println(", LOW");
    }
    ptr << 1;
  }
}

Output:

i=28,ptr=1, HIGH
i=30,ptr=1, HIGH
i=32,ptr=1, HIGH
i=34,ptr=1, HIGH
i=36,ptr=1, HIGH
i=38,ptr=1, HIGH
i=40,ptr=1, HIGH
i=42,ptr=1, HIGH

You are never assigning the new value to ptr, you are just shifting it and then throwing away the result.

Thank you awesome guys. I do improperly used << operator and now it works.

i got a little confused when i read this, since i would shift the command (not the ptr)(of course it works already..)

if (cmd & ptr)
    digitalWrite(i,HIGH);
    else
    digitalWrite(i,LOW);
    cmd=cmd >> 1;