I am trying to compare a string created from characters sent over serial to a word. If the word "no" matches, led 13 should turn on, and if the word "off" matches, led 13 should turn off.
All goess right untill the comparison is made, I checked by writing back results to serial.
I just can't get it to work? Any ideas?
String inData;
String test;
int testLed = 13; // LED on pin 13
void setup()
{
Serial.begin(9600);
}
void loop(){
inData="";
if (Serial.available() > 0) {
int h=Serial.available();
h--;
for (int i=0;i<h;i++){
inData += (char)Serial.read();
}
Serial.read();
}
//print it out
if (inData == "") {
//There is no spoon!
}
else
{
Serial.println(inData);
processData();
}
delay(50); // Without delay, no data is shown in serial monitor.
}
void processData(){
String t = inData;
Serial.println("processing");
if (t == "on") {
Serial.println("light go ON");
digitalWrite(testLed, HIGH);}
if (t == "off"){
Serial.println("light be gone");
digitalWrite(testLed, LOW);}
}
if (Serial.available() > 0) {
int h=Serial.available(); // h probably == 1 at this point, unless the entire string was sent before you entered loop()
h--; // now it's 0, not that this variable is required
for (int i=0;i<h;i++){
inData += (char)Serial.read(); // so this never gets executed
}
Serial.read(); // but even if it did why read again?
}
This is bazaar, you're doing two serial.reads() based on a single available() and anyway all this will be complete long before the second char is received let alone any more of the string.
And how are you testing for the end of the transmission?
I'm quite new to this so I followed some tutorials and changed/added some stuff here and there to get it working the way it is now. I don't know how else to do it.
I have tried without h--; but then it displays the word and skips to a new line on my serial terminal.
The data i'm getting seems to be allright, it's just not comparable..
I see the exact same word I sent from my phone to the arduino in the serial terminal on my computer.
I can see that processData() is being called since my serial terminal also sends the word processing and that's all that happens...
Simple code to look for "on" and "off" to operate the board LED.
\// 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="";
}
}