Sub topic 10
Sending Commands from the Serial Monitor to the Board
Prerequisites
This chapter assumes that you can upload an Arduino sketch, use setup() and loop(), declare variables, write if statements, and open the Serial Monitor. You should also know that Serial.begin() starts communication at a chosen baud rate.
The Serial Monitor can do more than display messages. It can send characters to the Arduino through the same serial connection. The sketch checks whether data has arrived, reads it, and performs an action.
How received characters flow
Serial.available() returns the number of bytes waiting in the receive buffer. A buffer is temporary memory that holds incoming data until the sketch reads it. Serial.read() removes one byte and returns it.
This sketch uses 1 and 0 as commands for the built-in LED:
const int LED_PIN = LED_BUILTIN;
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
Serial.println(F("Send 1 to turn the LED on."));
Serial.println(F("Send 0 to turn the LED off."));
}
void loop() {
if (Serial.available() > 0) {
char command = Serial.read();
if (command == '1') {
digitalWrite(LED_PIN, HIGH);
Serial.println(F("LED on"));
} else if (command == '0') {
digitalWrite(LED_PIN, LOW);
Serial.println(F("LED off"));
} else if (command != '\n' && command != '\r') {
Serial.print(F("Unknown command: "));
Serial.println(command);
}
}
}char is a data type for one character. The comparisons use character constants such as '1', not integer values such as 1. The distinction matters because the Serial Monitor sends the character byte for the visible symbol.
Configure and test the command
- Upload the sketch.
- Open the Serial Monitor.
- Select
9600 baud, matchingSerial.begin(9600). - Choose a line-ending option, such as “Newline”.
- Send
1or0.
The LED changes state, and the Arduino sends a confirmation message. With “Newline” selected, the monitor sends the typed character followed by a newline character. The '\n' and '\r' tests ignore newline and carriage-return characters, so they do not produce unwanted error messages.
Single characters versus complete commands
The example acts immediately on one character. That is useful for simple controls. Longer commands, such as led on, require collecting characters until a line ending arrives. A line-based parser can then compare the complete text with known commands.
Read one character per loop iteration when you want the rest of the sketch to keep running. Do not wait forever for input inside a loop. A waiting loop can prevent sensors, timers, and other outputs from being processed.
Exercise
What happens when the Serial Monitor sends 1 followed by a newline?
Show answer
The sketch reads 1, turns the LED on, and prints LED on. It later reads the newline and ignores it.