Need help with the basics on serial control I am struggling to get my head around why this just won't work. In my simple mind this simple sketch should do as it's told. But I am obviously missing something fundamental.

If anyone could shed some light on what I am doing wrong that would be very good!

The sketch is just to control a relay by typing on or off into the serial monitor. However although it uploads, all I get is the Serial.println repeating and no action on the physical relay.

I can manage to control things over serial by using the switch, case statements but I wanted to try it using full words rather than single chars and also using IF statements etc.

Thanks in advance! 

EDIT
I just changed the string inputs to a char input and serial.readstring to just serial.read and it works with just entering a 1 or a 2 for example. So to re-ask my question - how can I get it to respond the same but using words? Thanks!

int relay=8;
String serialInput;

void setup() {
  Serial.begin(9600);
  pinMode(relay, OUTPUT);
}

void loop() {
  Serial.println("To toggle relay enter on or off");
  while (Serial.available()==0) {}
  serialInput = Serial.readString();
  if(serialInput=="on") {
    digitalWrite(relay, HIGH);
  }
  if(serialInput=="off") {
    digitalWrite(relay, LOW);
  }
}
You are assuming that Serial.readString() will magically know how long a string you meant to send, and wait until it's all there.  It doesn't guarantee that.

If your PC uses Linux or Mac, you can use Serial.readStringUntil('\n'), which will read until a line end, and send on&lt;ENTER&gt; as your command.

If you use Windows, the line endings are \r\n so it's a bit more awkward.  Build up your string piece by piece, perhaps

int relay=8;
String serialInput;

void setup() {
  Serial.begin(9600);
  pinMode(relay, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    char c = Serial.read();   // get one byte from serial buffer
    if ('\r'==c || '\n'==c) {
      // End of line - process the string
      if(serialInput=="on") {
        digitalWrite(relay, HIGH);
      } else if (serialInput=="off") {
        digitalWrite(relay, LOW);
      }
      serialInput = "";
    } else {
      serialInput += c;     // add it to readString
    }
  }
}


Brief description of how it works:

The string SerialInput starts empty.  We do the following repeatedly:


If there is a character available on the serial port, read it.
If it is not an end-of-line character, add it to the end of our string
If it IS an end-of-line character, we know we've got to the end of the line, so...


check whether it matches one of our "target" strings, and act on it if so
clear it back to an empty string