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 microcontroller registers in the bit editor

An 8-bit control register with several fields. Edit the expression or select a bit to flip it.

7
6
5
4
3
2
1
0
0xB6
hex · 8 bits
value
182

Microcontroller registers step by step

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.

Masks in common use

Masks in common use
MaskBinaryPurpose
0x0100000001Test bit 0
0x0F00001111Keep the low nibble
0xF011110000Keep the high nibble
0x7F01111111Clear the top bit
0x8010000000Test the top bit
0xFF11111111Keep the low byte
0xFFFF16 bits setKeep the low two bytes

Where microcontroller registers 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.

Microcontroller registers: 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 bit editor

The full editor holds many values, evaluates expressions across them, and reads live values from a serial port.

Open this value in the full editor

Questions about microcontroller registers

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.