3

I was looking at some macro use in an Arduino code. I believe what this macro does is it expands into a state that basically sets a pin to either input or output, but I'm a little confused about everything going on in this macro.

I do understand the point behind the do{...} while(0), but I'm sure what the ## are accomplishing. Also, what if anything do the underscores before DDR and PIN do? I would very appreciative of a simple clarification. Thank you!

#define MASK(PIN)  (1 << PIN)

/// set pin as input
#define _SET_INPUT(IO) do {DIO ##  IO ## _DDR &= ~MASK(DIO ## IO ## _PIN); } while (0)
/// set pin as output
#define _SET_OUTPUT(IO) do {DIO ##  IO ## _DDR |=  MASK(DIO ## IO ## _PIN); } while (0)
7

## is the concatenation operator in macros. It joins two macros or pieces of text together when expanded.

#define _SET_INPUT(IO) do {DIO ##  IO ## _DDR &= ~MASK(DIO ## IO ## _PIN); } while (0)

_SET_INPUT(3);

woukd expand to:

do {DIO3_DDR &= ~MASK(DIO3_PIN); } while (0);

You can read more about how it works here: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

  • It seems that SE's syntax highlighting can't handle those macros. Should it maybe be reported? – Avamander Feb 14 '16 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.