Go Down

Topic: Communication with the PC problem! (Read 317 times) previous topic - next topic

sina92

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.


Code: [Select]
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!

billroy

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

-br

PaulS

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.

UKHeliBob

There is at least one fundamental flaw in your program.  This line
Code: [Select]
  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.
Code: [Select]
    int val = Serial.read() - '0';
Is that going to work I wonder ?
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

zoomkat

Very simple LED on/off via the serial monitor.

Code: [Select]

// 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="";
  }
}

Google forum search: Use Google Advanced Search and use Http://forum.arduino.cc/index in the "site or domain:" box.

sina92

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!

Go Up