Word Commands
Part of the Inputs section of Coddy's Arduino journey. Lesson 16 of 22.
One character per command runs out fast. Words are clearer: on, off. A word is several characters, so read the whole line at once. A piece of text is a String, and Serial.readStringUntil() reads characters until it meets the one you give it, the newline, which it throws away:
if (Serial.available() > 0) {
String command = Serial.readStringUntil('\n');
if (command == "on") {
// ...
}
}Text goes in double quotes, "on"; a single character in single quotes, 'o'.
To pick one of several commands, chain the tests with else if. The board tries them in order and runs only the first that is true; the last else catches everything else:
if (command == "on") {
// ...
} else if (command == "off") {
// ...
} else {
Serial.println("Unknown command");
}Challenge
EasyThe LED is on pin 13. Control it with words typed into the Serial monitor:
- read a whole line into a
String onturns the LED on,offturns it off- any other word prints
Unknown command
Press Run, send on, off or a word of your own from the Serial monitor, then Check.
Try it yourself
const int ledPin = 13;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
// read the line, then act on "on", "off" or anything else
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Inputs
Practice on your own: Arduino playground