So you got to output text. That's fun, I guess. Now what about reading input?
Let's build off of the code from the last example, and add the ability to print whatever we input verbatim.
Code (C++)
void setup() {
Serial.begin(115200);
Serial.println("Hello World!");
}
void loop() {
if (Serial && (Serial.available() > 0)) {
String input = Serial.readString();
Serial.println(input);
}
}
Breaking it down
The lines you want to pay attention to are here:
Code (C++)
String input = Serial.readString();
Serial.println(input);
Yes... the string class in the Arduino library starts with a capital "S". That is bound to confuse someone.
Anyways...
Serial.readString (
Documentation) is used to read data from the Serial Monitor, and put it in a String. And if you remember from the previous section,
Serial.println will print the contents of that String to the output module of the Serial Monitor.
Why "if (Serial && (Serial.available() > 0)) {
"?
Well try running it without those and see what happens.
Ahem, remember this is going on in the "loop()" function. Think of it as a
while(1)
.
As it turns out, there are a few checks that we would have to do before we get to actually accept input. Otherwise, it will constantly try to read from the Serial Monitor and print blank lines. The
Serial.available (
Documentation) function tells us how many bytes are available for reading from the Serial port (the input). If it is 0, the user clearly didn't input anything, so why waste our time trying to read an empty string and then print a blank line? As for the statement before
Serial.available()
...
if (Serial) (
Documentation) simply checks if the Serial port (input...) is even ready for input. If that fails, you have no reason to read input as it will fail too.
What if I wanted to convert that string to an Int?
Take a look at
toInt()'s documentation
here. Basically do something like this:
Code (C++)
String num_txt = "1234";
int num = num_txt.toInt();
Note: This function acts like
atoi()
(it is probably a wrapper for that function). The function will scan the String from left-to-right and stop when a non-number character is hit. This means that if the string does not contain a valid number at the start, it will return "0". So "a1234" will return "0". However, if the string was "12a34", then it would return "12".