PY2021 Doc - Electronics - Firmware Guides

Basics For Bit Manipulation
Guide to Bit Manipulation

AVR Programming
The Microchip/Atmel AVR series is a very popular microcontroller because it is used in many Arduino boards including the UNO and Mega. While the Arduino environment makes learning easy and prototyping fast, it comes at the cost of performance and flexibility.

Registers and bitwise operations
The AVR series of microcontrollers perform I/O and configuration by reading and writing to registers. By setting or checking whether a particular bit is set in a particular register, you can configure most of the functionality on the chip as well as do input and output through the GPIO pins.

Because particular bits being set in a register can affect the IO and other chip functionality, one needs to use bitwise operations to check, set and clear bits within a register. Wikipedia has a general overview of what bitwise operations do. Bitwise Operators

To summarize the most common bitwise operations in C: The binary shift operator allows you to shift all bits to the left or right by a number of places. For example, if you want the value of the nth bit (zero-indexed with the 0th bit being the least significant bit):

The value of 1 (00000001 in binary) will be shifted left n places. Shifting left by n is equivalent to multiplying by 2^n while shifting right is equivalent to dividing by 2^n. So (1 << 3) = 8 = 0001000 binary. You can set a bit in a variable or register without affecting other bits by logically ORing ( | ) it. For example, this will set the 2nd (zero-indexed) most significant bit in x

If you want to clear a bit in a register or variable without affecting the other bits, you can AND ( & ) it will the inverse/negation of that bit ( ~ )  The 2nd bit will be cleared without affecting the other bits.

If you want to check whether a bit is set, simply AND with that bit:  The condition will execute iff the 2nd bit is set in x.