Simple while loop question

Hello all,

I ran into something I did not understand. I simplified the code for you guys. There are two while loops in which the idea is to send character to the serial monitor for one second. The question is: Why does whileLoopA never end and whileLoopB is working?

unsigned long timeA = 0;

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

void loop() {

  while (timeA < 1000000) //whileLoopA
  {
   unsigned long timeA = micros();
   Serial.println("A");
  }

  while (micros() < 2000000) //whileLoopB
  {
    Serial.println("B");
  }
  
  Serial.println("done");
}
unsigned long timeA = micros();

This creates a new, discrete variable. So does NOT updatw the existing variable.

timeA = micros();

is how it should be.

You have assigned timeA twice , in the loop() just have

timeA = micros();

I’m unsure this is the issue , but put a print statement in the loop and see what values you get for timeA to help you debug it .

Note to self : type faster

Ah I see! Thank you for the reply. It does work now! So assigning again does not overwrite the existing timeA.

willybogard:
Ah I see! Thank you for the reply. It does work now! So assigning again does not overwrite the existing timeA.

because the timeA in the while loop is a completely different variable, due to it being in a different scope. If you tried declaring it outside the while loop, you would get a multiple definition error.