You don't need to. I make All my variables global, and never declare any inside of loop code.
Your code is little mixed up it seems to me. Reorganized a little and added some << notes
void loop()
{
for(j=0;j<4;j++) { // this loop sets all 4 outputs low
digitalWrite(led[j],LOW);
}
digitalWrite(led[j],HIGH); // then one output is written high - maybe j = 3 here? maybe 4?
delay(1000); // delay for a second
j++; // these 3 lines then do some pointless manipulation of j
if(j==4) // because j is set to 0 at the start of the for loop anyway.
j=0;
}
CrossRoads:
You don't need to. I make All my variables global, and never declare any inside of loop code.
Your code is little mixed up it seems to me. Reorganized a little and added some << notes
digitalWrite(led[j],HIGH); // then one output is written high - maybe j = 3 here? maybe 4?
delay(1000); // delay for a second
j++; // these 3 lines then do some pointless manipulation of j
if(j==4) // because j is set to 0 at the start of the for loop anyway.
j=0;
}
What would happen if j was 4 there? I think it'd have to be 4, in order for the test to be false. So after the for loop, it will would try to read beyond the end of the array....
My impression is that the code the OP wrote is entirely different from what he intended.
I use i or j - or if there's an obvious word that describes what the loop is counting, I use the first letter of that.
I can't see anything good coming from making them global. When do you need to know the value of that variable outside the loop when you don't already have another way of knowing what the value is? Maybe if you're expecting an interrupt while the for loop is running, and that ISR needs to know which step of the loop it's in for some reason? Are there any other situations where making it global would be of any use?
I wager that it's global in this case because he meant for that second digitalWrite() to be in the loop, but put the brace in the wrong place, and got compile error "variable was not declared in this scope", and declared it global to get it to compile.