Help to exit While on serial

Hi everyone, i would like my led to blink when i write a 1 on the serial monitor, and interrupt that blink when i write a 0, here is my code:

void setup(){
pinMode(8, OUTPUT);
Serial.begin(9600);
}

void loop(){
if(Serial.available()){
int datoqueviene = Serial.parseInt();

Serial.print("Recibi: ");
Serial.println(datoqueviene, DEC);

while(datoqueviene != 0){
digitalWrite(8, HIGH);
delay(2000);
digitalWrite(8, LOW);
delay(2000);
Serial.read();
Serial.flush();

}{

digitalWrite(9,LOW);

}
}

}

Then design your program so that it does not use a while loop it that way! Waiting in a loop like that inside loop() or any function called from it is stupid in the biggest way! As is using delay() and for the same reasion!

Mark

while(datoqueviene != 0){
digitalWrite(8, HIGH);
delay(2000);
digitalWrite(8, LOW);
delay(2000);
Serial.read();
Serial.flush();

}

There's no line inside this while loop that will change datoqueviene. If it is not zero to get into that while loop then you will be in that while loop for infinity.

The line that calls Serial.read() doesn't save the result. Should that have been:

datoqueviene = Serial.read();

But that won't work because if there is nothing to read then that will be -1 which is not 0.

The call to Serial.flush() is not needed. flush is to block while outgoing serial data finishes. You're not printing anything in that while loop so you certainly don't need to call flush.

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

And there is this clever idea if you just want to check for single characters.

...R