Sub topic 6
Using the Arduino Serial API
This chapter assumes you can write a basic sketch with setup() and loop(). It also assumes you know what a byte is and what HIGH and LOW mean on a pin. You should have seen the UART frame (start bit, data bits, optional parity, stop bit) and the idea of a baud rate. Here you will use the Arduino Serial object to control all of that from code.
What the Serial object is
Serial is an instance of the HardwareSerial class. It wraps the board's first hardware UART. It gives you a transmit buffer, a receive buffer, and a set of methods for configuring the port, sending data, and reading data.
On an Uno or Nano, Serial uses digital pins 0 (RX) and 1 (TX). The same pins connect to the USB-to-serial chip, which is why the Serial Monitor works with no extra wiring. It also means that anything else you wire to pins 0 and 1 can disturb uploads and Serial Monitor traffic.
Your code never touches the wire directly. It only talks to the two buffers. Chapter 7 covers the buffers in detail. Here you only need to know that they exist, because they explain several behaviors below.
Starting and stopping the port
Serial.begin(speed) configures the UART for the baud rate you give it and enables the transmitter and receiver. Call it once, normally in setup().
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
int b = Serial.read();
Serial.write(b);
}
}This sketch is an echo test. Whatever you type in the Serial Monitor comes straight back. If you see your own characters, both directions work.
The second argument to begin() sets the frame format. The default is SERIAL_8N1, which means 8 data bits, no parity and 1 stop bit.
void setup() {
Serial.begin(115200, SERIAL_8E1);
}
void loop() {
}This sets 115200 baud with 8 data bits, even parity and 1 stop bit. The constants follow the pattern SERIAL_<data bits><parity><stop bits>, where parity is N (none), E (even) or O (odd). Examples are SERIAL_7E1, SERIAL_8N2 and SERIAL_8O1. Which constants exist depends on the board, so check your core's HardwareSerial.h. The Serial Monitor in the Arduino IDE only speaks 8N1, so a sketch using another format will show garbage there. That is correct behavior, because the two ends disagree on the frame.
Serial.end() disables the UART and releases pins 0 and 1 for ordinary digital use. You rarely need it.
Choosing a baud rate
Each 8N1 byte takes 10 bit times on the wire: 1 start, 8 data and 1 stop. The maximum throughput in bytes per second is therefore the baud rate divided by 10.
| Baud rate | Bit time | Byte time | Max throughput |
|---|---|---|---|
| 9600 | about 104 µs | about 1.04 ms | 960 bytes/s |
| 57600 | about 17.4 µs | about 174 µs | 5760 bytes/s |
| 115200 | about 8.68 µs | about 86.8 µs | 11520 bytes/s |
Faster is not always better. On a 16 MHz AVR, some baud rates cannot be produced exactly, because the hardware divides the system clock by an integer. The error at 115200 is about 2.1 percent on a 16 MHz AVR. That is usually acceptable, but it eats into the tolerance of the link (roughly 3 to 5 percent total between both ends). Rates such as 9600 and 19200 have much smaller errors.
Sending data: print, println and write
Serial.print() and Serial.println() send human-readable text. Serial.write() sends raw bytes. The difference matters because the same number can mean two very different things on the wire.
void setup() {
Serial.begin(9600);
Serial.println(78); // sends the characters 7 and 8
Serial.println(78, BIN); // sends 1001110
Serial.println(78, OCT); // sends 116
Serial.println(78, HEX); // sends 4E
Serial.println(1.23456, 2); // sends 1.23
Serial.println('N'); // sends N
Serial.println("Hello"); // sends Hello
Serial.write(78); // sends one byte with value 78, which displays as N
Serial.println(); // sends just the line ending
}
void loop() {
}The table summarizes the two families.
| Call | What goes on the wire | Typical use |
|---|---|---|
| `Serial.print(78)` | Two bytes: `'7'` (0x37) and `'8'` (0x38) | Text for people or text protocols |
| `Serial.write(78)` | One byte: 0x4E | Binary protocols, echoing received bytes |
| `Serial.write(buf, len)` | `len` bytes from the array, unchanged | Binary frames |
| `Serial.write("text")` | The characters of the string, no terminator | Rarely needed, `print` does the same |
println() appends a carriage return and a line feed ("\r\n", bytes 0x0D 0x0A). The receiving program must expect that. If you parse lines, you should tolerate both \r\n and a bare \n, as the line reader in a later chapter does.
For floating-point numbers, the optional second argument is the number of decimal places. The default is 2.
Saving RAM with F()
String literals normally occupy RAM on AVR boards, which is scarce (2 KB on an Uno). Wrap constant text in F() to keep it in flash instead:
void setup() {
Serial.begin(9600);
Serial.println(F("Sensor ready"));
}
void loop() {
}F() has no effect on boards where flash is directly addressable, and it is harmless there.
Receiving data: available, read and peek
Incoming bytes are collected by the UART hardware and an interrupt handler, which places them in the receive buffer. Your sketch collects them with these methods.
Serial.available()returns the number of bytes waiting in the receive buffer.Serial.read()removes and returns the oldest byte as anint. If the buffer is empty it returns -1.Serial.peek()returns the oldest byte without removing it, or -1 if the buffer is empty.
read() returns an int rather than a char so that -1 can be told apart from the valid byte 0xFF. If you store the result in a char or byte before testing it, you lose that distinction. Always call available() first, or test the int for -1, and only then narrow it.
Here is a small command interpreter that turns the built-in LED on and off:
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
int c = Serial.read();
if (c == '1') {
digitalWrite(LED_BUILTIN, HIGH);
Serial.println(F("LED on"));
} else if (c == '0') {
digitalWrite(LED_BUILTIN, LOW);
Serial.println(F("LED off"));
}
}
}Characters other than 1 and 0, including the newline the Serial Monitor adds, fall through and are ignored. The sketch never waits for input. If no byte has arrived, loop() simply runs again.
Convenience readers and their cost
The Stream base class that Serial inherits from provides higher-level readers:
Serial.parseInt()andSerial.parseFloat()skip non-numeric characters and read a number.Serial.readBytes(buffer, length)reads up tolengthbytes into an array.Serial.readBytesUntil(terminator, buffer, length)reads until the terminator, the length limit, or a timeout.Serial.readStringUntil(terminator)returns an ArduinoString.Serial.find("text")scans the input until the given text is found.
All of these block. They wait for data until the timeout set by Serial.setTimeout(ms) expires, and the default timeout is 1000 ms. A parseInt() call at the end of input with no trailing character will therefore stall your loop for a full second. For simple tools this is fine. For a sketch that must also blink, sample sensors or run motors, it is a source of mysterious lag. Use setTimeout(10) if you must call them, or read bytes yourself without blocking. The chapter on parsing shows the second approach.
String objects allocate memory on the heap. On small AVR boards, repeated use of readStringUntil() can fragment memory and eventually crash the sketch. Prefer fixed-size character arrays for long-running programs.
Waiting for the port: flush, availableForWrite and while (!Serial)
Sending is asynchronous. Serial.print() copies bytes into the transmit buffer and returns, and the interrupt handler feeds them to the hardware at the configured baud rate. Three consequences follow.
print()can block. If the transmit buffer is full,print()waits until space appears. At 9600 baud, printing a long line takes about 1 ms per character, so a sketch that prints 100 characters in every loop pass is limited to about 10 passes per second.Serial.flush()waits for the transmission to finish. In current Arduino cores,flush()blocks until the last byte has left the UART. It does not clear the receive buffer, which is a common misconception from older versions of the API. To discard unread input, read it out:
void clearInput() {
while (Serial.available() > 0) {
Serial.read();
}
}
void setup() {
Serial.begin(9600);
Serial.println(F("Sending..."));
Serial.flush(); // wait until the text has physically been sent
clearInput(); // discard anything received so far
}
void loop() {
}Serial.availableForWrite()tells you how many bytes you can send without blocking. Check it before a large write if your loop cannot afford to stall.
On boards where Serial is a native USB port, such as the Leonardo, Micro and many 32-bit boards, the idiom while (!Serial) {} in setup() waits for the host to open the port. On an Uno-style board with a separate USB chip, Serial is always true, so the line does nothing. Do not use it in a sketch that must run without a computer attached, since on native USB boards it would wait forever.
Also note the reset behavior. On many boards, opening the Serial Monitor toggles the DTR line, which resets the board. Your sketch restarts every time you open the monitor, so early output is not lost, but state is.
Other serial ports
Boards with more than one hardware UART expose them as Serial1, Serial2 and so on. An Arduino Mega has Serial through Serial3. These objects have exactly the same API as Serial. Only the pins differ. Chapter 9 covers them and SoftwareSerial.
Common mistakes with the Serial API
- Mismatched baud rate in the Serial Monitor. Garbage characters almost always mean the monitor is set to a different rate than
begin(). - Using
print()when you meantwrite(), or the reverse. If a receiver expects the byte 65 and you sendprint(65), it receives the two characters'6'and'5'. - Storing
read()in acharorbytebefore checking for -1. A -1 stored in abytebecomes 255. - Reading without checking
available(). You will process -1 values as if they were data. - Calling
begin()repeatedly inloop(). It reinitializes the port each time and may discard buffered data. - Printing too much at a low baud rate. The loop slows to the speed of the wire.
- Leaving wires on pins 0 and 1 during upload. The bootloader uses the same UART, so a connected device can make the upload fail.
Exercise
A sketch runs Serial.begin(9600); and then calls Serial.print(200); and Serial.write(200); in two separate runs. How many bytes does each call put on the wire, and how long does the wire need to carry each one in the default frame format?
Show answer
Serial.print(200) sends three bytes, the characters '2', '0' and '0', so it needs 30 bit times, which is about 3.1 ms at 9600 baud. Serial.write(200) sends a single byte with value 200 (0xC8), which needs 10 bit times, or about 1.04 ms.
Exercise
Why does the following loop sometimes act on garbage values, and how would you fix it? byte b = Serial.read(); if (b == 'A') { digitalWrite(LED_BUILTIN, HIGH); }
Show answer
Serial.read() returns -1 when no byte is waiting, and assigning that to a byte turns it into 255. The code then treats an empty buffer as if a real byte had arrived. Fix it by testing Serial.available() > 0 before calling read(), or by storing the result in an int and checking for -1.