Search code examples
mplabxc8

xc8 : please detailed the (((unsigned)&(REGISTER_NAME))*8) + BIT_NUM


i want defining macros for set pin direction and level.their argumans must be port name and pin number.i dont want use TRIS Register or LAT register name,only port name(PORTA e.g).i do this with pointer and bit mask like:

set pin dir:

#define SET_PIN_DIR_IN(port,pin)   *(&port+0x80)|=1<<pin

set pin level:

#define SET_PIN_HIGH(port,pin)      port|=1<<pin

read pin state:

#define READ_PIN_LEVEL(port,pin)   (((*(&port+0x100)>>pin)&0x01)==0x01)

but i know above code is not optimum. Q1:can i write my macro with "(((unsigned)&(REGISTER_NAME))*8) + BIT_NUM" Optimally? Q2:for all PIC MCU,is order of I\O register same?


Solution

  • If you are using xc8 you are probably using an 8 bit PIC processor :). A more normal way to do this is to first set the direction by setting the tri-state attribute of the pin for instance:

    TRISA1 = 0; // tri-state OFF so this pin is an output
    TRISA2 = 1; // tri-state ON so this pin is an input
    

    You read an inputs pin vale by its R value thus:

    pin2_state = RA2;
    

    To set an output you use the LATCH, so to set A1 to 1 use

    LATA1 = 1;
    

    With port AN you sometimes also have to disable the analog inputs using the ANSEL register (i.e. the pins wont work properly and DIGITAL if they are assigned to be analog inputs). Look at the data sheet for your device and the ANSEL register defaults.