Communication with the PC problem!

Hello. I wrote some code after watching a tutorial on Youtube. Basically, I'd like to control an LED through the communication window.

However, the code does not work. Please take a look at it.

int ledPin = 5;

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


void loop(){

  while(Serial.available() == 0);

     int val = Serial.read() - '0';

if(val == 1){
  digitalWrite(ledPin, HIGH); // this doesn't executed
  Serial.println("LED ON"); // this gets executed
}
else if(val == 0){
  digitalWrite(ledPin, LOW);
  Serial.println("LED OFF"); this gets executed
}
else{
  Serial.println("ERROR!");
}

Serial.flush(); 

}

Also, the Serial.flush() doesn't work. If I type in "asd" in the window, I get three "ERROR!" lines, instead of just one.

Please help me control the LED and figure the Serial.flush() out!

Thx in advance!

It might work better if you call pinMode() in setup to set the LED pin as an output.

-br

And, you should read up on what flush() does, now. It blocks until the outgoing serial buffer is empty. Hardly useful in your situation.

There is no means of emptying the incoming serial buffer without reading everything. For good reason.

There is at least one fundamental flaw in your program. This line   while(Serial.available() == 0);checks to make sure that there is nothing in the serial input buffer and if there is nothing there it reads a byte from it.

    int val = Serial.read() - '0';

Is that going to work I wonder ?

Very simple LED on/off via the serial monitor.

// zoomkat 8-6-10 serial I/O string test
// type a string in serial monitor. then send or enter
// for IDE 0019 and later

int ledPin = 13;
String readString;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT); 
  Serial.println("serial on/off test 0021"); // so I can keep track
}

void loop() {

  while (Serial.available()) {
    delay(3);  
    char c = Serial.read();
    readString += c; 
  }

  if (readString.length() >0) {
    Serial.println(readString);

    if (readString == "on")     
    {
      digitalWrite(ledPin, HIGH);
    }
    if (readString == "off")
    {
      digitalWrite(ledPin, LOW);
    }

    readString="";
  } 
}

Thanks guys! I added "pinMode(5, OUTPUT);" & changed the first line in the loop to "while(Serial.available()){", now it works just as intended. Thx!