Set, Clear and Read Register Bits using Bit Masks

There are alternative ways to set and clear register bits by using bit masks or bit positions.

In order to set a bit from a register using bit masks, the binary OR operator will be applied between the register and the bit mask. Using the binary OR operator will ensure that the other bit settings made inside the register will remain the same and unaffected by this operation.

ADCON0 |= _ADCON0_ADON_MASK; /* the ADC Enable bit is set */

In order to clear a bit from a register using bit masks, the binary AND operator will be applied between the register and the negated value of the bit mask. This operation also keeps the other bit settings unchanged.

ADCON0 &= ~_ADCON0_ADON_MASK; /* the ADC Enable bit is cleared */

The bit mask for the ADC Enable bit (ADON) has the following declaration in the header file.

#define _ADCON0_ADON_MASK                                   0x80

The code listing below shows how to read the value of a PORT pin using bit masks and execute a set of instructions if that pin is low.

if(PORTA & _PORTA_RA0_MASK)
{
    /* set of instructions */
}