Search code examples
cembeddedbitwise-operatorsgpio

about reading pin from register GPIODATA


I need to understand why i have to use &=(and) instead of |=(or).

I tried drawing and using it but had no success.

      char readPin(char port,char pinNum){
       switch(port){
          case'A' :
              return ((portA &=(1<<pinNum))>>pinNum);
          case'B' :
              return ((portB &=(1<<pinNum))>>pinNum);
           case'C' :
              return ((portC &=(1<<pinNum))>>pinNum);
           case'D' :
              return ((portD &=(1<<pinNum))>>pinNum);
           case'E' :
              return ((portE &=(1<<pinNum))>>pinNum);
           case'F' :
              return ((portF &=(1<<pinNum))>>pinNum);

    }
}

I need to know why and is used instead of or.


Solution

  •  portA &=(1<<pinNum)
    

    returns a '1' at the position shifted to.

    For Example: PinNum = 4, Port A.4 is Set / High, Port A.1 is Set / High

    PortA                           -    0001 0010
    (1<<pinNum)                     -    0001 0000 &  // use bitwise and
    
    portA &=(1<<pinNum)             -    0001 0000    // Result (bit 1 is discarded due to and operation)
    ((portA &=(1<<pinNum))>>pinNum) -    0000 0001    // Result is shifted back to position 0
    

    The returned value is a 1.

    If you were to use use a bitwise or like:

    portA |= (1<<pinNum)
    

    You would return a non 0 value in all cases.

    For Example: PinNum = 4, all Port A bits are low.

    PortA                           -    0000 0000
    (1<<pinNum)                     -    0001 0000 |  // use bitwise or
    
    portA |=(1<<pinNum)             -    0001 0000    // Result (bit 4 is set)
    ((portA |=(1<<pinNum))>>pinNum) -    0000 0001    // Result is shifted back to position 0
    

    The returned value is a 1.

    As you can see, you tried to check for Pin 4 (which is not set) but you got a non zero result back (caused the masking bit).