Are there any other methods for passing variables?
this seems to be a very simple question, but it will get quite complex.
Basically there are two options
- function call by value
- function call by reference
The first one is what you know currently, you pass a value into a local variable to the function.
You will have a copy of your value during the existance of the function.
it will ocupy additional RAM from the stack.
In the second option you pass a reference to the existing variable. The value will not be duplicated - you just hand over a "reference" to your variable (it will ocupy some memory, because the controller needs some kind of adressing to find your referenced variable, but it will not be a 1:1 copy).
I'm not a native speaker and I guess you can easily google for the differences of the two options and you will get an even better explanation for them.
When you are dealing about "global" or local try to keep your variables as narrow scoped as possible like already proposed.
If you need a variable only in loop, declare it in the loop.
If you need it within an if, declare it under the if.
Be carefull if you need variables in a switch/case case. It's pain in the a.. and I prefer to declare it outside of the switch.
Lot of global variables in Arduino beginner project don't need to be globally.
E.g. if you need a variable only within a function you can declare it in the function.
Local variables will be destroyed when the function ends.
If you want to keep value of the variable alive AFTER the function has ended for the next function call use the keyword static. E.g. an "uint32_t previousMillis" could be a static variable within a function if it is only needed for timekeeping in that function.
Declaring a variable globally, static or locally has a big impact on your memory usage and the remaining free memory. As you are using microcontrollers with a very limited amount of free memory, always care about the least possible static data usage.
If you want to get some first insights how an ATmega handles variables and how they effect RAM usage, read this beginner friendly
article Optimizing SRAM | Memories of an Arduino | Adafruit Learning System.
If this was not enough, try this article, but concentrate on the Arduino parts Memory and the Arduino | Electronics | Sumida Crossing