5.2.6 Using SFRs From C Code

The Special Function Registers (SFRs) are typically memory mapped registers and are accessed by absolute C structure variables that are placed at the register’s address. These structures can be accessed in the usual way so that no special syntax is required to access SFRs.

The SFRs control aspects of the MCU and peripheral module operation. Some registers are read-only; some are write-only. Always check your device data sheet for complete information regarding the registers.

The SFR structures are predefined in header files and are accessible once you have included <xc.h> (see 5.2.3 Device Header Files) into your source files. Structures are mapped over the entire register and bit-fields within those structures allow access to specific SFR bits. The names of the structures will typically be the same as the corresponding register, as specified in the device data sheet, followed by bits (see 3.3.2.5 How Do I Find The Names Used To Represent SFRs And Bits?). For example, the following shows code that includes the generic header file, clears PORTA as a whole and sets bit 2 of PORTA using the bit-field definition.

#include <xc.h>
int main(void)
{
    PORTA = 0x00;
    PORTAbits.RA2 = 1;
}

Care should be taken when accessing some SFRs from C code or from in-line assembly. Some registers are used by the compiler to hold intermediate values of calculations and writing to these registers directly can result in code failure. A list of registers used by the compiler and can be found in 5.6 Register Usage.