Register access and read-modify-write
A familiar C operator can be wrong for a hardware register with special write semantics.
Registers are not ordinary RAM
Hardware registers can have read-clear, write-one-to-clear, reserved or self-clearing fields. Read the register description before choosing an access pattern. A debugger read may itself have side effects on some registers.
The RMW hazard
The expression register |= mask reads a value, modifies it and writes it back. On a write-one-to-clear status register, writing back other set bits can unintentionally clear them. Concurrent hardware changes and access-width requirements create additional risks.
Use the supported interface
Prefer vendor-provided accessors or driver APIs. Where direct access is permitted, use the documented width and semantics. For a pure write-one-to-clear field, a documented write of only the intended mask may be correct; do not generalize that to every mixed-semantics register.
/* Only for a documented pure write-one-to-clear register: */
STATUS = ERROR_MASK;
/* STATUS |= ERROR_MASK may clear unrelated set flags. */Follow each transition
Read semantics
Identify access width and field behaviour.
Conceptual sequence. Timing is slowed for learning; it is not a hardware measurement.
Your investigation
Two status bits are set. A read-modify-write intended to clear one clears both. Explain why.
Reveal the investigation checklist
- Confirm write-one-to-clear semantics.
- Inspect the actual written bit pattern.
- Replace the operation with the documented accessor.
- Test simultaneous flags and reserved-bit handling.
Why can |= be unsafe on a write-one-to-clear register?
Answer the knowledge check correctly to complete this lesson.
Think through Register access and read-modify-write
Ask for an explanation, an automotive example or a question that tests your understanding.
Checking mentor availability…