# Bitwise Operations in AVR

## Apr 25, 2017 00:00 · 380 words · 2 minutes read avr electronics

I’ve realised I’ve become abit rusty when it comes to microcontroller stuff. I’ve decided to tinker with things and I thought it’d be cool to write about C bit manipulation since I use it alot when programming microcontrollers. Here’s an example of a set of macros that uses bit manipulation:

``````#define output_low(port, pin) port &= ~(1<<pin)
#define output_hig(port, pin) port |= (1<<pin)
#define set_input(portdir, pin) portdir &= ~(1<<pin)
#define set_output(portdir, pin) portdir |= (1<<pin)
``````

Here are the bit operators and their truth tables:

(1) | : bit OR

Input A Input B Output
0 0 0
0 1 1
1 0 1
1 1 1

(2) & : bit AND

Input A Input B Output
0 0 0
0 1 0
1 0 0
1 1 1

(3)^ : bit XOR

Input A Input B Output
0 0 0
0 1 1
1 0 1
1 1 0

(4) ~ : bit NOT

Input Output
1 0
0 1

The other bitwise operator commonly used is the `<<` or shift-left operator. Let’s look at some use cases for the bitwise operators.

Let’s say I had an output pin called LED6 initialised to 0. To set(make the bit a 1) and then store the result back into LED6, I would do:

``````LED6 |= 0x01;
``````

To clear(set the bit to 0) in LED6, I would do the following:

``````LED6 &= ~0x01;
``````

Another important concept is that of shifting bits. Before we dive into this, let’s talk about Bit MASKS. A bit mask is a binary number in which the desired bits are one and the remaining are 0. We can use the `<<` operator to build bit masks. Here are examples:

``````// To build a bit mask with with bit 1 set:
(0x01 << 1)

// To build a bit mask with bit 5 set:
(0x01 << 5)

// To build a bit mask with bit 1 and 5 set:
(0x01 << 1 | 0x01 << 5)
``````

In conclusion, bitwise operations are quite important in AVR programming. They can be used to set pins as output or inputs(using the DDR) register and many other things. A fundamental understanding of bitwise operators is therefore instrumental when working with microcontrollers.