Howdy,
I'm trying to get my led to blink when the Serial input is "ha". Turn on when "a", and off when "b".
I am able to get it to turn on and off with "a" and "b", but when it comes to "ha" it doesn't work always. It has to do (I assume) with the fact that the "ha" string is more than 1 character, and my String isn't putting the two characters into the same string all the time.
Here's my code:
/*
based on: Arduino Turn LED On/Off using Serial Commands //// Created April 22, 2015 - Hammad Tariq, Incubator (Pakistan)
*/
boolean printToSerial;
// These are for the serial input
char character;
String inputString = "";
void setup() // run once, when the sketch starts
{
Serial.begin(9600); // set the baud rate to 9600, same should be of your Serial Monitor
pinMode(7, OUTPUT);
printToSerial = true;
}
void loop()
{
printToSerial = true;
getString();
if ((inputString != "")){ // && (printToSerial == true)){
Serial.println("getString = " + inputString);
printToSerial = false;
}
if (inputString == "a") { //in case of 'a' turn the LED on
digitalWrite(7, HIGH);
} else if (inputString == "b") { //incase of 'b' turn the LED off
digitalWrite(7, LOW);
} else if (inputString == "ha") {
digitalWrite(7, HIGH);
delay(500);
digitalWrite(7, LOW);
delay(500);
Serial.println("Blink");
}
inputString = "";
}
void getString(){
while(Serial.available()){
character = Serial.read();
inputString.concat(character);
}
}
When I type "a" and "b", the light does as expected.
It's when I type more than one character, that it doesn't work right. Usually, it just prints each character, one per line. I copy/pasted "bbbbb", and get this result in the Serial Monitor:
getString = b
getString = b
getString = b
...
getString = b
getString = b
...
getString = b
getString = b
getString = b
getString = bbbbb
How come it's only sometimes getting the multiple characters and others not?
Is it due to how I'm emptying "inputString"?
Thanks for any ideas!
edit: Okay, so I'm on to something - it's likely due to the fact I don't know where to empty my "inputString". I moved the if (Serial.available() > 0) out of the getString part, and wrapped it around the loop's calling of it.
Now, I can get strings, such as "abbab" and "haha"...only, now each time I type into the Serial Monitor, it just adds onto the string, instead of making it a new one. Hm...