I'm doing some AVR programming and am kinda getting to grips with this whole bit operation thing but still ain't so sure about data type conversion.
For example:
I have a 16-bit variable (myValue
) that corresponds the state of 16 LEDs over 2 ports (e.g. 8 LEDs on Port A and 8 on Port D). The 8 high bits of myValue
are on Port D.
So my idea was to essentially use (0b0000000011111111 & myValue)
to get the values for Port A and (0b1111111100000000 & myValue)
for Port D
The question is then can I then do something like uint8_t portA = (0b0000000011111111 & myValue)
? I believe I can just simply then set
PORTA |= portA
since Port A has only 8 pins (in my case).
The problem arises in Port D since using unsigned 8 bit on the other hand is not possible for Port D because it will still remain a 16-bit variable after the &
operation? How do I then set an 8-pin Port D with a 16-bit variable?
Use:
PORTD = (myValue >> 8) & 0xff;
Also stay on the safe side and do the clipping for port A:
PORTA = myValue & 0xff;
Be aware that by using |=
you can only set bits from 0 to 1, bits that are already 1 will not be altered by the or operation.