In this tutorial, we’ll connect a Raspberry Pi with Arduino boards over UART: the Raspberry Pi 5’s GPIO14 (TX) and GPIO15 (RX) pins wired to an Arduino UNO’s serial pins, with no USB cable between the two boards. You’ll learn how to wire a 3.3v Raspberry Pi to a 5v Arduino safely, which serial port to open on the Raspberry Pi 5, why the UNO’s D0/D1 pins fight with its own USB chip, which baud rates work between the two chips, and how to send commands and read values reliably. The Raspberry Pi side is written twice, in Python (pyserial) and C++ (LibSerial).
We’ll answer the question most readers bring here: how do I wire the Pi’s TX and RX to a 5v Arduino UNO without damaging the Pi, and send data both ways without garbage or lost bytes? You’ll see five complete examples (sending a line, reading the reply, a command protocol with checksums and timeouts, reading the UNO’s A0 to dim its LED, and a data stream with no lost lines), plus oscilloscope captures, error counts at seven baud rates, and the round-trip time compared with USB serial. Without further ado, let’s get right into it!
Note: All examples in this tutorial are tested with: Raspberry Pi 5 (8GB) with Raspberry Pi OS (64-bit) Trixie, an Arduino UNO R3 (Arduino IDE 2), and a BSS138 level shifter.
This tutorial assumes your Raspberry Pi is set up with Raspberry Pi OS and reachable over SSH. If it isn’t, follow the Raspberry Pi Setup Guide first. Enabling the UART and the Raspberry Pi 5’s serial ports are covered in detail in my Raspberry Pi UART tutorial; this tutorial uses UART0 on GPIO14/15.
Raspberry Pi Arduino UART Communication in 3 Steps
To connect a Raspberry Pi to an Arduino over UART, cross the TX and RX lines through a 3.3v to 5v level shifter and share ground, enable UART0, then open /dev/ttyAMA0 at the same baud rate the sketch uses:
- Wire it: Pi GPIO14 TX (pin 8) → shifter → UNO RX; UNO TX → shifter → Pi GPIO15 RX (pin 10); GND to GND. Never connect the UNO’s 5v TX straight to the Pi.
- Enable UART0: add dtparam=uart0=on to /boot/firmware/config.txt and reboot. On a Raspberry Pi 5 the GPIO UART is /dev/ttyAMA0; /dev/serial0 is the debug connector.
- Talk: Serial.begin(115200) on the UNO and serial.Serial('/dev/ttyAMA0', 115200) on the Pi ( sudo apt install python3-serial).
Arduino Code example (the UNO answers every line it receives)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
/* * LAB Name: Arduino UART Echo (Raspberry Pi 5 GPIO UART <-> Arduino UNO D0/D1) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ // The Raspberry Pi sends a text line ending in '\n' to the UNO's RX pin (D0). // The UNO answers on TX (D1) with "UNO got: <line> (<n> chars)" and toggles its LED. // Wiring: Pi GPIO14 (TX) -> BSS138 -> UNO D0, UNO D1 -> BSS138 -> Pi GPIO15 (RX), GND to GND. #define LINK_BAUD 115200 // Must match the baud rate on the Raspberry Pi side #define LINE_MAX 64 // Longest line we accept (the UNO's RX buffer is 64 bytes too) char line[LINE_MAX + 1]; uint8_t len = 0; void setup() { Serial.begin(LINK_BAUD); // Hardware UART on D0 (RX) and D1 (TX) pinMode(LED_BUILTIN, OUTPUT); Serial.println(F("READY")); // Tells the Pi the sketch is running } void loop() { while (Serial.available()) // Never block: take what has arrived and return { char c = Serial.read(); if (c == '\r') continue; // Accept "\r\n" line endings too if (c == '\n') { line[len] = '\0'; Serial.print(F("UNO got: ")); Serial.print(line); Serial.print(F(" (")); Serial.print(len); Serial.println(F(" chars)")); digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); len = 0; } else if (len < LINE_MAX) { line[len++] = c; } // Characters past LINE_MAX are dropped until the next '\n' } } |
Python Code example (the Raspberry Pi sends three lines and prints the UNO’s replies)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
"""uart_read.py - send a line to the Arduino UNO over GPIO UART and read its reply, with a timeout. Author: Khaled Magdy, www.DeepBlueMbedded.com Sketch on the UNO: Arduino_UART_Echo """ import serial with serial.Serial("/dev/ttyAMA0", 115200, timeout=0.5) as ser: ser.reset_input_buffer() # Drop anything that arrived before we started for text in ["Hello UNO", "Raspberry Pi 5 here", "12345"]: ser.write((text + "\n").encode()) reply = ser.readline() # Returns at '\n' or after the 0.5 s timeout if not reply.endswith(b"\n"): print(f"{text!r}: no reply (timeout), got {reply!r}") continue print(f"{text!r} -> {reply.decode(errors='replace').strip()}") |
The rest of this tutorial explains each step and the two traps the short version hides: the UNO’s D0/D1 are shared with its USB chip, and some baud rates the UNO can’t produce.
UART, USB, I2C or SPI Between a Raspberry Pi and an Arduino
A Raspberry Pi and an Arduino can talk over four links. This tutorial is about the GPIO UART; pick the link by what your project needs:

| USB Serial | UART (GPIO) | I2C | SPI | |
|---|---|---|---|---|
| Wires | 1 USB cable | TX, RX, GND | SDA, SCL, GND | SCLK, MOSI, MISO, CS, GND |
| Level shifter for a 5v UNO | No | Yes | Yes | Yes |
| Who starts a transfer | Either side | Either side | Pi (master) | Pi (master) |
| One-byte round trip (measured) | ~4 ms | 0.49 ms at 115200, 0.09 ms at 1M | see Part 3 | see Part 4 |
| Best for | Programming + data on one cable | Text commands, streams, either side talks first | Several devices on two wires | Fast, fixed-size frames |
UART is the link to pick when either board may start talking, when you want plain text commands you can read on a scope or in a terminal, and when USB’s 4ms delay is too slow. Every link in this series runs on the same Raspberry Pi 5 and Arduino UNO; for why a project uses both boards at all, see Raspberry Pi vs Arduino.
Raspberry Pi Arduino UART Wiring: Level Shifter or Divider
Note: Never wire the UNO’s TX straight to the Raspberry Pi. The UNO’s TX swings to 5v, and the Raspberry Pi’s GPIO pins are 3.3v only and aren’t 5v tolerant (Raspberry Pi documentation).
Measured through a BSS138 level shifter on my bench: the Pi’s TX idles at 3.34v on the 3.3v side and at 5.12v on the UNO’s RX; the Pi’s RX idles at 3.31v. At 1Mbaud the UNO-side edge rises in 261ns (10–90%) and falls in 44ns, so a 1µs bit still settles, and 60-byte bursts at 1M and 2M arrived with zero errors. Both directions need attention for different reasons:
- UNO TX → Pi RX must be shifted down: 5v into a 3.3v pin is the one connection that can damage the Pi.
- Pi TX → UNO RX works without a shifter on paper, but with little margin: the ATmega328P reads a HIGH from 0.6 × VCC = 3.0v at 5v (ATmega328P datasheet, Table 30-1), and the Pi drives 3.3v. The shifter brings it to a full 5v.
I use a common 4-channel BSS138 level shifter: each channel is a BSS138 MOSFET with a 10kΩ pull-up on each side, the circuit from NXP’s AN10441. It’s bidirectional, so you don’t have to care which channel carries TX and which carries RX.
The Resistor Divider Alternative
If you have no level shifter, a divider on the UNO’s TX line works: 1kΩ from the UNO’s TX to the Pi’s RX, and 2kΩ from the Pi’s RX to GND gives 5v × 2k / 3k = 3.33v at the Pi. Leave the Pi’s TX wired straight to the UNO’s RX (3.3v against the 3.0v threshold). The divider has two costs: it loads the UNO’s TX with 1.67mA at idle, and it adds an RC delay with the Pi’s pin capacitance, which is harmless at 115200 and is the reason to prefer a shifter at 1Mbaud. Everything measured in this tutorial ran through the BSS138.
Wiring Diagram and Parts
| QTY. | Component Name | Amazon.com | AliExpress |
|---|---|---|---|
| 1 | Raspberry Pi 5 (4GB or 8GB) | Amazon | AliExpress |
| 1 | Raspberry Pi 27W USB-C Power Supply | Amazon | AliExpress |
| 1 | Arduino UNO R3 (or a UNO kit) | Amazon | AliExpress |
| 1 | BSS138 4-Channel Logic Level Shifter | – | – |
| 1 | 10kΩ Potentiometer | Amazon | – |
| 1 | LED (5mm) + 220Ω Resistor | Amazon | – |
| 1 | Breadboard | Amazon | AliExpress |
| 1 | Jumper Wires (Female-Male + Male-Male) | Amazon | AliExpress |

The Pi’s GPIO14 (TX) goes through channel 1 to the UNO’s D0 (RX), and the UNO’s D1 (TX) comes back through channel 2 to the Pi’s GPIO15 (RX): TX always goes to RX. The shifter’s LV side takes 3.3v from the Pi, its HV side takes 5V from the UNO, and GND ties the grounds together. On the UNO, D6 drives an LED through a 220Ω resistor, and A0 reads a 10kΩ potentiometer.
Power and Ground
Power each board from its own supply: the Pi from its USB-C supply, and the UNO from your PC’s USB port (that’s also how you upload sketches). Don’t connect the Pi’s 5v pin to the UNO’s 5V pin; the only links between the boards are TX, RX and ground. Without the common ground, the Pi receives nothing or garbage.
Which Serial Port: /dev/ttyAMA0, Not /dev/serial0, on the Raspberry Pi 5
Most guides (and Google’s AI Overview) tell you to open /dev/serial0. On a Raspberry Pi 3 or 4 that pointed at the GPIO UART; on a Raspberry Pi 5 it points at /dev/ttyAMA10, the 3-pin debug connector between the HDMI ports. The UNO on GPIO14/15 is on /dev/ttyAMA0, which exists only after you enable UART0:
|
1 2 |
echo 'dtparam=uart0=on' | sudo tee -a /boot/firmware/config.txt sudo reboot |
| Device | Raspberry Pi 5 hardware | Use it for |
|---|---|---|
/dev/ttyAMA0 | UART0 on GPIO14 (TX, pin 8) / GPIO15 (RX, pin 10) | The Arduino in this tutorial |
/dev/serial0 → ttyAMA10 | Debug UART connector (3-pin JST), Linux console | Serial console, not the GPIO header |
/dev/ttyACM0 | Arduino plugged in by USB | Part 1: USB serial |
Leave the Linux serial console where Raspberry Pi OS puts it on the Pi 5: on the debug connector. A console on GPIO14/15 (for example after enable_uart=1 with no debug cable) answers your Arduino with login: prompts; my Raspberry Pi UART tutorial shows every UART on the Pi 5 and how to move the console.
For Python, install pyserial from the Raspberry Pi OS packages: sudo apt install python3-serial (it’s already on the Full image). pip install pyserial stops with externally-managed-environment on current Raspberry Pi OS (PEP 668). For C++, install LibSerial: sudo apt install libserial-dev.
Arduino D0/D1 vs SoftwareSerial vs AltSoftSerial
The UNO has one hardware UART, on D0 (RX) and D1 (TX), and its USB chip already uses it: the ATmega16U2’s TX and RX reach D0 and D1 through two 1kΩ resistors (RN4 on the UNO R3 schematic). When the Raspberry Pi is wired to the same pins, two transmitters share D0:

What I Measured With the Pi on D0/D1
- Uploads fail while the Pi’s UART is enabled, even with no program running on the Pi: avrdude prints not in sync: resp=0x00 ten times. With GPIO14 released ( pinctrl set 14 ip pn) the same upload works.
- The scope shows why: the Pi holds its TX high, and through the BSS138’s body diode it holds D0 up; the USB chip’s 1kΩ can pull D0 down only to about 2.6v, far above the 1.5v the ATmega needs for a 0. Nothing from the PC reaches the UNO.
- Serial Monitor: you see everything the UNO sends (D1 feeds both the PC and the Pi), but what you type never arrives. Opening the Serial Monitor also resets the UNO, exactly as in Part 1.
- Data between the Pi and the UNO is perfect: 0 errors in both directions at 9,600, 57,600, 115,200, 250,000 and 500,000 baud (5s runs; 230,400 is a baud rate problem, covered below).
SoftwareSerial and AltSoftSerial Measured
Moving the Pi to other pins frees D0/D1 for USB. I ran the same bench sketch with the Pi on SoftwareSerial (D2/D3, built into the Arduino IDE) and on AltSoftSerial (D8/D9, PJRC library, install it from the Library Manager):
| UNO side | Clean in both directions | Fails at | Receive while sending | Loop speed while receiving 57,600 baud | USB uploads with the Pi wired |
|---|---|---|---|---|---|
| Serial on D0/D1 | 9,600–500,000 | 230,400 (UNO’s baud error) | Yes (full duplex) | 189k loops/s | No (release GPIO14 first) |
| AltSoftSerial on D8/D9 | 9,600–57,600 | 115,200 (both ways) | Yes: 0 errors at 9,600; at 57,600, 7 bad bytes on the UNO and 185 on the Pi | 150k loops/s | Yes |
| SoftwareSerial on D2/D3 | 9,600–57,600 | 115,200 (Pi → UNO) | No: 793 of 926 bytes bad at 9,600 | 27k loops/s | Yes |
The loop speed is how many times the bench sketch’s loop() ran per second while a continuous stream arrived, a direct measure of the CPU time each receiver leaves for your code. SoftwareSerial receives in a pin-change interrupt that busy-waits through every byte and sends with interrupts off ( cli() in its write()), so at any baud it takes over 80% of the UNO and can’t listen while it talks. AltSoftSerial uses Timer1’s input capture instead, costs much less, and works in both directions at once; the price is D10’s PWM.
Tip: My recommendation: use AltSoftSerial on D8/D9 at 57,600 baud while you develop, so uploads and the Serial Monitor keep working with the Pi connected. Move to Serial on D0/D1 at 115,200 baud or faster when the UNO runs on its own or you need the speed, and release GPIO14 ( pinctrl set 14 ip pn, then pinctrl set 14 a4 pn) or unplug the TX wire whenever you upload. Skip SoftwareSerial for a link to a Raspberry Pi.

Only the two signal wires move; the Pi side, power, the LED on D6 and the pot on A0 stay as they are.
Example 1: Send a Line From the Raspberry Pi to the Arduino
Upload Arduino_UART_Echo from the code example to the UNO (with the Pi on D0/D1, release GPIO14 for the upload). The sketch collects characters until '\n' and answers each complete line. On the Pi, writing is one call; flush() returns once the bytes have left the UART.
Python Code example (Raspberry Pi sends three text lines to the Arduino)
|
1 2 3 4 5 6 7 8 9 10 11 12 |
"""uart_send.py - send text lines from the Raspberry Pi 5's GPIO UART (GPIO14 TX) to an Arduino UNO. Author: Khaled Magdy, www.DeepBlueMbedded.com Sketch on the UNO: Arduino_UART_Echo """ import serial # /dev/ttyAMA0 = UART0 on GPIO14 (TX, pin 8) and GPIO15 (RX, pin 10), enabled with dtparam=uart0=on with serial.Serial("/dev/ttyAMA0", 115200, timeout=1) as ser: for text in ["Hello UNO", "Raspberry Pi 5 here", "12345"]: ser.write((text + "\n").encode()) # The '\n' tells the sketch the line is complete ser.flush() # Return only after the bytes have left the UART print("sent:", text) |
C++ Code example (Raspberry Pi sends three text lines to the Arduino)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// uart_send.cpp - send text lines from the Raspberry Pi 5's GPIO UART (GPIO14 TX) to an Arduino UNO (LibSerial) // Author: Khaled Magdy, www.DeepBlueMbedded.com // Sketch on the UNO: Arduino_UART_Echo // Build: g++ -std=c++17 uart_send.cpp -o uart_send $(pkg-config --cflags --libs libserial) #include <libserial/SerialPort.h> #include <iostream> using namespace LibSerial; int main() { // /dev/ttyAMA0 = UART0 on GPIO14 (TX, pin 8) and GPIO15 (RX, pin 10) SerialPort ser("/dev/ttyAMA0", BaudRate::BAUD_115200); for (const char* text : {"Hello UNO", "Raspberry Pi 5 here", "12345"}) { ser.Write(std::string(text) + "\n"); // '\n' ends the line for the sketch ser.DrainWriteBuffer(); // Wait until the bytes have left the UART std::cout << "sent: " << text << "\n"; } } |
Build and run the C++ version on the Pi:
|
1 2 3 |
sudo apt install build-essential libserial-dev g++ -std=c++17 uart_send.cpp -o uart_send $(pkg-config --cflags --libs libserial) ./uart_send |
No time.sleep(2) after opening the port: unlike USB, the GPIO UART has no DTR line, so opening /dev/ttyAMA0 doesn’t reset the UNO. The sketch is already running and the first byte gets through.
Example 2: Read the Arduino’s Reply on the Raspberry Pi
Reading needs one rule: never wait forever. Give the port a timeout, read a line, and check that it ends in '\n'; a missing reply then becomes an error you can handle instead of a frozen program.
Python Code example (the Pi sends a line and reads the reply with a 0.5s timeout)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
"""uart_read.py - send a line to the Arduino UNO over GPIO UART and read its reply, with a timeout. Author: Khaled Magdy, www.DeepBlueMbedded.com Sketch on the UNO: Arduino_UART_Echo """ import serial with serial.Serial("/dev/ttyAMA0", 115200, timeout=0.5) as ser: ser.reset_input_buffer() # Drop anything that arrived before we started for text in ["Hello UNO", "Raspberry Pi 5 here", "12345"]: ser.write((text + "\n").encode()) reply = ser.readline() # Returns at '\n' or after the 0.5 s timeout if not reply.endswith(b"\n"): print(f"{text!r}: no reply (timeout), got {reply!r}") continue print(f"{text!r} -> {reply.decode(errors='replace').strip()}") |
C++ Code example (the Pi sends a line and reads the reply with a 500ms timeout)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// uart_read.cpp - send a line to the Arduino UNO over GPIO UART and read its reply, with a timeout (LibSerial) // Author: Khaled Magdy, www.DeepBlueMbedded.com // Sketch on the UNO: Arduino_UART_Echo // Build: g++ -std=c++17 uart_read.cpp -o uart_read $(pkg-config --cflags --libs libserial) #include <libserial/SerialPort.h> #include <iostream> using namespace LibSerial; int main() { SerialPort ser("/dev/ttyAMA0", BaudRate::BAUD_115200); ser.FlushInputBuffer(); // Drop anything that arrived before we started for (const char* text : {"Hello UNO", "Raspberry Pi 5 here", "12345"}) { ser.Write(std::string(text) + "\n"); std::string reply; try { ser.ReadLine(reply, '\n', 500); // Up to '\n', or throw after 500 ms } catch (const ReadTimeout&) { std::cout << "'" << text << "': no reply (timeout)\n"; continue; } while (!reply.empty() && (reply.back() == '\n' || reply.back() == '\r')) reply.pop_back(); std::cout << "'" << text << "' -> " << reply << "\n"; } } |
reset_input_buffer() ( FlushInputBuffer() in LibSerial) drops anything that arrived before your program started, such as half a line the UNO sent while the port was closed.
Example 3: A Command Protocol With Checksums and Timeouts
Plain lines are fine for a demo. A project needs to know that a command arrived intact and was carried out, so the protocol in this example gives every message the same shape, a checksum, and a reply:

- $ starts a frame, so bytes left over from noise or a half line are thrown away.
- *HH is the XOR of the body in hex, the checksum NMEA GPS sentences use. Easy to compute on both sides, and readable in a terminal.
- Every command gets a reply: $OK,..., a value, or $ERR,CHK / CMD / ARG / LEN.
- The Pi waits 200ms for a reply, retries twice, then raises an error. No sleep() anywhere: the reply itself tells the Pi when the UNO is done.
Arduino Code example (Arduino UNO command protocol: LED, PWM, A0, status)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 |
/* * LAB Name: Arduino UART Command Protocol (Raspberry Pi 5 Controls the LED, Reads A0) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ // Every message is one text line: $BODY*HH\n // BODY = command and comma-separated arguments, HH = XOR of all BODY characters in hex. // // Raspberry Pi -> UNO UNO -> Raspberry Pi // $PING*HH $PONG*HH // $LED,1*HH (0 or 1) $OK,LED,1*HH // $PWM,128*HH (0..255) $OK,PWM,128*HH // $A0?*HH $A0,512*HH (10-bit ADC, 0..1023) // $STAT?*HH $STAT,<frames>,<errors>,<uptime ms>*HH // anything wrong $ERR,CHK / CMD / ARG / LEN / FMT*HH // // LINK_PORT 0: the Pi is on the hardware UART, D0 (RX) and D1 (TX). Fastest, but uploads need the Pi's TX released. // LINK_PORT 1: the Pi is on AltSoftSerial, D8 (RX) and D9 (TX); Serial (USB) stays free. Library: AltSoftSerial. // LINK_PORT 2: the Pi is on SoftwareSerial, D2 (RX) and D3 (TX); Serial (USB) stays free. #define LINK_PORT 0 #define LINK_BAUD 115200 // 57600 or lower with AltSoftSerial or SoftwareSerial #define LED_PIN 6 // PWM pin (Timer0) with a 220 ohm resistor and an LED #define FRAME_MAX 40 #if LINK_PORT == 1 #include <AltSoftSerial.h> AltSoftSerial link; // RX = D8, TX = D9 (uses Timer1: no PWM on D10) #elif LINK_PORT == 2 #include <SoftwareSerial.h> SoftwareSerial link(2, 3); // RX = D2, TX = D3 #else #define link Serial #endif char frame[FRAME_MAX + 1]; uint8_t len = 0; bool inFrame = false, tooLong = false; uint16_t frames = 0, errors = 0; uint8_t xorOf(const char *s) // Checksum = XOR of the characters between '$' and '*' { uint8_t x = 0; while (*s) x ^= (uint8_t)*s++; return x; } void reply(const char *body) // Sends $BODY*HH\n { char cs[3]; sprintf(cs, "%02X", xorOf(body)); link.print('$'); link.print(body); link.print('*'); link.println(cs); } int hexVal(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - 'A' + 10; if (c >= 'a' && c <= 'f') return c - 'a' + 10; return -1; } bool readNumber(const char *s, long lo, long hi, long *out) // Whole string must be a number in [lo, hi] { char *end; if (*s == '\0') return false; long v = strtol(s, &end, 10); if (*end != '\0' || v < lo || v > hi) return false; *out = v; return true; } void handle(char *f) // f = "BODY*HH" without '$' and line ending { char *star = strrchr(f, '*'); if (!star || strlen(star) != 3) { errors++; reply("ERR,FMT"); return; } int h = hexVal(star[1]), l = hexVal(star[2]); *star = '\0'; if (h < 0 || l < 0 || xorOf(f) != (uint8_t)(h * 16 + l)) { errors++; reply("ERR,CHK"); return; } frames++; char out[32]; long v; if (strcmp(f, "PING") == 0) reply("PONG"); else if (strncmp(f, "LED,", 4) == 0) { if (!readNumber(f + 4, 0, 1, &v)) { errors++; reply("ERR,ARG"); return; } analogWrite(LED_PIN, v ? 255 : 0); sprintf(out, "OK,LED,%ld", v); reply(out); } else if (strncmp(f, "PWM,", 4) == 0) { if (!readNumber(f + 4, 0, 255, &v)) { errors++; reply("ERR,ARG"); return; } analogWrite(LED_PIN, (int)v); sprintf(out, "OK,PWM,%ld", v); reply(out); } else if (strcmp(f, "A0?") == 0) { sprintf(out, "A0,%d", analogRead(A0)); reply(out); } else if (strcmp(f, "STAT?") == 0) { sprintf(out, "STAT,%u,%u,%lu", frames, errors, millis()); reply(out); } else { errors++; reply("ERR,CMD"); } } void setup() { pinMode(LED_PIN, OUTPUT); link.begin(LINK_BAUD); #if LINK_PORT != 0 Serial.begin(115200); // USB debug port, free because the Pi isn't on D0/D1 Serial.println(F("UNO protocol ready, Pi link on the software UART")); #endif reply("READY"); } void loop() { while (link.available()) { char c = link.read(); if (c == '$') { inFrame = true; tooLong = false; len = 0; continue; } // A '$' always starts a new frame if (!inFrame || c == '\r') continue; // Bytes outside a frame are noise if (c == '\n') { inFrame = false; if (tooLong) { errors++; reply("ERR,LEN"); continue; } frame[len] = '\0'; handle(frame); } else if (len < FRAME_MAX) frame[len++] = c; else tooLong = true; } } |
Set LINK_PORT to 1 and LINK_BAUD to 57600 for AltSoftSerial on D8/D9 (the setup I recommend while developing); the rest of the sketch doesn’t change.
Python Code example (protocol helper class)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
"""uno_uart.py - checksummed command protocol between a Raspberry Pi and an Arduino UNO over UART. Author: Khaled Magdy, www.DeepBlueMbedded.com Sketch on the UNO: Arduino_UART_Protocol Frame: $BODY*HH\n, HH = XOR of the BODY characters in hex (the same checksum NMEA GPS sentences use). """ import serial def checksum(body: str) -> str: x = 0 for c in body.encode(): x ^= c return f"{x:02X}" def frame(body: str) -> bytes: return f"${body}*{checksum(body)}\n".encode() class ProtocolError(Exception): pass class UnoUart: def __init__(self, port="/dev/ttyAMA0", baud=115200, timeout=0.2, retries=2): # No DTR reset on GPIO UART: the sketch keeps running, so there is no READY line to wait for self.ser = serial.Serial(port, baud, timeout=timeout) self.retries = retries self.ser.reset_input_buffer() def _read_frame(self): """Read one line, check its format and checksum, return the BODY. None on timeout.""" line = self.ser.readline() if not line.endswith(b"\n"): return None # Timeout: nothing or half a line text = line.decode(errors="replace").strip() start, star = text.rfind("$"), text.rfind("*") if start < 0 or star < start or len(text) != star + 3: raise ProtocolError(f"bad frame {text!r}") body = text[start + 1:star] if checksum(body) != text[star + 1:].upper(): raise ProtocolError(f"checksum mismatch in {text!r}") return body def request(self, body: str) -> str: """Send one command, return the reply BODY. Retries on timeout or a corrupted reply.""" for attempt in range(1 + self.retries): self.ser.reset_input_buffer() # A late reply to an earlier try must not answer this one self.ser.write(frame(body)) try: reply = self._read_frame() except ProtocolError: continue if reply is None: continue if reply.startswith("ERR,"): raise ProtocolError(f"{body} -> {reply}") return reply raise TimeoutError(f"no valid reply to {body} after {1 + self.retries} tries") # Convenience calls def ping(self): return self.request("PING") == "PONG" def led(self, on: bool): self.request(f"LED,{int(on)}") def pwm(self, duty: int): self.request(f"PWM,{duty}") def read_a0(self) -> int: name, value = self.request("A0?").split(",") return int(value) def close(self): self.ser.close() |
Python Code example (run every command and show the error replies)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
"""uart_protocol.py - run every command of the UNO protocol and show how errors are reported. Author: Khaled Magdy, www.DeepBlueMbedded.com Sketch on the UNO: Arduino_UART_Protocol """ import sys import time from uno_uart import UnoUart, ProtocolError, frame BAUD = int(sys.argv[1]) if len(sys.argv) > 1 else 115200 # 57600 for AltSoftSerial on D8/D9 uno = UnoUart("/dev/ttyAMA0", BAUD) try: t0 = time.perf_counter() print("PING ->", uno.request("PING"), f"({(time.perf_counter() - t0) * 1000:.2f} ms)") print("LED,1 ->", uno.request("LED,1")) print("PWM,64 ->", uno.request("PWM,64")) print("A0? ->", uno.request("A0?")) print("STAT? ->", uno.request("STAT?")) for bad in ["PWM,300", "MOTOR,1"]: # Out-of-range argument, unknown command try: uno.request(bad) except ProtocolError as e: print("error ->", e) uno.ser.write(b"$LED,1*00\n") # A frame with a wrong checksum, sent by hand print("bad checksum ->", uno.ser.readline().decode().strip()) print("good frame bytes:", frame("LED,1")) finally: uno.close() |
C++ Code example (protocol helper class)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
// uno_uart.hpp - checksummed command protocol between a Raspberry Pi and an Arduino UNO over UART (LibSerial) // Author: Khaled Magdy, www.DeepBlueMbedded.com // Sketch on the UNO: Arduino_UART_Protocol. Frame: $BODY*HH\n, HH = XOR of the BODY characters in hex. #pragma once #include <libserial/SerialPort.h> #include <cstdio> #include <stdexcept> #include <string> struct ProtocolError : std::runtime_error { using std::runtime_error::runtime_error; }; inline std::string checksum(const std::string& body) { unsigned x = 0; for (unsigned char c : body) x ^= c; char hex[3]; std::snprintf(hex, sizeof hex, "%02X", x); return hex; } inline std::string frame(const std::string& body) { return "$" + body + "*" + checksum(body) + "\n"; } class UnoUart { public: explicit UnoUart(const std::string& port = "/dev/ttyAMA0", LibSerial::BaudRate baud = LibSerial::BaudRate::BAUD_115200, int timeoutMs = 200, int retries = 2) : ser_(port, baud), timeoutMs_(timeoutMs), retries_(retries) { ser_.FlushInputBuffer(); // No DTR reset on GPIO UART: nothing to wait for } // Send one command, return the reply BODY. Retries on timeout or a corrupted reply. std::string request(const std::string& body) { for (int attempt = 0; attempt <= retries_; attempt++) { ser_.FlushInputBuffer(); // A late reply to an earlier try must not answer this one ser_.Write(frame(body)); std::string reply; try { reply = readFrame(); } catch (const LibSerial::ReadTimeout&) { continue; } catch (const ProtocolError&) { continue; } if (reply.rfind("ERR,", 0) == 0) throw ProtocolError(body + " -> " + reply); return reply; } throw std::runtime_error("no valid reply to " + body + " after " + std::to_string(retries_ + 1) + " tries"); } bool ping() { return request("PING") == "PONG"; } void led(bool on) { request(std::string("LED,") + (on ? "1" : "0")); } void pwm(int duty) { request("PWM," + std::to_string(duty)); } int readA0() { return std::stoi(request("A0?").substr(3)); } // "A0,512" -> 512 private: std::string readFrame() { std::string line; ser_.ReadLine(line, '\n', timeoutMs_); while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) line.pop_back(); auto start = line.rfind('$'), star = line.rfind('*'); if (start == std::string::npos || star == std::string::npos || star < start || line.size() != star + 3) throw ProtocolError("bad frame '" + line + "'"); std::string body = line.substr(start + 1, star - start - 1); if (checksum(body) != line.substr(star + 1)) throw ProtocolError("checksum mismatch in '" + line + "'"); return body; } LibSerial::SerialPort ser_; int timeoutMs_, retries_; }; |
C++ Code example (run every command and show the error replies)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// uart_protocol.cpp - run every command of the UNO protocol and show how errors are reported (LibSerial) // Author: Khaled Magdy, www.DeepBlueMbedded.com // Sketch on the UNO: Arduino_UART_Protocol // Build: g++ -std=c++17 uart_protocol.cpp -o uart_protocol $(pkg-config --cflags --libs libserial) #include "uno_uart.hpp" #include <chrono> #include <iomanip> #include <iostream> int main(int argc, char* argv[]) { // 115200 for D0/D1; pass 57600 for AltSoftSerial on D8/D9 auto baud = (argc > 1 && std::string(argv[1]) == "57600") ? LibSerial::BaudRate::BAUD_57600 : LibSerial::BaudRate::BAUD_115200; UnoUart uno("/dev/ttyAMA0", baud); auto t0 = std::chrono::steady_clock::now(); std::string pong = uno.request("PING"); double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count(); std::cout << "PING -> " << pong << " (" << std::fixed << std::setprecision(2) << ms << " ms)\n"; std::cout << "LED,1 -> " << uno.request("LED,1") << "\n"; std::cout << "PWM,64 -> " << uno.request("PWM,64") << "\n"; std::cout << "A0? -> " << uno.request("A0?") << "\n"; std::cout << "STAT? -> " << uno.request("STAT?") << "\n"; for (const char* bad : {"PWM,300", "MOTOR,1"}) { // Out-of-range argument, unknown command try { uno.request(bad); } catch (const ProtocolError& e) { std::cout << "error -> " << e.what() << "\n"; } } } |
One PING and its PONG took 2.2ms at 115,200 baud on D0/D1, in Python and in C++, and 4.1ms at 57,600 baud on AltSoftSerial. Here is the same exchange on the oscilloscope, decoded:
Example 4: Read A0 and Set the LED From the Raspberry Pi
The Raspberry Pi has no analog inputs, and the UNO has a 10-bit ADC (one of the reasons to use both boards). In this example the Pi asks for A0 twenty times per second, scales it from 0–1023 to a 0–255 PWM duty, and sends it back to the LED on D6. The protocol sketch from Example 3 runs on the UNO unchanged.
Python Code example (read the potentiometer on the UNO’s A0 and set the LED brightness)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
"""led_pot.py - read the UNO's A0 (potentiometer) and set its LED brightness from the Raspberry Pi 5. Author: Khaled Magdy, www.DeepBlueMbedded.com Sketch on the UNO: Arduino_UART_Protocol. Stop with Ctrl+C. """ import sys import time from uno_uart import UnoUart BAUD = int(sys.argv[1]) if len(sys.argv) > 1 else 115200 # 57600 for AltSoftSerial on D8/D9 uno = UnoUart("/dev/ttyAMA0", BAUD) try: while True: a0 = uno.read_a0() # 0..1023 from the UNO's 10-bit ADC duty = a0 // 4 # 0..255 PWM duty uno.pwm(duty) volts = a0 * 5.0 / 1023 print(f"A0 = {a0:4d} ({volts:4.2f} V) LED duty = {duty:3d}", end="\r", flush=True) time.sleep(0.05) # 20 updates per second, a pacing choice, not a sync hack except KeyboardInterrupt: uno.pwm(0) print() finally: uno.close() |
C++ Code example (read the potentiometer on the UNO’s A0 and set the LED brightness)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// led_pot.cpp - read the UNO's A0 (potentiometer) and set its LED brightness from the Raspberry Pi 5 (LibSerial) // Author: Khaled Magdy, www.DeepBlueMbedded.com // Sketch on the UNO: Arduino_UART_Protocol. Stop with Ctrl+C. // Build: g++ -std=c++17 led_pot.cpp -o led_pot $(pkg-config --cflags --libs libserial) #include "uno_uart.hpp" #include <chrono> #include <csignal> #include <cstdio> #include <thread> static volatile std::sig_atomic_t stop = 0; int main(int argc, char* argv[]) { std::signal(SIGINT, [](int) { stop = 1; }); // 115200 for D0/D1; pass 57600 for AltSoftSerial on D8/D9 auto baud = (argc > 1 && std::string(argv[1]) == "57600") ? LibSerial::BaudRate::BAUD_57600 : LibSerial::BaudRate::BAUD_115200; UnoUart uno("/dev/ttyAMA0", baud); while (!stop) { int a0 = uno.readA0(); // 0..1023 from the UNO's 10-bit ADC int duty = a0 / 4; // 0..255 PWM duty uno.pwm(duty); std::printf("A0 = %4d (%4.2f V) LED duty = %3d\r", a0, a0 * 5.0 / 1023, duty); std::fflush(stdout); std::this_thread::sleep_for(std::chrono::milliseconds(50)); // 20 updates per second } uno.pwm(0); std::printf("\n"); } |
Example 5: Stream Data From the Arduino Without Losing Lines
For logging, let the UNO talk on its own: the Arduino_UART_Stream sketch sends one numbered line every 5ms ( seq,millis,A0), and the Pi checks that every sequence number arrives.
Arduino Code example (numbered data lines every 5ms)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
/* * LAB Name: Arduino UART Data Stream to Raspberry Pi 5 (Numbered Lines) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ // The UNO streams one numbered line every PERIOD_MS: <seq>,<millis>,<A0>\n // The sequence number lets the Raspberry Pi prove that no line was lost. // A '?' from the Pi pauses or resumes the stream. #define LINK_BAUD 115200 #define PERIOD_MS 5 // 200 lines/s, about 3.4 kB/s at ~17 characters per line uint32_t seq = 0, nextMs = 0; bool running = true; void setup() { Serial.begin(LINK_BAUD); // Hardware UART, D0/D1 Serial.println(F("READY")); } void loop() { if (Serial.available() && Serial.read() == '?') running = !running; uint32_t now = millis(); if (running && (int32_t)(now - nextMs) >= 0) { nextMs = now + PERIOD_MS; Serial.print(seq++); Serial.print(','); Serial.print(now); Serial.print(','); Serial.println(analogRead(A0)); // ~112 us conversion, well inside the period } } |
The only real loss I could produce is at the start. When the Pi opens the port in the middle of the stream, the first line can begin with junk bytes, received while nobody was reading:
So the readers below throw away the first line, then parse each line and count gaps in the sequence numbers:
Python Code example (receive the stream for 30s and count lost lines)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
"""uart_stream.py - receive the UNO's numbered data lines and prove that none is lost. Author: Khaled Magdy, www.DeepBlueMbedded.com Sketch on the UNO: Arduino_UART_Stream. Runs for SECONDS, then prints a summary. """ import sys import time import serial SECONDS = float(sys.argv[1]) if len(sys.argv) > 1 else 10 with serial.Serial("/dev/ttyAMA0", 115200, timeout=1) as ser: ser.reset_input_buffer() ser.readline() # The first line can start mid-way: throw it away expected, lines, lost, bad, a0 = None, 0, 0, 0, None end = time.monotonic() + SECONDS while time.monotonic() < end: raw = ser.readline() try: seq, ms, a0 = (int(v) for v in raw.decode().strip().split(",")) except ValueError: bad += 1 # Garbled or partial line continue if expected is not None and seq != expected: lost += seq - expected # Gap in the sequence numbers = lines lost print(f"gap: expected {expected}, got {seq}") expected = seq + 1 lines += 1 print(f"{lines} lines in {SECONDS:.0f} s, lost {lost}, garbled {bad}, last A0 = {a0}") |
C++ Code example (receive the stream for 30s and count lost lines)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
// uart_stream.cpp - receive the UNO's numbered data lines and prove that none is lost (LibSerial) // Author: Khaled Magdy, www.DeepBlueMbedded.com // Sketch on the UNO: Arduino_UART_Stream // Build: g++ -std=c++17 uart_stream.cpp -o uart_stream $(pkg-config --cflags --libs libserial) #include <libserial/SerialPort.h> #include <chrono> #include <cstdio> #include <cstdlib> using namespace LibSerial; int main(int argc, char* argv[]) { double seconds = argc > 1 ? std::atof(argv[1]) : 10; SerialPort ser("/dev/ttyAMA0", BaudRate::BAUD_115200); ser.FlushInputBuffer(); std::string line; try { ser.ReadLine(line, '\n', 1000); } catch (const ReadTimeout&) {} // The first line may be partial long expected = -1, lines = 0, lost = 0, bad = 0, a0 = -1; auto end = std::chrono::steady_clock::now() + std::chrono::duration<double>(seconds); while (std::chrono::steady_clock::now() < end) { try { ser.ReadLine(line, '\n', 1000); } catch (const ReadTimeout&) { bad++; continue; } long seq, ms; if (std::sscanf(line.c_str(), "%ld,%ld,%ld", &seq, &ms, &a0) != 3) { bad++; continue; } if (expected >= 0 && seq != expected) { lost += seq - expected; // Gap in the sequence numbers = lines lost std::printf("gap: expected %ld, got %ld\n", expected, seq); } expected = seq + 1; lines++; } std::printf("%ld lines in %.0f s, lost %ld, garbled %ld, last A0 = %ld\n", lines, seconds, lost, bad, a0); } |
5,974 lines in 30s and none lost, in both languages. The Linux serial driver buffers incoming data while your program is busy (more than 1MB in my UART tests), so a slow reader falls behind rather than losing lines. Losses come from the Arduino side: a sketch that sends faster than the baud rate blocks in Serial.print(), and a UNO that receives faster than its loop() reads overflows its 64-byte buffer.
Raspberry Pi Arduino Baud Rate: Which Speeds Work and Why
A UART link works when both ends send and sample at nearly the same rate. The two chips get there differently:
- The Raspberry Pi 5’s PL011 UART divides a 50MHz clock with a 1/64 fraction and lands within 0.006% of any common baud rate (measured in my Raspberry Pi UART tutorial).
- The UNO’s ATmega328P divides 16MHz by 8 × (UBRR + 1) with a whole-number UBRR (HardwareSerial.cpp). Rates that divide 2MHz evenly come out exact: 250,000, 500,000, 1,000,000. The classic rates don’t: 115,200 becomes 117,647 (+2.1%) and 230,400 becomes 222,222 (−3.5%).
I measured the UNO’s real rate with the scope (a stream of 0x55 is a square wave at half the baud rate) and ran 5s of data at each rate in both directions:
| Serial.begin() | UNO sends | Error | Pi → UNO | UNO → Pi |
|---|---|---|---|---|
| 9,600 | 9,620 | +0.21% | 0 errors | 0 errors |
| 57,600 | 58,824 (formula) | +2.12% | 0 errors | 0 errors |
| 115,200 | 117,600 | +2.08% | 0 errors | 0 errors |
| 230,400 | 222,120 | −3.59% | 97% bad | 0 errors |
| 250,000 | 249,880 | −0.05% | 0 errors | 0 errors |
| 500,000 | 500,000 (formula) | 0% | 0 errors | 0 errors |
| 1,000,000 | 1,000,000 (formula) | 0% | 0 errors in bursts¹ | 0 errors |
¹ The line is clean at 1M and even 2M (60-byte bursts arrived without an error), but a continuous stream overruns the UNO: at 10µs per byte, the bench sketch’s loop() couldn’t empty the 64-byte receive buffer in time and lost or misread 20% of 500,000 bytes.

Why does 230,400 fail in only one direction? The ATmega328P samples each bit 8 times (the core uses double-speed mode) and the datasheet recommends at most ±1.5% total error (Table 20-3); −3.6% is past it, so the UNO misreads the Pi’s bytes. The Pi’s PL011 samples 16 times per bit and tolerated the UNO’s slow bytes. At +2.1%, 115,200 is outside the recommendation too, but well inside the hard limits, and it ran clean in every test.
Tip: Pick 115,200 for a link that also suits LibSerial and any terminal program, or 250,000 / 500,000 when you want an exact match (pyserial accepts them; LibSerial’s BaudRate list doesn’t include 250,000, so C++ needs termios2 there). Avoid 230,400 with a 16MHz Arduino.
GPIO UART vs USB Serial: Latency and Throughput
In Part 1, the same UNO talked to the same Pi over its USB cable. Here are both links measured with the same method (1,000 tagged one-byte echoes, Python):
| GPIO UART (this tutorial) | USB serial (Part 1) | |
|---|---|---|
| One-byte round trip, 115,200 baud | 0.49ms (median) | ~4.0ms |
| One-byte round trip, 1,000,000 baud | 0.093ms | ~4.0ms |
| UNO → Pi without loss | Line rate up to 500,000 baud (49.9kB/s) | Up to 250,000 baud |
| Opening the port resets the UNO | No (no DTR on GPIO) | Yes, 1.57s until the sketch runs |
| Old data on open | Can be junk bytes (drop the first line) | Old lines buffered in the 16U2 |
The USB link is slow for one reply because the UNO’s ATmega16U2 firmware sends serial data to the PC on a 4ms timer. The GPIO UART has no such buffer: the round trip is the two frames on the wire plus the Pi’s receive timeout, which is why it shrinks with the baud rate.
Raspberry Pi Arduino UART Troubleshooting
Nothing Received
Check three things in this order: TX goes to RX in both directions (TX to TX is the most common mistake), the grounds are connected, and you opened /dev/ttyAMA0, not /dev/serial0 (see the capture above: a PING to serial0 returns b''). On the UNO, make sure the sketch’s port matches the wiring: Serial for D0/D1, AltSoftSerial for D8/D9.
Garbage Characters
Garbage means the two ends disagree on the bit timing: a different baud rate in the sketch and on the Pi, or a rate the UNO can’t make (230,400, see the baud rate table). A 5v signal straight into the Pi also corrupts data before it damages anything; on my scope that is the only place I look at a 5v TX line, never on the Pi’s pin.
Permission denied
Your user must be in the dialout group ( sudo usermod -aG dialout $USER, then log out and in). If a getty (the serial console) owns the port, ttyAMA0 becomes root-only: turn the login shell off in raspi-config as shown in my Raspberry Pi UART tutorial.
The Upload Fails While the Pi Is on D0/D1
avrdude reports not in sync: resp=0x00 because the Pi’s TX holds D0 high (see the D0/D1 section). Release the pin with pinctrl set 14 ip pn, upload, then give it back with pinctrl set 14 a4 pn; or unplug the TX wire; or use AltSoftSerial on D8/D9, where uploads work with the Pi connected.
The Linux Console Talks to the Arduino
If cmdline.txt sends the console to GPIO14/15, the UNO receives boot messages and a login: prompt, and the Pi answers your sketch’s output as a failed login. Keep the console on the debug connector (the default on the Pi 5) and the serial hardware enabled.
pip install pyserial Fails
Use sudo apt install python3-serial, or a virtual environment if you need a newer pyserial.
Lost Bytes at High Baud Rates
From the Pi to the UNO, a continuous stream above about 500,000 baud overruns the UNO’s 64-byte buffer; keep the UNO’s loop() short, send in bursts and wait for a reply (the protocol in Example 3 does that), or lower the rate. SoftwareSerial and AltSoftSerial top out at 57,600.
Raspberry Pi Arduino UART FAQ
Can I connect the Arduino’s TX to the Raspberry Pi’s RX directly?
No. The UNO’s TX swings to 5v and the Raspberry Pi’s GPIO pins are 3.3v only, per the Raspberry Pi documentation. Use a level shifter or a 1kΩ/2kΩ divider on that line.
Does a 3.3v Arduino need a level shifter?
No. Boards that run at 3.3v (Arduino Pro Mini 3.3v, Nano 33, Due) connect pin to pin with a common ground.
Which Arduino has a spare hardware UART for the Raspberry Pi?
The Arduino Mega 2560 has three more UARTs (Serial1–Serial3 on pins 18/19, 16/17 and 14/15, Arduino docs), so the Pi gets its own port and USB stays free; it still needs a level shifter.
Which baud rate should I use between a Raspberry Pi and an Arduino?
115,200 works reliably with a UNO and suits every tool; 250,000 and 500,000 are exact on a 16MHz AVR. Avoid 230,400, which the UNO sends 3.6% slow.
Can the Raspberry Pi program the Arduino over the GPIO UART?
Not without the reset line: the bootloader runs only right after a reset, which USB triggers through DTR. Program the UNO over USB, from the Pi as in Part 1 or from your PC.
Raspberry Pi With Arduino Tutorial Series
This tutorial is the second part of our Raspberry Pi With Arduino tutorial series:
| Part | Tutorial | What You’ll Build |
|---|---|---|
| 1 | Raspberry Pi With Arduino: USB Serial and Programming | Program the UNO from the Pi (arduino-cli, Arduino IDE), USB serial in Python and C++ |
| 2 | Raspberry Pi With Arduino: UART Communication (this tutorial) | Serial over the GPIO pins with a level shifter, Python and C++ |
| 3 | Raspberry Pi With Arduino: I2C Communication | The UNO as an I2C target, register protocol, clock stretching |
| 4 | Raspberry Pi With Arduino: SPI Communication | The UNO as an SPI slave, the one-byte lag, a framed protocol |
Download Raspberry Pi With Arduino UART Examples
The download contains the three Arduino sketches, every Raspberry Pi example in Python and C++, and the bench sketch and script behind the measurements, with a README that lists each command.
Download Raspberry Pi With Arduino UART Examples (Arduino, Python, C++)
Download all attachment files for this Article/Tutorial (project files, schematics, code, etc.) using the link below. Everything is tested and verified to work on real hardware, as you’ve seen in the demo videos & screenshots. Please consider supporting my work if it helped you.
Wrap Up
To conclude this tutorial, we’ve connected a Raspberry Pi 5 to an Arduino UNO over UART through a BSS138 level shifter, found the right port ( /dev/ttyAMA0), measured why the UNO’s D0/D1 block uploads while the Pi is attached, compared SoftwareSerial and AltSoftSerial, and built a checksummed command protocol in Python and C++. The baud rate table shows which speeds the two chips agree on, and the GPIO link answers about eight times faster than USB serial at 115,200 baud.
This was Part 2 of the Raspberry Pi With Arduino series: Part 1 covers USB serial and uploading sketches from the Pi, Part 3 I2C, and Part 4 SPI. For the Raspberry Pi’s UARTs in general, see my Raspberry Pi UART tutorial; for the Arduino side, the Arduino UART tutorial, Arduino serial communication and serial communication between two Arduino boards; and for more Raspberry Pi projects, the Raspberry Pi tutorials page.

