Why is Serial.println(count) necessary?

I have the following program which takes an input (12 or 13), toggles the LED on the appropriate port and returns a returnmessage.

However, if I remove the Serial.println(count) after my if-part, it doesn’t output or do anything, but if it’s there, everything works perfect, anyone who has an explanation?

static boolean state[14];
static int pos;
static int fade;
int count;
int LED;

void setup() {

pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
Serial.begin(9600);
pos = 0;
LED = 12;
count = 0;
state[12] = false;
state[13] = false;

}

void loop() {
count = 0;
pos = 0;
while (Serial.available() > 0) {

char ch = Serial.read();

if (ch>‘0’ && ch<= ‘9’){
pos = pos * 10 + ch - ‘0’;
count++;
}

Serial.println(count);
}
if (count==2){
state[pos] = !state[pos];
digitalWrite(pos, state[pos]);
Serial.write(“Pin #: “);
Serial.print(pos);
if (state[pos]) Serial.write(” on”);
if (!state[pos]) Serial.write(" off");
Serial.write(".");
}
//count = 0;
//pos = 0;
}

The transmission of serial is relatively slow. Your code for reading the serial data assumes that it is all ready to be read.

When it isn't, the Serial.println() statement adds a delay to the while loop, while data is sent out. This small delay is enough to allow the rest of the data to arrive.

If the data being sent included an end of packet marker, and the code on the Arduino were to read until that end of packet marker arrived, the problem you are seeing could be avoided.

A small delay() will also mask the problem, giving time for the data to arrive. How long? Depends on the baud rate, and what is sending the data. Typically, about 10 milliseconds per character.

only after the LED is set/cleared the value of pos should be set to 0.

if (count==2) { ... pos = 0; }