Sub topic 11
Troubleshooting a UART Link
This chapter assumes you know the UART frame layout (start bit, data bits, optional parity, stop bit), how baud rate sets the bit time, the Arduino Serial API, and the receive buffer. It also assumes you know the basics of TTL, RS-232 and RS-485 levels. Here you will turn those pieces into a repeatable debugging method.
A Method: Work from the Wire Upward
Most UART faults fall into one of four layers. Check them in this order, because each layer depends on the one below it.
- Physical: wiring, ground, voltage levels, power.
- Frame: baud rate, data bits, parity, stop bits.
- Buffer: bytes arrive correctly but are lost before your code reads them.
- Message: bytes arrive intact but your parser misreads them.
Changing several things at once hides the cause. Change one thing, test, and note the result.
Symptom: Nothing Arrives
If no bytes appear, the signal is not reaching the receiver or the receiver is not listening.
Check the Crossing
A UART link connects the transmit pin (TX) of one device to the receive pin (RX) of the other. Straight-through connections (TX to TX) are the most common wiring error. If you swap the two wires and the link starts working, that was the fault.
With a USB-serial adapter, remember that the labels describe the adapter's point of view. The adapter's TX goes to your board's RX.
Check the Common Ground
Both devices need a shared ground. Without it, the receiver has no reference for what counts as HIGH or LOW. Symptoms of a missing ground include random garbage, data that works only when you touch the board, or a link that works only when both devices share a USB hub.
Check the Voltage Levels
Confirm that both sides use the same logic level.
- A 5 V board driving a 3.3 V device's RX pin can damage it. Use a level shifter or a resistor divider on that line.
- A 3.3 V TX into a 5 V Arduino RX usually works, but check the receiver's input threshold in its datasheet.
- RS-232 uses about ±3 V to ±15 V and inverts the logic. Never connect it directly to a TTL pin. Use a transceiver chip such as a MAX232 type.
- RS-485 is differential and half-duplex. It needs a transceiver, and the driver-enable line must be switched correctly.
A multimeter is useful here. An idle TTL UART line sits HIGH. If an idle line reads 0 V, the line is held low, the device is off, or the wire is not connected.
Check for Pin Conflicts on the Arduino
On an Uno, the hardware UART uses pins 0 and 1, and the same UART talks to the USB chip. If a wire is connected to pin 0 while you upload, the upload can fail. A device on pins 0 and 1 can also corrupt what the Serial Monitor shows. Disconnect the external device during upload, or use a second serial port.
Confirm Each Direction Separately
Use the echo sketch from the Arduino Serial API chapter to test one direction at a time.
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
int b = Serial.read();
Serial.write(b);
}
}If you type a character and nothing returns, either the receive path or the transmit path is broken. A loopback test narrows it down. Connect TX to RX on the same board (disconnect anything else first) and send bytes. If you receive what you sent, the UART and sketch are fine and the fault lies in the cable or the other device.
Symptom: Garbled Text
Readable-looking but wrong characters, such as âÿ or ????, mean that bytes arrive but are sampled at the wrong times. This is almost always a frame mismatch.
Baud Rate Mismatch
The receiver finds the start bit's falling edge, then samples each following bit at fixed intervals based on its own baud rate. If its rate differs from the sender's, the sampling points drift across the bit boundaries.
At 9600 baud, one bit lasts about 104 µs. A frame of 10 bits takes about 1.04 ms. The receiver must stay within roughly half a bit of the correct position by the last sampled bit. That leaves a tolerance of about ±5% in the best case, and in practice you should stay within 2% to 3%.
Typical causes:
- The Serial Monitor is set to a different rate than
Serial.begin(). - The device was configured at a different rate earlier and kept it (GPS modules, Bluetooth modules and many sensors have a factory default that may not be 9600).
- The clock on a board is inaccurate. Boards with a ceramic resonator are less accurate than those with a crystal. Some baud rates, such as 115200 on a 16 MHz AVR, have a rounding error of a few percent that can fail with a poorly matched partner. A rate such as 57600 or 9600 has a smaller error.
- An internal RC oscillator on a small microcontroller drifts with temperature.
If you do not know the device's rate, try the common ones in turn: 9600, 19200, 38400, 57600, 115200. Once the output turns into readable text, you have found it.
Frame Format Mismatch
A match on baud rate is not enough. The data bits, parity and stop bits must also match.
| Mismatch | Typical result |
|---|---|
| Parity on one side only | Occasional or constant errors; some characters correct |
| 7 data bits vs 8 | Characters above 127 wrong, or all characters shifted |
| 1 stop bit vs 2 | Often works, because the extra stop bit looks like idle time |
| Inverted polarity (RS-232 vs TTL) | Nothing sensible, or constant garbage |
Set the format explicitly on both sides instead of relying on defaults.
void setup() {
Serial.begin(115200, SERIAL_8E1);
}
void loop() {
}This uses 8 data bits, even parity and 1 stop bit. The default is SERIAL_8N1.
Binary Data in a Text Monitor
If you send raw bytes with Serial.write(), the Serial Monitor shows them as characters. A byte value of 65 appears as A, and values that are not printable appear as symbols. That is not a fault. Use Serial.print(value, HEX) while debugging, or a terminal that shows hexadecimal.
Line Endings
If every line of output overwrites the previous one or you see blank lines, the sender and the viewer disagree about line endings. Some devices send \r\n, others \n or only \r. The Serial Monitor's line-ending setting affects what you send. Your parser should accept the variants you expect, as the line-reading sketch does by ignoring \r.
Symptom: Lost or Repeated Bytes
If the text is correct but some of it is missing, the problem is usually in the buffer layer.
Receive Buffer Overflow
The Arduino AVR core keeps incoming bytes in a 64-byte software buffer. Hardware also holds a small amount of data. If your code does not call Serial.read() quickly enough, new bytes overwrite or are dropped. You then lose data silently.
Common causes:
delay()calls inloop()that last longer than the buffer takes to fill. At 115200 baud, about 11,520 bytes per second arrive (10 bits per byte), so 64 bytes fill in under 6 ms.- Long
Serial.print()calls that block while the transmit buffer drains. - Interrupts disabled for a long time, so the UART's receive interrupt is not served. This causes an overrun in the hardware register.
- Reading only one byte per pass of
loop()while the rest ofloop()is slow.
Fixes, in order of preference:
- Remove blocking delays and use
millis()for timing. - Drain the buffer with
while (Serial.available() > 0), notif. - Lower the baud rate if the data rate is higher than your code can handle.
- Make the sender slower or add a pause between messages.
- Increase the buffer size where the core allows it, at the cost of RAM.
Transmit Buffer Blocking
Serial.print() places bytes in a transmit buffer and returns. When that buffer is full, the call waits for space. A sketch that prints a lot at a low baud rate therefore slows down. At 9600 baud, printing a 30-character line takes about 31 ms (300 bits at about 104 µs each). If your loop needs to run faster, print less, print less often, or raise the baud rate.
SoftwareSerial Limits
SoftwareSerial bit-bangs the protocol using pin-change interrupts. It has these limits:
- It is reliable only at lower rates, usually 9600 or below on a 16 MHz AVR, and sometimes up to 57600.
- It can receive on only one instance at a time.
- It disables interrupts while sending, which can cause lost bytes on a hardware UART or missed timer ticks.
- RX is limited to pins that support pin-change interrupts on that board.
If you see losses on a SoftwareSerial link, lower the rate first. If that is not enough, move the device to a hardware UART or choose a board with more of them.
Symptom: Occasional Errors on a Link That Mostly Works
Intermittent faults are harder because they depend on timing and noise.
- Noise: Long, unshielded wires near motors or relays pick up interference. Shorten the cable, twist TX and RX with ground, add a series resistor of about 100 Ω, or switch to RS-485 for long runs.
- Brown-outs: A motor or radio that draws a lot of current can pull the supply down and reset the board. The serial output then shows a repeated boot message. Give the high-current part its own supply and decoupling capacitors.
- Parity errors: If you enabled parity, the UART flags the frame as bad. Most Arduino cores discard the byte. An occasional dropped byte with parity on suggests noise.
- Framing errors: The receiver did not see a HIGH stop bit where it expected one. This usually means a baud mismatch or a break condition. A line held LOW for longer than a frame (a break) shows up as a run of zero bytes with framing errors.
- Startup glitches: Many boards pulse their TX line while resetting or booting. The first garbage byte after power-up is normal. A framed protocol with a start marker and checksum lets the receiver discard it.
Symptom: Bytes Are Correct but the Data Is Wrong
If the raw bytes are right but your program behaves incorrectly, the fault is in the message layer.
- Missing or unexpected delimiter: Your parser waits for
\nand the sender never sends one. Print the received bytes in hex to see what really arrives. - Buffer too small: A line longer than your array must be handled. The line-reading example drops extra characters instead of overflowing.
- Byte order: A 16-bit value sent low byte first is read as high byte first. Agree on the order.
- Checksum mismatch: Compute the checksum over exactly the same bytes on both sides. Decide whether the start marker and length byte are included, and document it.
- Resynchronization: After an error, a binary parser must find the next start marker. A
0x7Ebyte can also occur inside the payload, so a checksum check is needed before trusting a frame. - Mixing text and binary:
Serial.print(65)sends the two characters6and5, whileSerial.write(65)sends the single byte0x41.
A small dump routine helps while debugging.
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
int b = Serial.read();
if (b < 0x10) {
Serial.print('0');
}
Serial.print(b, HEX);
Serial.print(' ');
}
}Type Hi followed by Enter in the Serial Monitor with "Newline" selected, and you should see 48 69 A.
Tools
| Tool | What it shows | Use it when |
|---|---|---|
| Serial Monitor or terminal | Text and basic hex | Quick checks of rate and content |
| USB-serial adapter as a sniffer | Data on a line you tap | You need to see what a device sends |
| Logic analyzer with UART decoder | Exact bit timing, parity and framing flags | Baud or format is unknown, or errors are intermittent |
| Oscilloscope | Voltage levels, noise, edge shapes | Levels, ringing or noise are suspected |
| Multimeter | Idle level and continuity | Checking wires, ground and supply |
A logic analyzer is the strongest tool. Measure the width of the shortest pulse (one bit) and compute the rate: baud = 1 / bit time. A 104 µs pulse means 9600 baud. A 8.68 µs pulse means 115200 baud.
A Short Checklist
- Is power on, and do both devices share ground?
- Are TX and RX crossed, and are the levels compatible?
- Do both sides use the same baud rate, data bits, parity and stop bits?
- Does a loopback test or echo sketch work?
- Is the sketch reading fast enough, with no long blocking calls?
- Do the bytes in hex match what the protocol document says?
- Does the checksum cover the agreed bytes?
Exercise
A 5 V Arduino at 9600 baud reads data from a sensor. The text on the Serial Monitor is readable at first, but when you add delay(500) to loop(), characters go missing. The sensor sends 20 bytes every 10 ms. What is the cause, and how would you fix it?
Show answer
The sensor delivers about 2000 bytes per second, so the 64-byte receive buffer fills in about 32 ms. The 500 ms delay lets it overflow, and later bytes are dropped. At 9600 baud the link carries at most about 960 bytes per second, so the stated sender rate is also higher than the link can handle. Remove the delay and use millis() for timing, read with while (Serial.available() > 0) on every pass, and raise the baud rate (on both sides) or have the sensor send less data.
Exercise
A logic analyzer shows the shortest pulse on an unknown device's TX line is about 17.4 µs wide. What baud rate is it likely using, and which standard rate is it closest to?
Show answer
Baud = 1 / bit time = 1 / 17.4 µs, which is about 57,470. The closest standard rate is 57600 baud.