how to clear serial after reading?

OK,

After much mesing about, well actually hacking of other scripts! I managed to knock up a tiny c# .Net app that sends the word CLOSE over USB to the Arduino. I have the Arduino turn on pin 13, wait a second, then turn it off. The problem is that it keeps turning back on! I assume it's because something is not getting cleared down inside the loop?

Here is the sketch..

char character;
String message = "";

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

void loop(){
//Serial data from PC
while(Serial.available()) {
character = Serial.read();
message.concat(character);
}
if (message == "CLOSE") {
Serial.println(message);
digitalWrite(13, HIGH);
delay (1000);
digitalWrite (13, LOW);
delay (1000);
String message = "";
}
Serial.flush();
}

Do I need to somehow clear down the serial buffer after reading from it?
Any help would be great - I', completely new to all this so go easy on a newbie!! :slight_smile:

I'm a newbie too, so no gauarantee that this will work for you, but I had a similar problem recently, and after a helpful tip by another forum member I solved it by including the following code within the void loop():

// Pause for a minute before looping again. Keep draining serial buffer.
unsigned long pause = 3600000;
unsigned long timeNow = millis();
unsigned long pauseEnd = timeNow + pause;
while (millis() < pauseEnd)
{
if (Serial.available())
{
Serial.read();
}
}

Let us know whether it helped!

The problem is that it keeps turning back on! I assume it's because something is not getting cleared down inside the loop?

Yes, something is not getting cleared. That something is the String instance message. You are creating a new instance called message that you set to an empty string. That does nothing to the other instance, that you check next time through loop().

Ah, yes, I see it now:-) :slight_smile: many thanks, I knew it was something silly!

PaulS, It's not my thread, but would you mind explaining that a little more fully? I didn't get it at all. Sorry to be dense.

char character;
String message = "";   // <----- first variable
...
   if (message == "CLOSE") {
      Serial.println(message);
                digitalWrite(13, HIGH);
                delay (1000);
                digitalWrite (13, LOW);
                delay (1000);
                String message = ""; // <----- second variable
   }

By putting String on that "second" line you are creating a new variable and clearing it. Not clearing the first variable.

Ah yes, I see that now. Very many thanks!