Hello, I'm trying to learn about arrays and the code I'm using won't work. The error message says, "i not declared in this scope" but it looks like it is. I also added semicolons after the for function brackets even though the tutorial I'm following left them out. here is my code.
int ledArray [ ] = { 2,3,4,5,6,7,8,9 };
int delayTime = 150;
void setup() {
for(int i; i < 10 ; i++);
{
pinMode(ledArray[i], OUTPUT);
}
}
void loop() {
for(int i; i <= 7, i++);
{
digitalWrite(ledArray[i], HIGH);
delay(delayTime);
}
for(int i = 7; i >= 0; i--);
{
digitalWrite(ledArray[i], LOW);
delay (delayTime);
}
}
Lose the semicolons after the for(). It says, "do nothing". Since you didn't post the code that has the problem you mention, please post the correct code. Before you do that, please read the sticky posts at the top of the forum about how to post code (especially the part about using code tags).
i is initiating at 0, so that should be fine. The weird thing now is that the Loop isn't looping. It runs through LEDs up then down once and stops. Any idea why it wouldn't loop? here's the working code.
int ledArray [ ] = { 2,3,4,5,6,7,8,9 };
int delayTime = 150;
void setup() {
for(int i; i < 9 ; i++)
{
pinMode(ledArray[i], OUTPUT);
}
}
void loop() {
for(int i; i <= 7; i++)
{
digitalWrite(ledArray[i], HIGH);
delay(delayTime);
}
for(int i = 7; i >= 0; i--)
{
digitalWrite(ledArray[i], LOW);
delay (delayTime);
}
}
Variable “i” (unless it is global - which it isn’t) is stored on the stack as a local variable (or maybe in a register if the compiler so chooses).
Local variables are left un-initialised. They are basically junk random data left over from whatever was on the stack (or in the register) previously.
You really need to set i = 0 at the start of the for and stop assuming it happens automatically.
Sometimes you may be lucky and that is simply the case by random accident. The vast majority of times probably it will not. There certainly are no guarantees.
First I learned about the serial println debugging and did that. It looked like it was stuck int the digitalWrite...LOW part. Then when I came back here I saw more talking about declaring i as zero instead of assuming. Changed that and it's now looping properly.