Bit Opperations

Programming an AVR is fairly different to programming an Arduino board because you will be required to directly manipulate the microcontroller registers on a bit level. To be able to do this effectively an understanding of bit operations is required. A bit is a single binary digit so either a 1 or a 0. When using Arduino you often define these values as TRUE/FALSE or HIGH/LOW but they are also sometimes refered to as YES/NO, Logic 1/0 or even simply 1/0. Lets take a look at the different operations we can use to manipulate these bits.

NOT

We’ll start with the easiest of all bit operations, the NOT. The NOT operator inverts the bit, a 1 becomes a 0 and a 0 becomes a 1. It’s that simple! NOT is written in C using the ‘!’ mark.

!1 = 0
!0 = 1

OR

The next operation we will look at and probably the most common operator is ‘OR’. An OR operation can be performed on two or more bits. The bits are compared and the opperation returns a 1 if any of the bits being evaluated are a 1. It is written in C with the ‘|’ mark.

1 | 0 = 1
0 | 0 = 0

This is also a good time to introduce truth tables; a table that shows the result of an opperation.

OR | 0  1
---|------
 0 | 0  1
 1 | 1  1

AND

The other essential operation is the ‘AND’ operation which functions almost as an opposite to the ‘OR’ opperation. When an ‘AND’ opperation is performed a 1 is only returned if all bits are a 1, otherwise the result is 0. In C the and opperation is written using ‘&’.

1 & 0 = 0
1 & 1 = 1

And here is the truth table.

AND | 0  1
-----------
  0 | 0  0
  1 | 0  1

Registers

There are other operators you can use such as ‘XOR’, ‘NAND’ and ‘NOR’ but they are rarely used and out of scope for this post.

The bits used to control microcontroller functions are arranged into groups of 8 called registers. These registers can be manipulated using the bit operators discussed above. The operations work on each column individually. (Note the 0b prefix denoting the number is represented in binary format)

     0b00101001            0b01101101
AND  0b01011001       OR   0b01001010       !  0b01100101
---------------       ---------------       -------------
  =  0b00001001        =   0b01101110       =  0b10011010