Serial.available() corrupted....

I am using this code to measure ultrasonic time-of-flights:

int outputPin = 12;
int val;
void setup()
{
  Serial.begin(9600);
  pinMode(outputPin, OUTPUT);
}

void loop()
{
  if (Serial.available()) {
    val = Serial.read();
    if (val == 'A' ) {
      digitalWrite(outputPin, HIGH);
    } 
    if (val == 'B' ) {
      digitalWrite(outputPin, LOW);
    }
  }
}

when 12 is HIGH ultrasound is transmitted, it is stopped when 12 is LOW. The ‘A’ and ‘B’ are sent, through Xbee, from the ultrasonic receiver side.
Now, the problem: I would like Arduino to also control motors, so I added some code to do that:

void loop() {
  if (Serial.available()) {
    val = Serial.read();
    if (val == 'A') {
      digitalWrite(outputPin, HIGH);
    } 
    if (val == 'B') {
      digitalWrite(outputPin, LOW);
    }
} 
    val0 = analogRead(inPin0); 
   if (val0 > seuil){ 
   moteur(20, true, 20, true, delayTime);   
  }if (val0 < seuil) {
  moteur(0, true, 255, false, randNumber);
  }
}

but then the serial part does not work anymore.
Should I use an interrupt?
Someone wrote somewhere that Serial.available is an interrupt by itself. Is that so?
What is the difference between “if (Serial.available())” and “while (Serial.available() > 1)”?
Thanks for your help!

but then the serial part does not work anymore

“Does not work” is not a very good description of the symptoms. What does not work?

You should put the { on the next line, and properly indent your code. It is hard to follow the logic of the program since it is hard to find where one block starts and ends.

if (val0 > seuil)
if (val0 < seuil)

These can not both be true for any value of val or seuil. The second one should be replaced with else.

If the code you added causes serial communication to stop, then the problem must be in this function:
 moteur(0, true, 255, false, randNumber);,
which you didn’t bother posting.

What is the difference between “if (Serial.available())” and “while (Serial.available() > 1)”?

Two differences. One uses an if statement. The other uses a while statement. The if block will be executed once, if there is serial data to be read. The while block will be executed as long as there is serial data to be read.

The lack of “> 0” in the if test is possible because of how C handles true or false. If Serial.available() returns a positive number, that is considered true. If it returns 0, it is considered false.

It’s not a good habit to get into, in my opinion, since it makes it appear that Serial.available() returns a boolean (true or false), rather than a number. It causes newbies to forget that Serial.available() returns the number of bytes available to read, not just whether there are bytes to be read.

Sorry about the poor presentation of my code but I do not know the rules. I am an autodidact programmer and try my best..... Anyway thanks guys for your comments.