Set, Clear and Read Register Bits using Bit Unions

The recommended coding style to set or clear a specific bit in a register is to use the union declaration of the register from the header file.

The example below shows how to set and clear the Enable bit from the ADCON0 register using the recommended coding style.

ADCON0bits.ADON = 1; /* the ADC Enable bit is set */
ADCON0bits.ADON = 0; /* the ADC Enable bit is cleared */
The value of a register bit can be tested as follows. The code listing below shows how to poll the ADGO bit, waiting until it is cleared:
/* wait while the ADGO bit is set */
while(ADCON0bits.ADGO) 
{
    /* wait */
}
Note: Setting the ADGO bit in the ADC´s ADCON0 register starts an ADC conversion. This bit is then cleared by hardware when the conversion is complete.

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

/* if pin 0 of the PORTA is clear execute a set of instructions */
if(!PORTAbits.RA0)
{
    /* set of instructions */
}