Help with #define substitutiuon

Talk about anything you want!
Post Reply
george4657
Posts: 21
Joined: Fri Apr 05, 2013 7:05 pm

Help with #define substitutiuon

Post by george4657 » Tue Sep 29, 2015 4:02 pm

I am learning to use defines but this one I can't get to work.
I have:
#define STEPPERS_DISABLE_PORT D
#define STEPPERS_DISABLE_BIT 5 // Max32 pin 39

#define STEPPERS_DISABLE_MASK (1<<STEPPERS_DISABLE_BIT)
#define STEPPERS_DISABLE_CLR LATDCLR=STEPPERS_DISABLE_MASK
#define STEPPERS_DISABLE_SET LATDSET=STEPPERS_DISABLE_MASK

This works but I would like to have:
#define STEPPERS_DISABLE_CLR LAT + STEPPERS_DISABLE_PORT + CLR=STEPPERS_DISABLE_MASK
So I only have to change D and 5 to change pin
Is this possible:

Thanks
George

User avatar
majenko
Site Admin
Posts: 2164
Joined: Wed Nov 09, 2011 7:51 pm
Location: UK
Contact:

Re: Help with #define substitutiuon

Post by majenko » Tue Sep 29, 2015 4:14 pm

Yes, it is possible, but it's not straightforward.

You have to use a multi-later approach to concatenate macros together.

First you need a macro that will concatenate three parameters together:

Code: Select all

#define TRIPCAT(A, B, C) A ## B ## C 
Then you need one that will parse the parameters as macros and pass them to the TRIPCAT macro (the TRIPCAT macro won't parse them because it's using the token-pasting operator ##):

Code: Select all

#define GENLAT(X) TRIPCAT(LAT, X, CLR)
Then you can use that in your final macro:

Code: Select all

#define STEPPERS_DISABLE_CLR GENLAT(STEPPERS_DISABLE_PORT)=STEPPERS_DISABLE_MASK
So in total you have:

Code: Select all

#define STEPPERS_DISABLE_PORT D
#define STEPPERS_DISABLE_BIT 5 // Max32 pin 39
#define STEPPERS_DISABLE_MASK (1<<STEPPERS_DISABLE_BIT)

#define TRIPCAT(A, B, C) A ## B ## C
#define GENLAT(X) TRIPCAT(LAT, X, CLR)
#define STEPPERS_DISABLE_CLR GENLAT(STEPPERS_DISABLE_PORT)=STEPPERS_DISABLE_MASK

STEPPERS_DISABLE_CLR
That last line is just there to force an invocation for testing - pass that through the preprocessor and you end up with:

Code: Select all

$ cpp macro.c 
# 1 "macro.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "macro.c"
# 9 "macro.c"
LATDCLR=(1<<5)
Why not visit my shop? http://majenko.co.uk/catalog
Universal IDE: http://uecide.org
"I was trying to find out if it was possible to only eat one Jaffa Cake. I had to abandon the experiment because I ran out of Jaffa Cakes".

george4657
Posts: 21
Joined: Fri Apr 05, 2013 7:05 pm

Re: Help with #define substitutiuon

Post by george4657 » Tue Sep 29, 2015 4:51 pm

Thank you very much. I tried to google for solution but could not find anything close to this.
I am converting GRBL to run on a pic32mx and the code is littered with masking functions so having this macro will make it much easier to convert as well as making pin swapping easier.

Thanks
George

Post Reply