McLion McLion - 1 year ago 122
C Question

Pointer to bit in port register

I have some code that needs to run on 2 different PCBs. At bootup the code does detect/know on which hardware it runs and sets a flag.

Now, some signals change ports depending on the hardware, i.e.:
on HW1, signal A is on 0x08 on P9 whereas it is on 0x02 on P14 on the other hardware.

I can easily check the flag everywhere signal A is used - however this solution does not seem 'nice' to me.

I can also easily change the port at boot with something like this:

if(cIsHW1) Reg = &P14;
else Reg = &P9;

and use Reg to access the correct port on each HW.

However, how do I change the bit position as well? I now there is no such thing as a pointer to a bit in a register - which is actually what would I think I would need.

I need to read these port bits and set/clear it as well.

Do I miss something or do I really need to check the flag (if .. else) everywhere I need to access that port bit?


Answer Source

Just collect the hardware-dependent data in a structure, and figure out which one to use at startup:

struct hw_config {
  volatile uint32_t *reg;
  uint32_t mask;
} boardA = { .reg = &P14, .mask = 8 },
  boardB = { .reg = &P9,  .mask = 2 },
  * board;

int main(void)
  // Figure out which board we're on, and set the board pointer.
  board = running_on_board_a() ? &boardA : boardB;

  // Example usage.
  *board->reg |= board->mask;

If you can figure out which one to use at compile-time, you can of course optimize this by never defining the redundant one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download