In a previous question (Append Text to Variable Names: Please Help Me Shorten This Code) I learned that in order to shorten this code:
fanSpeed = readEEPROM(AT24C32_ADDRESS, 1, fanSpeedPos);
I could define a macro at the top of the script like this:
#define readEE(VAR) VAR = readEEPROM(AT24C32_ADDRESS, 1, VAR ## Pos)
And then just use the following shorter code:
readEE(foo);
Which would be expanded out to:
foo = readEEPROM(AT24C32_ADDRESS, 1, fooPos);
My current question is: How can I write a macro that accepts 2 arguments instead of just 1? I couldn't find much information about this concerning Arduinos, so I studied about how to do it in C++ (like from here: http://en.cppreference.com/w/cpp/preprocessor/replace) but it was too complicated for me to understand.
In particular, I would like to learn if it's possible to shorten the following code:
void writeToEE(byte location, bool value, bool &var) {
writeEE(loc, value); var = value;
}
(Sidenote: the writeEE
function looks like this: void writeEE(uint8_t entry, uint8_t data) { writeEEPROM(AT24C32_ADDRESS, 1, entry, data); }
. Since the first 2 arguments are almost always constants, that's why I shortened it with another function).
Since whenever I'm using writeToEE
, the "entry" variable name is always the "data" variable name with "Pos" appended, I would ideally like to do this (pseudo-code):
#define wrEE(VAR, VAL) VAR = writeToEE(VAR ## Pos, VAL, VAR)
so that when I write this:
wrEE(fanSpeed, 3);
it will be expanded out to:
writeToEE(fanspeedPos, 3, fanspeed);
I just don't know how to pass the 2nd argument ("VAL") into the macro, which is the value being stored in the "fanSpeed" variable, in the "fanSpeedPos" location in the EEPROM. When I try to compile my pseudo code example (was hoping to get lucky!), I get the following error message: "void value not ignored as it ought to be"
void
. Which means it doesn't return anything.readEEPROM
was returning a variable, which is whyVAR =
was needed. I removed it so that the macro then became:#define wrEE(VAR, VAL) writeToEE(VAR ## Pos, VAL, VAR)
, and it seems to work! It seems like it's storing my variable correctly. Is it really that simple? Does it look like that's the correct way to do it?writeToEE
function is calling thewriteEE
function, would the code run faster if I skipped thewriteToEE
function and just had the macro expand out to thewriteEE
function? (Sorry for the confusing similar names). Or does it all end up to be the same after it goes through the compiler?