Home > Enterprise >  Why when I define the variable I defined in the for loop as global, it only writes once on the seria
Why when I define the variable I defined in the for loop as global, it only writes once on the seria

Time:06-29

as you can see below, I have defined the variable that I need to define in the for loop global, and this time the for loop only worked once, even though it was inside the void loop. Could you tell me why?

char i = 'A';

void setup() {
    Serial.begin(9600);
}

void loop() {
    for ( ; i <= 'Z'; i  )
        Serial.print(i);
    delay(500);
}

CodePudding user response:

Since i is a global variable, it's value persists through each call to loop().

First time loop() is called:

void loop() {
    // i == 'A', it's initial value
    for ( ; i <= 'Z'; i  )
        Serial.print(i);
    // Now, i == '[' because of i   in the loop
    delay(500);
}

Second time loop() is called:

void loop() {
    // i == '[', it's value from before, when loop finished the first time
    for ( ; i <= 'Z'; i  )
        Serial.print(i);
    // i == '[' because the loop is not entered because `[` is not lte `Z`
    delay(500);
}

And i stays equal to '[' since it does not get reset anywhere. You can reset it in the loop each time:

for (i = 'A'; i <= 'Z'; i  )

In your code, there is no reason I can see to make i global, so you can just declare it locally:

for (char i = 'A'; i <= 'Z'; i  )
  • Related