Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 272 of 9364. Peripheral Interfacing and ControlFree lesson

Performing Atomic Register Access for Bit Manipulation

Students will implement atomic bitwise operations to modify specific GPIO registers without corrupting adjacent pin configurations during concurrent execution.

Performing Atomic Register Access for Bit Manipulation

In this lesson, you will learn how to modify specific bits in a GPIO register safely, ensuring your changes persist without being accidentally wiped out by concurrent system operations.

The Problem: The Read-Modify-Write Hazard

When you want to turn on one LED connected to GPIOA without affecting the other pins, you typically perform a Read-Modify-Write sequence:

  1. Read the current value of the register into a CPU variable.
  2. Modify that variable using bitwise logic (e.g., ORing a bit to set it high).
  3. Write the new value back to the register.

The danger arises if an interrupt occurs between step 1 and step 3. If an interrupt routine modifies the same register, your CPU will eventually overwrite those changes with its stale version of the data, leading to "race conditions" where your peripheral settings become corrupted.

The Solution: Bit-Banding and Atomic Sets

To avoid this, we use atomic operations. Many modern microcontrollers provide an "Atomic Bit Set/Reset Register" (often called a BSRR or BITSET register). Instead of reading the whole register, you write a specific "magic value" to this hardware-mapped address. The hardware circuitry interprets this write as an instruction to modify only the target bit, leaving the other bits untouched.

Because this happens in a single hardware cycle, the processor does not need to perform a read-back, making it impossible for an interrupt to "sneak in" during the process.

// Non-Atomic approach (Dangerous in concurrent environments):
GPIOA->ODR |= (1 << 5); 

// Atomic approach (Safe):
// Writing to the BSRR register affects only the chosen pin
// without requiring a read or a risk of corruption.
GPIOA->BSRR = (1 << 5); 

By using these specialized registers, you ensure that your pin manipulation is isolated and immune to the timing unpredictability of background interrupts. This keeps your peripheral configuration robust even as your application grows in complexity.

Key Takeaway: Always use atomic hardware registers (like BSRR) instead of manual Read-Modify-Write sequences to prevent data corruption from concurrent interrupt execution.