1

I'm using XC8 compiler to develop a small embedded application with a PIC. In XC8 to set the usage of a pin (output or input), the programmer should perform an instruction like this:

TRISAbits.RA0 = 1;

in particular:

  • TRIS in the prefix of the register (constant)
  • A is the port
  • bits is the suffix (constant)
  • RA0 is the name of the pin

What I want to do is to define all pins with a human-readable name, like:

#define LED_1     A,RA0
#define LED_2     A,RA1
#define SWITCH_1  B,RB5
...

And define some macros like SET_OUTPUT or SET_INPUT used in this way: SET_OUTPUT(LED_1).

What I tried to do is these two macros:

#define SET_INPUT(port, pin)  TRIS ## port ## bits. ## pin ## = 0

however, the comma inside the previously defined constants is not expanded and interpreted as a single argument. I tried also:

#define SET_INPUT(X)  SET_INPUT_(X ## "")
#define SET_INPUT_(port, pin)  TRIS ## port ## bits. ## pin ## = 0

without success.

Essentially is the opposite of this question: Comma in C/C++ macro

Does it exist a solution or a more convenient way to do that?

Community
  • 1
  • 1
ocirocir
  • 3,543
  • 2
  • 24
  • 34
  • At the start you say it should be `= 1`, but then you tried `= 0` in your macros, what's that about? – M.M Jun 12 '16 at 21:18

1 Answers1

3

You were close:

#define SET_INPUT(X)  SET_INPUT_(X)
#define SET_INPUT_(port, pin)  TRIS ## port ## bits.pin = 1

The ## is only for pasting two tokens to form another token. For cases where you are not forming a new token (e.g. bits.pin) you don't need to do anything special.

I would recommend statement-izing the macro:

#define SET_INPUT_(port, pin)  do { TRIS ## port ## bits.pin = 1; } while (0)
Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365