Sub topic 2
Starting serial with Serial.begin and choosing a baud rate
This chapter assumes you can write a basic sketch with setup() and loop(), and that you can upload it from the Arduino IDE. You should also be comfortable with variables, data types and if statements in C/C++. Here you will learn what Serial.begin() does, what the baud rate means, how to pick one, and why a wrong choice produces garbage on screen.
What Serial.begin does
Serial is an object provided by the Arduino core. It wraps the board's UART, the hardware block that sends and receives data one bit at a time over a pair of wires. Until you call Serial.begin(), that hardware is off. Anything you print before then is lost or never sent.
Serial.begin() does three things:
- It sets the speed, in bits per second, at which the UART sends and receives.
- It sets the frame format, which is how each byte is wrapped for transmission.
- It enables the transmit and receive circuits and allocates the software buffers behind them.
Call it once, at the start of setup():
void setup() {
Serial.begin(9600);
Serial.println(F("Setup complete"));
}
void loop() {
Serial.println(millis());
delay(1000);
}Calling Serial.begin() inside loop() is a common mistake. It re-initializes the port on every pass, which can drop buffered data and wastes time.
What baud means
Baud is the number of signal changes per second on the line. On a plain UART link each change carries one bit, so a baud rate of 9600 means 9600 bits per second. Both ends must agree on this number in advance, because there is no separate clock wire. The receiver watches for the start of a frame, then samples the line at the rate it expects. If its expected rate differs from the sender's, the samples land in the wrong places and the bytes decode as the wrong characters.
The default frame format is called 8N1:
- 1 start bit, which is always low and marks the beginning of a frame.
- 8 data bits.
- No parity bit.
- 1 stop bit, which is always high.
That is 10 bits on the wire for every byte of data. Divide the baud rate by 10 to get the maximum number of bytes per second.
Common baud rates and what they cost
The Arduino documentation uses 9600 in most examples, and it is a safe default. Faster rates move more data and keep your sketch from waiting on the port.
| Baud rate | Bytes per second (8N1) | Time per byte | Time for 100 bytes |
|---|---|---|---|
| 9600 | 960 | about 1.04 ms | about 104 ms |
| 19200 | 1920 | about 0.52 ms | about 52 ms |
| 57600 | 5760 | about 0.17 ms | about 17 ms |
| 115200 | 11520 | about 0.087 ms | about 8.7 ms |
These numbers matter because a UART is much slower than the CPU. A 16 MHz AVR core executes thousands of instructions in the time it takes to send one character at 9600 baud. When the transmit buffer fills, Serial.print() waits until space is free, so printing too much at a low baud rate slows your whole sketch. A later chapter covers this in detail.
Matching the Serial Monitor
The Serial Monitor has its own baud setting, a dropdown at the bottom right of its panel. It must match the number in your Serial.begin() call. If you write Serial.begin(115200), set the dropdown to 115200 baud. Changing the dropdown does not change the board, and changing the sketch does not change the dropdown. You are responsible for keeping both in step.
If they differ, the symptoms are fairly consistent:
- Random symbols, boxes or question marks usually mean the rates are mismatched.
- Output that looks nearly correct with a few wrong characters often means the rates are close but not equal, or the line has noise.
- Nothing at all more often points to a port or board problem, not a baud problem.
When you see garbage, check the dropdown first. It is the cheapest fix.
Choosing a rate
For most debugging, pick from this short list:
- Use 9600 when you print short messages a few times per second, or when you follow a tutorial that uses it.
- Use 115200 when you print many values quickly, stream data to a plotter, or want printing to cost less time.
- Use a matching rate when talking to another device, such as a GPS module or Bluetooth board. That device's datasheet sets the rate, not you.
A higher rate is not always better. At high speeds a long or poor-quality cable, or a board with an inexact clock, can introduce errors. The next section explains why.
Rate accuracy on AVR boards
The UART on an AVR board such as the Uno divides the 16 MHz system clock to make its bit clock. The divisor must be a whole number, so some baud rates cannot be produced exactly. At 9600 the error is small enough to ignore. At 115200 the error is about 2 percent in the normal mode, which is still usually within tolerance, though it leaves less margin than lower rates. Rates such as 250000 divide the clock evenly and have no error on a 16 MHz AVR, but some desktop serial tools do not offer them in a menu.
The optional config argument
Serial.begin() takes an optional second argument that sets the frame format. The default is SERIAL_8N1. Other values change the number of data bits, the parity (N for none, E for even, O for odd) and the number of stop bits:
void setup() {
Serial.begin(9600, SERIAL_8E1); // 8 data bits, even parity, 1 stop bit
Serial.println(F("Using 8E1"));
}
void loop() {
}You rarely need this when talking to the Serial Monitor, which uses 8N1. It matters when you connect to equipment that insists on parity. Both ends must use the same format as well as the same baud rate.
Boards with native USB
Not every board has a separate USB-serial chip. On an Uno, a second chip converts between the UART and USB, and the baud rate you set in Serial.begin() is the real rate on the UART wires. On boards with native USB, such as the Leonardo, Micro and many 32-bit boards, Serial is a virtual port carried directly over USB. Two differences follow:
- The baud rate in
Serial.begin()has no effect on the USB transfer speed, but you should still write it, because it keeps the code portable. - The port may not be open when
setup()runs, so early prints can disappear.
A common fix is to wait for the port to open, with a time limit so the sketch still runs when no monitor is attached:
void setup() {
Serial.begin(115200);
unsigned long start = millis();
while (!Serial && millis() - start < 3000) {
// wait up to 3 seconds for the Serial Monitor to connect
}
Serial.println(F("Ready"));
}
void loop() {
}On an Uno the expression Serial is always true, so the loop exits immediately and the code behaves normally.
Opening a second port and stopping serial
Boards with more than one UART expose extra objects named Serial1, Serial2 and so on. These use separate pins and take the same arguments, for example Serial1.begin(9600). You can use one to talk to a GPS module while Serial keeps printing to your computer.
Serial.end() turns the port off and releases its pins for normal use. You will seldom need it, but it is the way to get pins 0 and 1 back as ordinary digital pins after you finish with serial.
Checklist for a first serial sketch
- Put
Serial.begin(rate)as the first line ofsetup(). - Open the Serial Monitor after the upload finishes.
- Set the dropdown to the same rate.
- Expect the board to reset when the monitor opens, on boards that reset when the port is opened. Your
setup()runs again, so you will see its output. - If you see garbage, correct the dropdown before changing any code.
Exercise
A sketch calls Serial.begin(9600) with the default 8N1 format and then runs Serial.println("Temperature is 23.5 C") once. The text is 21 characters. About how many milliseconds does the UART need to send that line, and what would the time be at 115200 baud? Remember that println adds a carriage return and a newline.
Show answer
println adds 2 bytes (CR and LF), so 23 bytes are sent. Each byte takes 10 bits on the wire in 8N1, so 230 bits. At 9600 baud that is 230 / 9600 = about 0.024 s, or 24 ms. At 115200 baud it is 230 / 115200 = about 2 ms.
Exercise
You upload a sketch that calls Serial.begin(115200). The Serial Monitor shows rows of random symbols. List the first thing you check, and explain why changing the sketch to Serial.begin(9600) is not the right fix if the dropdown already says 9600.
Show answer
Check that the Serial Monitor dropdown is set to 115200 baud. The symbols appear because the monitor samples the line at a different rate than the board sends. If the dropdown says 9600 and the sketch says 115200, they disagree. Changing the sketch to 9600 would also work, but only if you re-upload it. The simplest fix is to set the dropdown to 115200, and either side can be changed as long as both values end up equal.