Basically what I'm expecting to see at the terminal is:
1
2
3
4
5
6
...etc
Instead (which is obvious to you guys that know what's going on) I get:
0
0
0
0
0
0
Now I know that it would work as such:
void loop...
counter = increment(counter);
...
int increment(int tempVar){
tempVar++;
return tempVar;
}
...but basically, I want to know if it's possible to pass a global variable as an argument to a function and have that function manipulate it internally with a local variable and store the result of the manipulated internal variable into the global variable without referring to the global variable directly in said function. My programming experience is limited to bits and pieces of various languages, but I'm pretty sure I've done this before in another language. Or am I being daft? :)
There's no need to pass a global to a function.
If you want to manipulate any variable, you might want to look at references.
http://arduino.cc/en/Reference/Pointer
I want to know if it's possible to pass a global variable as an argument to a function and have that function manipulate it internally with a local variable and store the result of the manipulated internal variable into the global variable without referring to the global variable directly in said function.
Yes, it is possible. The global variable needs to be passed by reference:
void increment(int [glow]&[/glow]tempVar)
You may need to add the function prototype. The IDE has problems with functions with reference arguments. Add this before setup().
int counter = 0;
void setup(){
Serial.begin(9600);
}
void loop(){
increment(&counter); //pass a pointer to counter as the actual parameter
Serial.println(counter);
delay(100);
}
void increment(int *tempVar){ //formal parameter is a pointer to an int
(*tempVar)++; // increment the contents of the pointer i.e. counter
}
I figured it might be something with pointers (a topic I avoided in my intro to C course at varsity... ignorance is bliss lol). I understand the concept, just never used them. Guess it's time to learn :)