Variable initial value not recognized

Hi all,

I'm trying to help my son with a project (he and I are both new to Arduino) and after stripping out all extraneous code there appears to be something fundamentally wrong with our Leonardo board -- essentially, in loop() the initial value of variables is not recognized properly.

Here is the code:

boolean flag;
int idx;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  flag = true;
  idx = 0;
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.print("idx=");
  Serial.println(idx);
  if ( flag )
  {
    Serial.println("resetting flag");
    flag = false;
  }
  delay(1000);
  idx++;
}

This is the output from two consecutive runs -- the second began when I uploaded the code again without clearing the monitor:

17:18:49.585 -> idx=2
17:18:50.560 -> idx=3
17:18:51.583 -> idx=4
17:18:52.565 -> idx=5
17:18:53.591 -> idx=6
17:18:54.566 -> idx=7
17:18:55.589 -> idx=8
17:18:56.566 -> idx=9
17:18:57.586 -> idx=10
17:19:05.539 -> idx=2
17:19:06.514 -> idx=3
17:19:07.546 -> idx=4
17:19:08.521 -> idx=5
17:19:09.549 -> idx=6
17:19:10.527 -> idx=7
17:19:11.551 -> idx=8
17:19:12.530 -> idx=9

Any ideas? When I run this code in the Tinkercad simulator I get the expected output.

Thanks!

You might add a little delay after begin to give the Serial port a chance to do its thing.

Or you might put

while (! Serial);

after Serial.begin().

And most defiantly add some digits to the serial speed, try 115200.

What if you print initial idx also in setup()?

Adding while (! Serial); did the trick -- thanks!

1 Like