Sub topic 10
Sending commands from the Serial Monitor to the board
This chapter assumes you can write a sketch with setup() and loop(), and that you already call Serial.begin() and print with Serial.println(). It also assumes the Serial Monitor baud rate matches your sketch. Here the data flows the other way. You type in the Serial Monitor, and the board reads and acts on it.
How input reaches your sketch
The Serial Monitor sends each typed character as a byte over USB. The board's serial hardware receives the bytes and stores them in a receive buffer. On AVR boards such as the Uno, this buffer holds 64 bytes. Your sketch does not get a notification. It has to check the buffer and take the bytes out.
Three functions cover most input work:
| Function | What it does |
|---|---|
| `Serial.available()` | Returns the number of bytes waiting in the receive buffer. |
| `Serial.read()` | Removes and returns the first byte, or `-1` if the buffer is empty. |
| `Serial.peek()` | Returns the first byte without removing it. |
Reading a byte removes it from the buffer, so each byte can be processed only once.
Setting the line ending
At the bottom of the Serial Monitor is a line-ending dropdown. It decides what the monitor appends to everything you send:
- No line ending sends only what you typed.
- Newline appends
\n(byte 10). - Carriage return appends
\r(byte 13). - Both NL & CR appends
\r\n.
If you type 1 and send it with Newline selected, the board receives two bytes: '1' and '\n'. Sketches that ignore this extra byte are a common source of confusing output, as the next example shows.
Reading single-character commands
The simplest protocol uses one character per command. This sketch switches the LED on pin 13 and ignores the newline bytes added by the line-ending setting.
const int LED_PIN = 13;
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
Serial.println(F("Send 1 to turn the LED on, 0 to turn it off"));
}
void loop() {
if (Serial.available() > 0) {
char c = Serial.read();
if (c == '1') {
digitalWrite(LED_PIN, HIGH);
Serial.println(F("LED on"));
} else if (c == '0') {
digitalWrite(LED_PIN, LOW);
Serial.println(F("LED off"));
} else if (c != '\n' && c != '\r') {
Serial.print(F("Unknown command: "));
Serial.println(c);
}
}
}Compare '1' with 1. The character '1' has the ASCII value 49, while the number 1 is a different byte. The monitor sends characters, so compare against character literals.
The last else if is what prevents the "Unknown command" message from appearing twice for every command. Remove it, select Newline, and send 1. You will see "LED on" followed by an unknown-command line for the invisible newline.
Reading whole-line commands
Single characters run out quickly. Commands such as on, off, or blink 3 need a line-based reader. The standard approach is to collect bytes into a char array until the newline arrives, then process the complete line.
const int LED_PIN = 13;
const byte MAX_LEN = 16;
char buf[MAX_LEN];
byte len = 0;
void handleCommand(const char *cmd) {
if (strcmp(cmd, "on") == 0) {
digitalWrite(LED_PIN, HIGH);
Serial.println(F("LED on"));
} else if (strcmp(cmd, "off") == 0) {
digitalWrite(LED_PIN, LOW);
Serial.println(F("LED off"));
} else if (strncmp(cmd, "blink ", 6) == 0) {
int times = atoi(cmd + 6);
for (int i = 0; i < times; i++) {
digitalWrite(LED_PIN, HIGH);
delay(150);
digitalWrite(LED_PIN, LOW);
delay(150);
}
Serial.print(F("Blinked "));
Serial.print(times);
Serial.println(F(" times"));
} else {
Serial.print(F("Unknown command: "));
Serial.println(cmd);
}
}
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
Serial.println(F("Commands: on, off, blink N"));
}
void loop() {
while (Serial.available() > 0) {
char c = Serial.read();
if (c == '\r') {
continue; // ignore carriage returns
}
if (c == '\n') {
buf[len] = '\0'; // terminate the string
if (len > 0) {
handleCommand(buf);
}
len = 0; // start a new line
} else if (len < MAX_LEN - 1) {
buf[len++] = c; // store the byte if there is room
}
}
}Points to notice in this design:
- The sketch never waits. Each pass through
loop()takes whatever bytes have arrived and returns, so other work inloop()keeps running. (Theblinkcommand itself usesdelay(), which blocks briefly. That is acceptable for a demo.) - Skipping
'\r'makes the sketch work with Newline, Carriage return, or Both NL & CR, as long as the sender ends lines with\n. If you select Carriage return only, the line never completes. Use Newline or Both NL & CR with this sketch. - The
len < MAX_LEN - 1check leaves room for the terminating'\0'. Without it, a long line would write past the end ofbufand corrupt other variables. A line that is too long is truncated, and its extra characters are discarded. strcmpis used because comparing two char arrays with==compares addresses, not contents.
Reading numbers with parseInt
Serial.parseInt() reads characters from the buffer and returns the first integer it finds. It is shorter than writing a parser, but it has a timing behaviour that catches many people.
void setup() {
Serial.begin(9600);
Serial.println(F("Type a whole number"));
}
void loop() {
if (Serial.available() > 0) {
int value = Serial.parseInt();
Serial.print(F("Got "));
Serial.println(value);
}
}Set the line ending to Newline and send 42. The sketch prints Got 42, and then, about one second later, Got 0. The reason is that parseInt() stops at the newline but leaves it in the buffer. On the next pass, available() is greater than 0, so parseInt() is called again. It finds no digits and waits for the stream timeout (1000 ms by default). When the timeout expires, it returns 0.
You can fix this in two ways:
- Set the line ending to No line ending while testing. This is quick, but it hides the problem rather than fixing it.
- Discard the leftover byte after parsing. For example, call
Serial.read()once afterparseInt()to remove the newline.
Because 0 is both a valid number and the timeout result, parseInt() cannot tell you whether the user actually typed zero. If that matters, use the line-based reader above and validate the text yourself.
Choosing a reading method
| Method | Good for | Watch out for |
|---|---|---|
| `read()` one byte at a time | Single-letter commands, custom protocols | You must handle newlines yourself |
| Char buffer until `'\n'` | Multi-word commands, no blocking | Must check length, must terminate the string |
| `parseInt()` / `parseFloat()` | Quick numeric entry | Blocks until timeout, returns `0` on failure |
| `readStringUntil('\n')` | Short, simple sketches | Blocks until timeout, uses the heap `String` class, which can fragment memory on small boards |
For anything that runs for a long time, prefer the char buffer approach. It is predictable and uses a fixed amount of RAM.
Common errors
- Nothing happens when you send. Check that the Serial Monitor is open on the correct port and that the baud rate matches
Serial.begin(). Also confirm that the text field is the input field and that you pressed Send or Enter. - Every command is rejected. The sketch is probably comparing against text that includes a stray
'\r'or'\n'. Print the received string with markers, for exampleSerial.print('['); Serial.print(cmd); Serial.println(']');, to see invisible characters. - Commands are ignored while the sketch is busy. A long
delay()or slow code stopsloop()from reachingSerial.read(). Bytes still accumulate, but if more than 64 arrive before you read them, the newest are dropped. - Commands run twice or give an "Unknown command" extra line. The line-ending setting is adding bytes your code does not expect.
- Upload fails when the Monitor is open. On some boards the port is busy. Close the monitor, upload, then reopen it.
Exercise
You send the text blink 3 with the line ending set to Both NL & CR. Your sketch is the line-based reader above. Which bytes does the sketch end up passing to handleCommand(), and why does it not receive the \r?
Show answer
It passes the string "blink 3". The board receives the bytes for "blink 3" followed by \r and \n. The sketch skips \r with continue, so it is never stored in the buffer. When \n arrives, the sketch writes '\0' after the last stored character and calls handleCommand() with the terminated string.
Exercise
A sketch uses if (Serial.available() > 0) { int n = Serial.parseInt(); Serial.println(n); }. You send 7 with Newline selected. Why does it print 7 and then, a second later, 0? Name one way to prevent the second line.
Show answer
parseInt() returns 7 but leaves the newline byte in the receive buffer. The next pass sees available() > 0, calls parseInt() again, finds no digits, and waits for the 1000 ms timeout before returning 0. You can prevent it by reading and discarding the leftover newline after parsing, by selecting No line ending, or by switching to a line-based reader that consumes the whole line.