Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 177 of 9363. Microcontroller Fundamentals and Bare-Metal CFree lesson

Performing Bitwise Operations on Register Bits

Learners will use bitwise AND, OR, and XOR operations to modify specific status and control bits within hardware registers.

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 a 1 in your mask becomes a 1 in the register, while 0s 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 is 0 and all others are 1. 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 is 0, XORing it with 1 makes it 1. If it is 1, XORing it with 1 makes it 0.
    • 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.