Bitwise Shift operators
Now we have reached the last section of bitwise operators. Bit shift Operators are used when you want to specify the bit number to be changed rather than masking it.
If a particular bit has to be set, then we can use left-shift (<<) operator.
Set PORTC to 0
PORTC = 0x00 // Clear all bits, PORTC = 0b00000000
Now if you write PORTC |= (1<<5), PORTC value becomes 00100000.
Let us see how this happens. When you write (1<<5), 1 sets the first bit which turn into 00000001. Now when (<<5) line is executed, this shifts the 1 in 00000001 to the left 5 times and results in 00100000.
If you need to set the 1st bit to 1, then PORTC = (1<<0) sets PORTC = 00000001. Fair enough. But what if we need to set both the bits? In this case, all that is needed is to OR the result.
00100000 | 00000001 = 00100001
PORTC = PORTC | 00100001
PORTC = 00000000 | 00100001
PORTC = 00100001
Programmatically you can write this as
PORTC = (1<<0)|(1<<4)
which results in 00100001.
Great!! Did we forget anything? Oh yeah, we haven’t looked at clearing a bit using shift operator. This is relatively simple if you have understood how we cleared it before.
Now PORTC = 00100001. Assume that we need to clear all the bits in this port.
This can be accomplished by writing
PORTC &= ~((1<<0)|~(1<<5))
Let us break this line and see how this is achieved.
We know that 1<<0 = 00000001 and 1<<5 = 00100000
(1<<0) | (1<<5) = 00000001 | 00100000
(1<<0) | (1<<5) = 00100001
~((1<<0) | (1<<5)) = 11011110
PORTC & = 11011110
PORTC = PORTC & 11011110
PORTC = 00100001 & 11011110
PORTC = 00000000
Now we have cleared all the bits in PORTC.
Similarly, we can use the XOR operator to toggle a bit using shift operator, which is really simple. If you have understood whatever you have learnt till now, then try toggling a bit using XOR and bitshift operator. Take it up as an exercise and give it a try.
Setting a bit using bitwise OR:
PORTC |= (1<<x); // where x is the bit set in PORTC.
Clearing a bit using bitwise AND:
PORTC &= ~(1<<x); // where x is the bit cleared in PORTC.
Toggling a bit using bitwise XOR:
PORTC ^= (1<<x); // where x is the bit toggled in PORTC.
The only one not included is "how to check the status of a bit". All you need to do is AND it with the bit you want to check. I have not written the code in this tutorial. Just think about it and see if you can come up with an answer.
This ends a complete tutorial on bit wise operators, and also the blinking LED tutorial.