A question that roamed my mind for a quite a while,
what is the advantage (if there is one) passing variables over from setup() to loop() vs. having global variables in a sketch?
I know it might be easier using just global variables, but that is not the question here; easy or not.
The OP explicitly referenced loop() and setup(), so I'm presuming he has a context in mind that involves those functions. Let's not wander off into a general discussion of function arguments until he's posted some context, eh?
Sorry, I made it only twice through the book and I couldn't find any reference to an explanation (or mention) of parameters to the loop() function.
However I see the construct
int main(void)
{
init();
setup();
for (;;)
loop();
return 0;
}
(pg 25., 2nd Ed.)
That tells me that apparently it is not possible to pass over parameters to the loop() function.
But I'm open for corrections.
As an explanation for all who asking me here is a code sample that is showing what I meant:
// @file funcCall.cpp
// an example how to pass and receive parameters in function calls
// ***********
void myFunction (int p1, int p2) {
Serial.println(p1);
Serial.println(p2);
}
// end function myFunction() ****//
// ***********
void setup() {
int var1 = 12;
int var2 = 365;
// how to call loop() with passing variables? perhaps [loop(var1, var2)]?
}
// end function setup() ****//
// ***********
void loop(int passvar1, int passvar2) {
myFunction(passvar1, passvar2); // 'passvar1', 'passvar2' passed by value
}
// end function loop() *****//
And btw., this code sample is NOT compiling successfully in the IDE v2.3.6
That sort of construct (it is actually varargs) is for command line invocation of a conventional C program on a mainframe computer. It also applies to smaller computers all the way down to a PC, but only under DOS (maybe?).
If you need to pass data into a program at run time there are many options. Today a web interface is often used but a preferences approach is also common. I am leaving out any sort of file system but do think a web interface to an eeprom storage might be an ok choice. There are also other memory types like fram to replace eeprom and for some boards a neat trick is a file loaded at startup via the Tools menu. (that last one is a very hazy memory)
There is no advantage as the former is impossible. If you want to modify variables in the setup() function and have them available in the loop() function, then they must be global.