Electronic – PORT names ans CONST in an array

picport

uC: PIC18F46K20

I want to scan, in a loop, different ports and test different pins on each port.

I have different target boards so I want to be able to quickly configure each board in CONST arrays. So I created arrays like these:

const char my_ports[4] = {PORTB, PORTB, PORTD, PORTA}; // <- this is the PROBLEM causing line
const char my_pins[4] = {3, 7, 1, 4};

in order to be able to scan those ports in a loop:

// NEW version of the func.
void pin_update(void)
{
  for (k=0; k<=3; k++)
  {
    if (my_ports[k] & my_pins[k])
    {
     // and actions here ........
    }
  }
}

But compiler comes up with an error :

        "my_ports[] ... constant expression required"

I used the approach of passing the port name (eg. PORTB) in previous version of the code when each pin was tested individually, eg. :

    pin_update(PORTB, 3);   
            // ...
    pin_update(PORTD, 1);   

// OLD version of the func:
void pin_update(char prt, char pn)
{
    if (prt & pn)
    {
     // and actions here ........
    }
}

and all was OK and code worked properly. But as you see PORTB is hard coded in a parameter list. And now I want to run the above 'pin updates' in a loop.

So problem came out when I wanted to list port names in CONST array.
I tried various things with casting to ports' addresses etc – nothing worked. Compiler still did not like it.

Best Answer

The compiler is correct. PORTx aren't constant; they result in the value stored in hardware. You need to store a pointer to the port and then dereference it when appropriate.

const *char my_ports[4] = {&PORTB, &PORTB, &PORTD, &PORTA};
const char my_pins[4] = {3, 7, 1, 4};

 ...

void pin_update(void)
{
  for (k=0; k<=3; k++)
  {
    if (*(my_ports[k]) & my_pins[k])
    {
     // and actions here ........
    }
  }
}