How to read a microcontroller register
A microcontroller register packs several fields into one value.
The data sheet gives a bit number or a bit range for each field.
To read one field, apply AND with a mask and then shift the result down.
Try it
An 8-bit control register with several fields. Select a bit to change it. Change the bit width or the signed mode to see the effect.
Worked example
Change one field without damage to the others:
- Read the current register value.
- Clear the field: apply AND with the inverted mask of the field.
- Shift the new field value up to its bit position.
- Apply OR to insert the new value.
- Write the result back to the register.
Where this is used
This read, change and write sequence is the standard method in a device driver.
A direct write of the whole register clears every other field, which stops another part of the device.
A data sheet marks some bits as reserved. Keep the value of those bits.
Points to note
- Never write a whole register to change one field. The other fields go to 0.
- Keep the reserved bits at their reset value. A write of another value gives undefined behaviour.
- Some registers clear a flag on a read. A second read gives a different value.
- Check the bit width of the register. A 32-bit register needs a 32-bit mask.
The full tool
The full editor holds many values at the same time. It also evaluates expressions across them, and it reads live values from a serial port.
Open the full editorQuestions
- How do I read one field of a register?
- Apply AND with the mask of the field, then shift the result right to bit 0.
- Why must I not write the whole register?
- A write sets every bit. The fields that you did not intend to change go to 0.
- What is a reserved bit?
- A reserved bit has no documented function. Keep its reset value, because a change can give undefined behaviour.