In embedded systems, we often deal with individual bits, not just bytes or variables. Whether it’s turning a GPIO pin ON or checking a status flag, you’ll use one set of tools over and over again:

🔧 Bit Manipulation Operators

Master these, and you can command hardware like a wizard.


💡 Why Bit Manipulation Matters

Imagine you have a 32-bit register that controls several pins or features. You might want to:

  • Turn ON just one pin
  • Clear only one flag
  • Toggle a bit without touching others

That’s where bitwise operators come in.


🧰 The Essential Bitwise Operators

OperatorSymbolUse CaseExample
AND&Mask bits (clear)reg & 0xF0
OR``Set bits
XOR^Toggle bitsreg ^ (1 << 2)
NOT~Invert bits~reg
Shift L<<Shift bits left (multiply)1 << 5
Shift R>>Shift bits right (divide)reg >> 2

🚦 Real-Life GPIO Example

Suppose GPIO_PORT is the address of an output register:

#define GPIO_PORT (*((volatile uint32_t*)0x400FF040))

✅ Set Pin 5 High (Bit 5 → 1)

GPIO_PORT |= (1 << 5);

❌ Clear Pin 5 (Bit 5 → 0)

GPIO_PORT &= ~(1 << 5);

🔁 Toggle Pin 5

GPIO_PORT ^= (1 << 5);

❓ Check if Pin 5 is HIGH

if (GPIO_PORT & (1 << 5)) {
    // Pin is High
}

🔄 Example: LED Toggle with Button Input

#define BUTTON_PIN   (*((volatile uint32_t*)0x400FF000))
#define LED_PIN      (*((volatile uint32_t*)0x400FF040))
void toggle_if_button_pressed() {
    if (!(BUTTON_PIN & (1 << 2))) { // Button active low
        LED_PIN ^= (1 << 5);        // Toggle LED
    }
}

⚙️ Bit Masks

Bit masks are custom binary values used to isolate or modify specific bits.

TaskMask Example
Mask Bit 30b00001000 (8)
Mask Bits 1-30b00001110 (14)
Clear Bit 2~(1 << 2)

💬 Pro Tip

If you’re working on larger systems or safety-critical software (like AUTOSAR or automotive), you’ll often see macros like:

#define SET_BIT(REG, BIT)     ((REG) |= (1U << (BIT)))
#define CLEAR_BIT(REG, BIT)   ((REG) &= ~(1U << (BIT)))
#define TOGGLE_BIT(REG, BIT)  ((REG) ^= (1U << (BIT)))
#define READ_BIT(REG, BIT)    (((REG) >> (BIT)) & 1U)

These make your code cleaner, safer, and reusable.


🔍 Up Next (Day 6):

🧱 Timers & Delays – How Microcontrollers Keep Track of Time
We’ll dive into how embedded systems use hardware timers for precise delays, blinking LEDs, PWM, and more.

LEAVE A REPLY

Please enter your comment!
Please enter your name here