Hello everyone! I'm prompted with creating a program that reads a user entered string, sees if it matches a predefined string, and if it does then it will light a green light, and if it doesn't then it will light a red light. I haven't added the light related code yet since I'm trying to break this down piece by piece, but what I'm getting hasn't been successful. I'll enter the correct string (that being Rocket) and the program will recognize it as being invalid. Any and all feedback is very appreciated! Here is my code:
String enteredUser;
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
Serial.println("Please enter your username or ID: ");
while (Serial.available() == 0)
{}
enteredUser = Serial.readString();
//if (enteredUser == "Rocket")
if(Serial.readString() == "Rocket")
{ Serial.println (enteredUser);
Serial.println("Hello Rocket Raccoon");
}
else
{
Serial.println("Invalid Username");
}
}
While youâre early in the journey, consider if caSe is important in your entry⌠Rocket isnât the same as rocket.
In my code, I convert all input to lowercase before I process it (unless caSE is important.
That also makes it easier that a user doesnât have to be keyboard or case aware⌠they just roll up to the keyboard and type it any old way - the parser doesnât care.
p.s. the CR / LF really has no reason to be saved as parts of your input. Detect them if needed for execution etc, then throw them away.
Likely you are not allowing for the line ending that the monitor puts on the end of your typed String. Either you need to allow for it in the String you compare to, or turn off in the monitor.
Thank you for your reply! I had it set to Newline, then I switched it to No line ending, though I'm just getting the "Please enter your username or ID: " after I type in "Rocket".
Thank you for your reply! Yes, I remember learning that C++ and Arduino is case sensitive, so I've been sure to enter "Rocket". Also, what does CR / LF mean and how would I go about erasing them?
Thank you for your reply! I had it previously set to Newline but switched to No line ending, though nothing changed. I had taken a course in C++ where string was introduced as data containing multiple letters so I figured that it would be the same here. Am I using the wrong data type?
The Serial Monitor and the basic String functions are pretty clunky, and you have to leave a lot of the thinking to them.
Now, Youâve seen how the Carriage Return and Line Feed characters affect your input.
If you do eventually migrate to using c-strings, youâll discover a bit more work, but a lot more flexibility with tighter code, that allows many tricks and better character handling.
While youâre still learning, get used to the basics, then get brave later!