Problem in the code of using serial communication

Hi. I was just working with the serial communication of Arduino UNO. If I press '1' , the LED on pin 13 will light and if I press '0' it will be off. What I didn't understand is that, if I put " Serial.read() - '0' == 0"
instead of the variable " val " in the condition of " else if " , it doesn't work. It prints " Invalid " even I press '0'.
Another problem is if I input multiple characters other than '1' or '0' at a time , monitor should have printed " Invalid " just once as I have used " Serial.flush () ", but it shows the message multiple times (equal to the number of characters).

The code is given below :

int LEDPIN = 13;

void setup()
{
Serial.begin(9600);
pinMode(LEDPIN,OUTPUT);
}
void loop()
{
while(Serial.available()==0);
int val = Serial.read()-'0';
if ( val == 1)
{
Serial.println("Led is ON");
digitalWrite(LEDPIN,HIGH);
}
else if (val == 0)
{
Serial.println("Led is OFF");
digitalWrite(LEDPIN,LOW);
}
else
{
Serial.println("Invalid");
}
Serial.flush();
}

serial_comm.ino (410 Bytes)

What's wrong with just posting the code?
It's not like you're going to bust a limit.

int LEDPIN = 13;

void setup()
{
  Serial.begin(9600);
  pinMode(LEDPIN,OUTPUT);
}
void loop()
{
  while(Serial.available()==0);
  int val = Serial.read()-'0';
  if ( val == 1)
  {
    Serial.println("Led is ON");
    digitalWrite(LEDPIN,HIGH);
  }
  else if (val == 0)
  {
    Serial.println("Led is OFF");
    digitalWrite(LEDPIN,LOW);
  }
  else 
  {
    Serial.println("Invalid");
  }
  Serial.flush();
}

It prints " Invalid " even I press '0'.

What is the serial monitor line-ending setting?

What do you think "Serial.flush()" does?

Nasim:
Hi. I was just working with the serial communication of Arduino UNO. If I press '1' , the LED on pin 13 will light and if I press '0' it will be off. What I didn't understand is that, if I put " Serial.read() - '0' == 0"
instead of the variable " val " in the condition of " else if " , it doesn't work. It prints " Invalid " even I press '0'.

By the time you get to your else if statement, attempting another read from serial will not give you the character that you've already read above. ( it's not in the Serial buffer anymore, once you've read it )

Another problem is if I input multiple characters other than '1' or '0' at a time , monitor should have printed " Invalid " just once as I have used " Serial.flush () "

What good do you think blocking until all outgoing serial data has been sent (THAT is what flush() does) will do?

The examples in serial input basics are simple reliable ways to receive data.

...R

No line ending was set in the serial monitor