3.1.1 Set, Clear and Read Register Bits Using Bit Masks

The register bits can be set, cleared and read using the bit masks provided by the header file.

Access the registers using the structure declaration

To set a specific bit in a register, the recommended coding style is to use the structure instance declared in the header file and bit masks macro definitions. Using the binary OR operator with the bit mask will ensure that the other bit settings made inside that register will remain the same, unaffected by the operation.

ADC0.CTRLA |= ADC_ENABLE_bm; /* Enable the ADC peripheral */

To clear a bit from a register, 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.

ADC0.CTRLA &= ~ADC_ENABLE_bm; /* Disable the ADC peripheral */

The ADC_ENABLE_bm bit mask is defined in the header file, as presented below.

#define ADC_ENABLE_bm  0x01  /* ADC Enable bit mask */

Reading a bit value is necessary for various applications. For example, the ADC RESRDY flag is set by hardware when an ADC result is ready. The code listing below shows how to test if this bit is set and execute some instructions in this case.

if(ADC0.INTFLAGS & ADC_RESRDY_bm) /* Check if the ADC result is ready */
{
    /* Insert some instructions here */
}

To test if a bit is clear, and execute instructions or wait while it remains clear, the following code can be used. In this case, the instructions inside this loop will be executed until the ADC result is ready.

while(!(ADC0.INTFLAGS & ADC_RESRDY_bm))
{
    /* Insert some instructions here */
}

Access the registers using the macro definition

Alternatively, the registers can be accessed also using the macro definitions from the header file. The example below shows how to set a bit using these definitions.

ADC0_CTRLA |= ADC_ENABLE_bm; /* Enable the ADC peripheral */

To clear a bit using macro definitions, the following code example can be used.

ADC0_CTRLA &= ~ADC_ENABLE_bm; /* Disable the ADC peripheral */

The code listing below shows how to test if this bit is set and to execute some instructions in this case.

if(ADC0_INTFLAGS & ADC_RESRDY_bm) /* Check if the ADC result is ready */
{
    /* Insert some instructions here */
}

To test if a bit is clear, and execute instructions while it remains clear, the following code can be used. In this case, the instructions inside this loop will be executed until the ADC result is ready.

while(!(ADC0_INTFLAGS & ADC_RESRDY_bm))
{
    /* Insert some instructions here */
}