Performing Bitwise Operations on Register Bits
In this lesson, you will learn how to precisely toggle, set, or clear specific bits within a hardware register using bitwise operators to control peripheral behavior.
When we interact with hardware, we rarely want to overwrite an entire register. Writing a new value to a status register might accidentally turn off a timer or change a clock divider. Instead, we use bitwise operators (&, |, ^) to modify only the bits we care about while leaving others untouched.
The Bitwise Trio
- Bitwise OR (
|): Used to set specific bits to 1. By ORing a register with a bitmask, any bit that is a1in your mask becomes a1in the register, while0s in the mask leave the original register bits unchanged.REG |= (1 << 3);// Sets bit 3 to high, keeps others as they were.
- Bitwise AND (
&): Used to clear bits or isolate a value. To clear a bit, we use a mask where the target bit is0and all others are1. Using the bitwise NOT operator (~) makes this easy.REG &= ~(1 << 3);// Clears bit 3 (sets it to 0), keeps others as they were.
- Bitwise XOR (
^): Used to toggle bits. If the bit is0, XORing it with1makes it1. If it is1, XORing it with1makes it0.REG ^= (1 << 3);// Flips bit 3 from its current state.
Why This Matters
In bare-metal C, these operations are the primary language of hardware control. A register might control an LED, a communication baud rate, or an interrupt flag. By shifting a 1 into a specific position (like 1 << 3 to target the 4th bit), we create a "mask." When we apply that mask with one of the operators above, we gain fine-grained control over the physical state of the microcontroller.
Key Takeaway: Use OR to set bits, AND with a negated mask to clear bits, and XOR to toggle them, ensuring your hardware modifications are surgical and don't disrupt unrelated configuration bits.