why wont this work?!

will somebody please help! I have started to create a simple Serial monitor project and to start it off you have to enter a password. I have done this hundreds of times and yet it is not working. it is simple, the Serial monitor asks for a password, and if you put in the right password (123) then a green light will light up. but for some reason it says that it is the wrong password and nothing lights up. I know that it is working and the the light is hooked up properly by doing simple digital writes but it still does not work, even the else statement works but the code thinks I am entering in something different. and I never receive any error codes it just does not work! what is going on!

int GPin1 = 13;

String msg1 = "Enter password to start";
String password;

int dt1 = 1000;
void setup() {
  pinMode (GPin1, OUTPUT);
  
  Serial.begin (9600);
}
void loop() {
  Serial.println (msg1);
  Serial.println ();
  while (Serial.available () ==0) {
    
  }
  password=Serial.readString();
  Serial.println (password);
  if (password =="123") {
    digitalWrite (GPin1, HIGH);
    Serial.println ("***");
    Serial.println ();
    delay (dt1);
    digitalWrite (GPin1, LOW);
  }
  else {
    Serial.println ("wrong password");
    Serial.println ();
  }
}

password_LED.ino (565 Bytes)

readString() doesn't know when to stop reading, so it has a timeout for that. It probably times out before getting all the characters you're inputting. Try readStringUntil(), looking for an end of line character.

What is the line endings set to in serial monitor? Set line endings to None and try your code.

Neither "123\r\n" or "123\n" are equal to "123".

Use Serial.readStringUntil('\n') or Serial.readStringUntil('\r\n'), depending on setting on Serial Monitor. See Serial.readStringUntil() example

Really the better thing is to not use Strings at all. Use of the String class can cause memory problems. See the evils of strings.

Robin2's serial input basics tutorial shows how to read serial data into null terminated character arrays (strings) with non blocking code (readString() and readStringUntil() are blocking functions).

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.