Search code examples
cpic

How do I iterate over adjacent PIC microcontroller registers?


I'm writing an application for a PIC18F45K80 microcontroller. I would like to retrieve bytes from the eight RXB1D registers. According to the datasheet, "Each receive buffer has an array of registers." Also, studying the defines reveals that all 8 registers have consecutive memory addresses, just like an array.

What is the correct syntax for looping through these registers?

I've tried for (i = 0; i < len; i++) databuf[i] = RXB1D0[i];, but the compiler returns error: subscripted value is not an array, pointer, or vector, and points to the RXB1D0 identifier.


Solution

  • I would discourage you from doing it this way as PICs use Hardware architecture and memory access via a pointer in some areas might not work as it requires special assembly instructions. They are only 8 so I would do it this way:

    #define GETREG(b, i) (b)[i] = RXB1D ## i
    #define GETREGS(b) do {GETREG(b,0);GETREG(b,1);GETREG(b,2);GETREG(b,3);\
                           GETREG(b,4);GETREG(b,5);GETREG(b,6);GETREG(b,7);}while(0)
    

    and usage:

    void foo()
    {
        char databuff[8];
        GETREGS(databuff);
    }
    

    Every read will compile to two assembly instructions. Even if you find the way of looping using pointers it will result in much more instructions.