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!!
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();
}
}
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().