I am just starting with this board and though I have programmed in the past I can't get a simple integer variable to work..
Here is a snippet of code pared down as far as I can. At the x=x+1 I get an error that "x was not declared in this context" I have looked at the reference and a few examples and can't seem to get around this simple hurdle..
void setup() {
// put your setup code here, to run once:
int x = 0;
}
void loop() {
// put your main code here, to run repeatedly:
x=x+1;
The word to search for is "scope". In your code, x has "local scope" (also called a "local variable" or "automatic variable" or "auto variable"). In this code, x has "global scope" (also called a "global variable")...
int x = 0; // Not defined inside of a function but rather in "no man's land".
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
x=x+1;
}
I knew it had to be something simple. I think my old Basic was showing and I also had the idea that void setup was where I was making it global....Have to go back and look at some examples after I know what I am looking for.
int count = 0; // this variable is global to the sketch
void setup() {
int i; // this variable is local to setup(), i.e. it doesn't exists outside setup() function
for (i = 0; i < 3; i++) {
Serial.print(i);
Serial.print(",");
Serial.println(count);
count++;
}
}
void loop() {
int i; // this is local to loop() function, it's completely unrelated to the i variable declared in setup()
for (i = 0; i < 3; i++) {
Serial.print(i);
Serial.print(",");
Serial.println(count);
count++;
}
delay(2000);
}
It should print:
0,0
1,1
2,2
0,3
1,4
2,5
0,6
1,7
2,8
etc.