Serial print integer with increment

Hi I was trying to print integers 1 to 3 and then stop however the Serial monitor keeps printing 1s forever.

The code looks like this:

/*
serial print integer with increment
*/

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

void loop() {
    int i = 1;
    Serial.print(i);
    delay(1000);
    if (i == 3){
      while(true);
    }
    i++;
}

The board is a Nano 33 BLE Sense. Any ideas? Thanks

This is a simple error because you do not fully understand the Arduino logic.

  • loop() runs forever over and over
  • your 1st statement is "int i = 1;" - that sets i to 0 at each (!) loop() run.

The statement "int i = 1;" must be placed outside loop(), e.g. in setup(). Then i is initialised one times and loop() runs as you expected.

 int i = 1;

That reinitializes i to 1 every time through loop(), so...

You could make it a static local variable:

static int i = 1;

that way it will hold its value loop() to loop() (not reinitialized).

Or make i a global variable and not local in scope.

that sets i to 0 at each (!) loop() run.

Sets i to 1.

The statement "int i = 1;" must be placed outside loop(), e.g. in setup().

Outside of loop() (in global scope), yes. In setup(), no, because when setup() finishes i would go out of scope (no longer exist).

The simple way:

void setup()
{
  Serial.begin(9600);
  
  for (int i = 1; i < 4; i++)
  {
    Serial.print(i);
    delay(1000);
  }
}


void loop() {}