Change Register Bit Field Configurations using Bit Masks

When updating only a bit field in a register, a read-modify-write must be used, to keep the other settings unaffected. Therefore, in order to change the configuration of a register bit field, it is recommended to first clear the bit field and then set a new configuration. However, in order to avoid putting the register in an unintended state between the clear and setting the new configuration, this should be done in a single line of code. For simplicity, the steps are first covered individually.

The bit field masks can be used to clear a bit field before assigning a new configuration. In the example, the T0OUTPS bit field mask is used to clear bit field.

/* The T0OUTPS bit field is cleared (Selecting a postscaler of 1:1 (T0OUTPS = 0)) */
T0CON0 &= ~_T0CON0_T0OUTPS_MASK; 
/* Selecting new configuration (0b0111) of the T0OUTPS bit field */
T0CON0 |= _T0CON0_T0OUTPS2_MASK | _T0CON0_T0OUTPS1_MASK | _T0CON0_T0OUTPS0_MASK;  

The bit field mask for the TMR0 Output Postscaler Select (T0OUTPS) has the following declaration in the header file.

#define _T0CON0_T0OUTPS_MASK                               0xF

These steps must be implemented in a single line to avoid putting the microcontroller in an unintended state.

T0CON0 = (T0CON0 & ~_T0CON0_T0OUTPS_MASK) | _T0CON0_T0OUTPS2_MASK 
                                          | _T0CON0_T0OUTPS1_MASK 
                                          | _T0CON0_T0OUTPS0_MASK;
Note: If the code is implemented as two separate lines, the first line of code will select for a short time, a postscaler of 1:1 (T0OUTPS = 0).
CAUTION: Even though it may seem easier to split the code into two separate lines of code, one to clear the old configuration and another to set the desired configuration. It is recommended to use a single line to achieve this, as presented in the code listing.