Beetwise

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.

Name or expression
ID0
Binary
0b
Hex
0x
Decimal
ASCII
·
Shift
Sign
Bits
Endian
7
6
5
4
3
2
1
0

Worked example

Change one field without damage to the others:

  1. Read the current register value.
  2. Clear the field: apply AND with the inverted mask of the field.
  3. Shift the new field value up to its bit position.
  4. Apply OR to insert the new value.
  5. 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 editor

Questions

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.