Sub topic 9
Extra serial ports: hardware UARTs and SoftwareSerial
Earlier chapters covered how a UART frame is built and how the Serial API works. This chapter covers what to do when one port is not enough. It assumes you can write a basic sketch, you know what baud rate and an 8N1 frame are, and you know that TX and RX must be crossed between devices.
Why one port is often not enough
A typical project talks to several serial devices at once. You might have a GPS receiver, a Bluetooth module, a display and the USB link to your computer for debugging. Each device needs its own receive line and its own transmit line, because UART has no addressing. Two devices cannot share one RX pin unless you add extra hardware, and a single Serial port can serve only one link.
There are two ways to get more ports:
- Use more hardware UARTs, which are dedicated peripherals inside the microcontroller.
- Use SoftwareSerial, a library that imitates a UART by toggling and sampling ordinary pins in software.
The two behave very differently, and the choice affects timing, reliability and the other code in your sketch.
Hardware UARTs
A hardware UART is a block of circuitry on the chip. It shifts bits in and out at the configured baud rate and stores the received byte in a register. The CPU is involved only when a byte has finished arriving or when the transmitter needs the next byte, and an interrupt handler handles both. Your loop() code keeps running while bits are on the wire.
The number of hardware UARTs depends on the board:
| Board | Hardware serial ports | Notes |
|---|---|---|
| Uno (ATmega328P) | `Serial` on pins 0 (RX) and 1 (TX) | Shared with the USB-to-serial chip |
| Nano | `Serial` on pins 0 and 1 | Same arrangement as the Uno |
| Mega 2560 | `Serial`, `Serial1`, `Serial2`, `Serial3` | `Serial1` uses 19 (RX) and 18 (TX), `Serial2` uses 17 and 16, `Serial3` uses 15 and 14 |
| Leonardo (ATmega32U4) | `Serial` over native USB, `Serial1` on pins 0 and 1 | `Serial` is a USB virtual port with no baud rate on the wire |
Check the documentation for your exact board before wiring. Boards built on other chips differ, and some boards let you remap a UART to other pins.
Using the extra ports
The extra ports use the same API as Serial: begin(), available(), read(), write(), print() and println(). Only the object name changes. This Mega sketch passes bytes between the USB port and a device on Serial1, which is a common way to talk to a module from the Serial Monitor:
void setup() {
Serial.begin(115200);
Serial1.begin(9600);
}
void loop() {
if (Serial1.available() > 0) {
Serial.write(Serial1.read());
}
if (Serial.available() > 0) {
Serial1.write(Serial.read());
}
}Each port has its own baud rate, its own frame format and its own buffers. Here the computer link runs at 115200 baud and the module link at 9600 baud, and neither setting affects the other.
The shared-port problem on the Uno
On an Uno, the USB-to-serial chip is wired to pins 0 and 1, the same pins the hardware UART uses. Anything you connect to those pins competes with the USB link. This causes two common problems:
- Uploads fail or hang while a device is connected, because the bootloader receives your new program over the same pins.
- Debug output from
Serial.print()is sent to the device on pins 0 and 1, and also to the computer.
A device that drives its TX line into pin 0 can also corrupt the data coming from the computer. If you need the hardware port for a peripheral, disconnect it before uploading. If you also need debug output, use SoftwareSerial or a board with more UARTs.
SoftwareSerial
SoftwareSerial implements UART timing in code. For transmission, it sets the pin to the start-bit level, waits one bit time, sets each data bit in turn, then sets the stop level. For reception, a pin-change interrupt fires on the falling edge of a start bit. The library then waits to the middle of each bit and samples the pin, which builds the byte.
You create a port by constructing an object with the RX pin first and the TX pin second:
#include <SoftwareSerial.h>
SoftwareSerial sensorPort(10, 11); // RX, TX
void setup() {
Serial.begin(9600);
sensorPort.begin(9600);
}
void loop() {
if (sensorPort.available() > 0) {
Serial.write(sensorPort.read());
}
}Pin 10 is the Arduino's receive pin, so it connects to the transmit pin of the sensor. Pin 11 is the Arduino's transmit pin and connects to the sensor's receive pin. Swapping the constructor arguments is a common mistake, and it looks exactly like a wiring swap: nothing arrives.
The API matches Serial closely. You get begin(), available(), read(), peek(), write(), print() and println(). The object also has listen(), isListening() and overflow(), which exist because of the library's limits.
Timing cost
At 9600 baud one bit lasts about 104 µs, so one 10-bit frame takes about 1.04 ms. While SoftwareSerial sends or receives a byte, it holds the CPU for that whole time, and interrupts are mostly disabled. Two effects follow:
- Other interrupt-driven code is delayed.
millis()can lose ticks, servo pulses can jitter, and hardware serial bytes can be overrun if your sketch is busy sending slowly through SoftwareSerial. - Transmitting is blocking.
sensorPort.print("hello")does not return until every bit has been sent, whereasSerial.print()returns as soon as the bytes are in the transmit buffer.
At higher baud rates the bit time shrinks. At 57600 baud it is about 17 µs and at 115200 baud about 8.7 µs, which is roughly 139 clock cycles on a 16 MHz AVR. The interrupt entry alone uses a noticeable fraction of that, so reception at 115200 baud often produces errors. A practical ceiling for reliable use is 38400 baud or lower, and 9600 baud is the safe choice.
One listener at a time
A SoftwareSerial object can receive only while it is the active listener. If you create two objects, only one receives at any moment, and bytes arriving for the other are lost. You choose the active one with listen():
#include <SoftwareSerial.h>
SoftwareSerial gps(10, 11); // RX, TX
SoftwareSerial modem(8, 9); // RX, TX
bool gpsActive = true;
unsigned long lastSwitch = 0;
void setup() {
Serial.begin(9600);
gps.begin(9600);
modem.begin(9600);
gps.listen();
}
void loop() {
SoftwareSerial &port = gpsActive ? gps : modem;
while (port.available() > 0) {
Serial.write(port.read());
}
if (millis() - lastSwitch >= 2000) {
lastSwitch = millis();
gpsActive = !gpsActive;
(gpsActive ? gps : modem).listen();
}
}Calling listen() makes the other object stop listening and discards anything in its buffer. This approach works only when the devices send data at predictable times, or when you can ask a device to send on request. A device that transmits at random will lose data whenever you are listening to the other one. Transmitting from any object does not need listen().
Other limits
- Frame format. The classic AVR library supports only 8 data bits, no parity and 1 stop bit. The
SERIAL_8E1style argument is a hardware-serial feature. - Receive buffer. The buffer holds 64 bytes. If the sketch reads too slowly, bytes are dropped, and
overflow()returnstrueonce to tell you. - Pin choice. On an Uno any pin can be an RX pin. On a Mega only some pins support pin-change interrupts, such as 10, 11, 12, 13, 14, 15, 50, 51, 52, 53 and A8 to A15. On a Leonardo, usable RX pins include 8, 9, 10, 11, 14, 15 and 16. Check your board's reference.
- Full duplex. Transmit and receive cannot happen at the same time. If a byte arrives while you are transmitting, it is missed.
Comparing the options
| Property | Hardware UART | SoftwareSerial |
|---|---|---|
| CPU use | Low, interrupt per byte | High, CPU held for each bit |
| Maximum reliable speed | 1 Mbaud or more, depending on the chip | About 38400 baud |
| Frame formats | Configurable (data bits, parity, stop bits) | 8N1 only on classic AVR |
| Simultaneous ports | All at once | One receiver at a time |
| Receive buffer | 64 bytes by default on AVR | 64 bytes |
| Pins | Fixed by the chip | Most digital pins |
| Effect on `millis()` and PWM | None | Can disturb timing |
Practical decision criteria
Start from the device, not from the library.
- If your board has a spare hardware UART, use it. It costs nothing in CPU time and supports every frame format.
- If the device needs more than 38400 baud, a format other than 8N1, or sends data at random times, avoid SoftwareSerial. Move to a board with more UARTs.
- If you must use SoftwareSerial, run it at 9600 baud and keep messages short. Read bytes promptly in
loop()so the 64-byte buffer does not fill. - If you use SoftwareSerial with several devices, give each one a request and response pattern so you know when to call
listen(). - If your sketch drives servos or relies on precise
millis()timing, test with the SoftwareSerial traffic running. Do not assume it is harmless.
Both kinds of port still need the same electrical care. Connect a common ground, cross TX and RX, and match the voltage levels. A 3.3 V device connected to a 5 V transmit pin needs a level shifter or a voltage divider.
Common errors
- No data at all from SoftwareSerial. Check that the constructor order is RX then TX, that the RX pin supports pin-change interrupts on your board, and that this object is the one currently listening.
- Garbage characters. Confirm the baud rate on both sides. If it is above 38400, drop it to 9600 and test again.
- Missing bytes. Read in a loop with
while (port.available() > 0), not a singleif. Checkoverflow()to see whether the buffer filled. - Uploads failing on an Uno. Disconnect anything attached to pins 0 and 1.
- Servos twitching when serial data arrives. SoftwareSerial is masking interrupts. Move the device to a hardware UART.
Exercise
A sketch on an Uno creates SoftwareSerial a(2, 3); and SoftwareSerial b(4, 5);, calls begin(9600) on both, and calls a.listen() in setup(). Device B sends a message every few seconds, but b.available() always returns 0. Why, and how can you fix it?
Show answer
Only one SoftwareSerial object can receive at a time, and a is the active listener, so bytes arriving on pin 4 are ignored. Calling b.listen() makes b the listener, but then a stops receiving and its buffer is discarded. Either alternate listen() at times when each device is known to send, or move one device to a hardware UART so both can receive at once.
Exercise
You need to read a GPS at 9600 baud and a motor controller at 115200 baud with a custom 8E1 frame, while also printing debug text to the computer. Which board and ports would you choose, and why?
Show answer
Use a board with several hardware UARTs, such as a Mega. Put the GPS on Serial1, the motor controller on Serial2 with Serial2.begin(115200, SERIAL_8E1), and keep Serial for the USB debug link. SoftwareSerial cannot reliably run at 115200 baud and supports only 8N1, so the motor controller needs a hardware port.