I have an Arduino Nano with a single relay board. I am printing a prompt in the serial monitor asking if the relay is off or on. When the command is received, I want it to turn it off or on. The problem I am having is that it is skipping the if statement. Even when the criteria is met, it does not implement the contents of the if statement. This is my first Arduino experience so it is probably some simple context I am missing. Any help is greatly appreciated!
(I printed the relayState variable before and after the prompt as a means of testing)
const int relayPin=8;
String relayState;
void setup() {
pinMode(relayPin, OUTPUT);
Serial.begin(9600);
digitalWrite(relayPin, HIGH);
}
void loop() {
Serial.println(relayState);
Serial.println("Do you want the relay on or off?");
while (Serial.available()==0){} //Wait for input
relayState = Serial.readString();
Serial.println(relayState);
if (relayState == "off") {
digitalWrite(relayPin, HIGH);
Serial.println("The relay is off!");
}
if (relayState=="on") {
digitalWrite(relayPin, LOW);
Serial.println("The relay is on!");
}
}