I'm trying to pick up c++ through arduino, and I've gotten to the point where I'm trying to use conditions in different applications to learn how they work.
Unfortunately I've come across a situation where I notice that my knowledge is to limited, and I can't see why, even after several google searches, so I'm hoping that someone in here might be able to point me in the correct direction.
The application is a basic one: I have two LED's that I want to flash sequentially, first one, then the other. This should go on indefinitely.
I've gotten it to work with a while loop, but with an if loop it doesn't work, and only keep one LED flashing, based on what value I've set my "Counter" to be.
void setup() {
// put your setup code here, to run once:
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int Counter = 0;
if (Counter % 2 == 0) { //If "Counter" is a even number, run this segment:
digitalWrite(11, HIGH);
delay(500);
digitalWrite(11, LOW);
delay(500);
++Counter;
}
else { //If "Counter" isn't an even number, run this.
digitalWrite(12, HIGH);
delay(500);
digitalWrite(12, LOW);
delay(500);
++Counter;
}
}
Could anyone give me some help as to what's wrong with my thinking and/or code?
At the start of each loop, you're putting counter back to 0.
Move the counter variable declaration outside of the loop so it's only set to 0 once, then your counting business can proceed.
I'd also just move Counter++ (and this is the correct form, ++ after, not before) to a single instance just outside the if else, no need for two of them. You could also move the second delay from each in the same fashion.
The Counter is local variable and its lifetime is within the loop(). It is created at the beginning of the loop() and set to zero (again and again). The value is lost at the end of loop(). It has nothing with 'if'.
Make the Counter global or static:
global - move the statement "int Counter = 0" somewhere above the loop() body,
static - just add "static" before its declaration "static int Counter = 0.
Ok, I kinda suspected it, but I tried placing it in the setup side of the script earlier, but that caused issues, didn't even think about putting it outside the main "void's"
Madsvg:
Ok, I kinda suspected it, but I tried placing it in the setup side of the script earlier, but that caused issues, didn't even think about putting it outside the main "void's"
It works now, thank you for clarifying it for me.
Research the concept of "Variable Scope" for C++. That's what's causing this issue.