String comparation

Hello!

What is wrong with my code, and when I write "Say hello" it does not respond "Hello" to the serial?

String incomingByte;
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
if (Serial.available() > 0) 
    {
        // read the incoming byte:
        incomingByte = Serial.read();
        if(incomingByte.equals("Say hello"))
            Serial.println("Hello");
    }
}

You read one single byte from the Serial line and expect that to equal the whole string "Say Hello"? One byte from serial is only one character.

Ok, and if I want to read a word, how I know when to stop reading?

alex5678:
Ok, and if I want to read a word, how I know when to stop reading?

That's the big question. The usual answer is to surround the data you're sending with markers to let the code know where the message begins and ends. Like [Say Hello] or something.

See the Serial Input Basics thread for some good reading on this topic.

First, the String class (note the capital 'S') is wasteful of memory and can fragment it. Use C strings (note lower case 's') built from char arrays instead. As to your question, Delta_G has one suggestion, here's another:

char msg[30];

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  int charsRead;

  if (Serial.available() > 0)
  {
    charsRead = Serial.readBytesUntil('\n', msg, sizeof(msg) - 1);  // Leave room for null
    msg[charsRead] = '\0';
    Serial.println(msg);
  }
}

With this code, just type a short message into the Serial monitor input textbox and press the Enter key. The newline character ('\n') marks the end of the input stream.

econjack:
With this code, just type a short message into the Serial monitor input textbox and press the Enter key. The newline character ('\n') marks the end of the input stream.

OP might have to set up serial monitor to append the newline character when he/she presses 'send'.

econjack:
First, the String class (note the capital 'S') is wasteful of memory and can fragment it. Use C strings (note lower case 's') built from char arrays instead. As to your question, Delta_G has one suggestion, here's another:

char msg[30];

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  int charsRead;

if (Serial.available() > 0)
  {
    charsRead = Serial.readBytesUntil('\n', msg, sizeof(msg) - 1);  // Leave room for null
    msg[charsRead] = '\0';
    Serial.println(msg);
  }
}




With this code, just type a short message into the Serial monitor input textbox and press the Enter key. The newline character ('\n') marks the end of the input stream.

Thank you, it worked!