In this tutorial, we’ll discuss how to use a Raspberry Pi with Arduino boards over the USB cable: how to program an Arduino from the Raspberry Pi with the Arduino IDE on Raspberry Pi and with arduino-cli, and how to exchange data between them over USB serial in Python and C++. You’ll learn what happens when you plug an Arduino UNO into a Raspberry Pi 5 ( /dev/ttyACM0, dmesg, and the dialout group), how to install and use arduino-cli and Arduino IDE on the Pi, and how to read sensor data from the Arduino and send it commands with pyserial and LibSerial.
We’ll answer the question: how do I program an Arduino from my Raspberry Pi and talk to it over the same USB cable, reliably? You’ll see the real compile and upload times on the Raspberry Pi 5, how long the Arduino takes to restart every time the port opens (and the two ways to deal with it), the round-trip time of one command, and which baud rates work with the UNO’s USB chip. Without further ado, let’s get right into it!
Note: All steps in this tutorial are tested with: Raspberry Pi 5 (8GB) with Raspberry Pi OS (64-bit) Trixie, Arduino UNO R3, arduino-cli, and Arduino IDE.
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. Every command below runs in an SSH session; my Raspberry Pi SSH tutorial shows how to connect from Windows, macOS, and Linux.
Raspberry Pi With Arduino: USB, UART, I2C, or SPI
There are four common ways to connect a Raspberry Pi and an Arduino. The Arduino UNO is a 5v board and the Raspberry Pi GPIO pins are 3.3v, so every link that goes through the GPIO pins needs a level shifter. Only the USB cable avoids that, which is why it’s the easiest place to start.

| Method | What You Need | Level Shifter | Arduino Power | Best For |
|---|---|---|---|---|
| USB (this tutorial) | 1 USB cable | No | From the Pi’s USB port | Programming the Arduino and serial data from the Pi |
| UART (Part 2) | TX, RX, GND wires | Yes | Separate | Serial data without using a USB port |
| I2C (Part 3) | SDA, SCL, GND wires | Yes | Separate | Several Arduinos on two wires, each with an address |
| SPI (Part 4) | SCLK, MOSI, MISO, CE0, GND | Yes | Separate | The fastest wired data link |
The USB cable carries power, programming, and serial data at the same time, and the Pi sees the Arduino as a serial port. I’ll use it for the rest of this tutorial.
Arduino IDE on Raspberry Pi: Program and Talk to an Arduino Over USB
Plug the Arduino into one of the Raspberry Pi’s USB ports, check that it shows up as /dev/ttyACM0, and install arduino-cli (the official command-line version of the Arduino IDE, with a 64-bit ARM build). Then compile, upload, and read the Arduino’s serial output from Python:
Shell Code commands (program an Arduino UNO from the Raspberry Pi)
|
1 2 3 4 5 |
wget https://github.com/arduino/arduino-cli/releases/download/v1.6.0/arduino-cli_1.6.0-1_arm64.deb sudo apt install ./arduino-cli_1.6.0-1_arm64.deb arduino-cli core update-index arduino-cli core install arduino:avr arduino-cli compile --upload -p /dev/ttyACM0 --fqbn arduino:avr:uno MySketch |
Python Code code (read the lines the Arduino prints)
|
1 2 3 4 5 |
import serial # python3-serial, already on Raspberry Pi OS with serial.Serial("/dev/ttyACM0", 115200, timeout=3) as uno: while True: print(uno.readline().decode().strip()) |
No sudo is needed for the serial port, because the default user is in the dialout group. Opening the port restarts the Arduino, so the first line arrives about 1.6 seconds later on my UNO. If you prefer a graphical IDE, Raspberry Pi OS also has Arduino IDE 1.8.19 ( sudo apt install arduino); Arduino IDE 2 has no official Linux ARM build. The rest of this tutorial explains each step with complete Python and C++ examples.
Connecting an Arduino to the Raspberry Pi Over USB
Connect the Arduino UNO to any USB port of the Raspberry Pi 5 with its USB A-to-B cable. I used one of the two black USB 2.0 ports: the UNO is a USB full-speed device (12Mbit/s), so the blue USB 3.0 ports don’t make it any faster.

The UNO has two chips. The ATmega328P runs your sketch, and the small ATmega16U2 next to the USB connector is a USB-to-serial converter: it appears on the Pi as a USB serial port and passes every byte to the 328P’s UART (pins D0 and D1). When your program writes to /dev/ttyACM0, the bytes travel through the USB cable and the 16U2 into Serial.read() on the Arduino, and Serial.print() takes the same path back.
Find the Arduino Port: lsusb, dmesg, and /dev/ttyACM0
Run these commands on the Pi after you plug the Arduino in:
- lsusb lists the UNO as 2341:0043 Arduino SA Uno R3 (CDC ACM): 2341 is Arduino’s USB vendor ID.
- dmesg shows a full-speed USB device and the cdc_acm driver creating ttyACM0. CDC ACM is the standard USB serial class, so no driver installation is needed.
- /dev/ttyACM0 belongs to the dialout group with read/write permission for the group, and my user pi is in dialout.
- /dev/serial/by-id/ has a link with the board’s name and serial number that always points to the right device (see the troubleshooting section for why this matters).
Note: Arduino clones with a CH340 chip appear as /dev/ttyUSB0 instead of /dev/ttyACM0 (driver ch341, USB ID 1a86:7523). Everything else in this tutorial works the same: replace the port name in the commands and code.
Don’t confuse ttyACM0 with ttyAMA0 or ttyAMA10: those are the Raspberry Pi’s own UARTs. On the Raspberry Pi 5, /dev/ttyAMA10 is the debug UART connector, and arduino-cli lists it next to the UNO as an unknown serial port (you’ll see it in the next section). The GPIO UART link is Part 2 of this series; over the GPIO pins one command and reply take 0.49ms instead of 4ms.
Raspberry Pi 5 USB Power for the Arduino
The USB port powers the UNO, so you don’t need another supply. The UNO alone needs only a few tens of milliamps. Keep in mind that the Raspberry Pi 5 limits its four USB ports to 600mA in total unless its power supply reports 5A (or you set usb_max_current_enable=1), per the Raspberry Pi power supply documentation. My bench Pi is powered through a USB-A to USB-C cable, so it runs with that limit. If you add servos, motors, or LED strips, power them from their own supply and not from the UNO’s 5v pin, because that current comes through the Pi’s USB port.
Program Arduino From Raspberry Pi With arduino-cli
arduino-cli is the official command-line tool from Arduino. It’s the same engine that Arduino IDE 2 runs underneath (the IDE ships it inside), it has a 64-bit ARM build for the Raspberry Pi, and it works over SSH, so you don’t need a monitor on the Pi. It’s the method I recommend for programming an Arduino from a Raspberry Pi.
Install arduino-cli on Raspberry Pi
arduino-cli isn’t in the Raspberry Pi OS (Debian Trixie) package lists, so download the ARM64 .deb package from the arduino-cli releases page (version 1.6.0 at the time of writing, 15.4MB) and install it with apt. Then create a configuration file and download the board list:
Arduino’s installation page also offers an install.sh script that puts the binary in a bin folder; the .deb package is easier to update and remove later.
Now install the core for your board. The UNO, Nano, and Mega use arduino:avr:
|
1 |
arduino-cli core install arduino:avr |
This downloads the AVR compiler, avrdude, and the core (about 47MB) into ~/.arduino15. On my Raspberry Pi 5 it took 1 minute 23 seconds, most of it unpacking the compiler on the SD card. Then check that the core is installed and that the UNO is detected:
board list recognises the UNO from its USB ID and prints its FQBN (fully qualified board name), arduino:avr:uno. You’ll pass it to every compile and upload command.
Compile and Upload a Sketch With arduino-cli
A sketch is a folder with an .ino file of the same name ( arduino-cli sketch new MySketch creates one). I copied this tutorial’s examples to ~/arduino-usb on the Pi. Compile and upload:
You can do both in one step with arduino-cli compile --upload -p /dev/ttyACM0 --fqbn arduino:avr:uno arduino/Arduino_Serial_Send. To avoid typing the FQBN and port every time, add a sketch.yaml file to the sketch folder:
|
1 2 |
default_fqbn: arduino:avr:uno default_port: /dev/ttyACM0 |
After that, arduino-cli compile -u in that folder is enough.
Arduino Serial Monitor on Raspberry Pi (arduino-cli monitor)
arduino-cli has a serial monitor too. This one shows something you’ll meet again later in this tutorial: the first lines are old output from before the port opened, then the Arduino restarts and prints READY and a counter starting from 0:
Press Ctrl+C to leave the monitor. Under the hood, both arduino-cli and Arduino IDE call avrdude to write the program through the UNO’s bootloader, and you could run avrdude directly with the same arguments if you need to flash a ready .hex file.
Compile and Upload Time: Raspberry Pi 5 vs PC
I timed the same sketch ( Arduino_Serial_Protocol, 2524 bytes) on the Raspberry Pi 5 and on my Windows PC (AMD Ryzen 9 5900X) with the same arduino-cli 1.6.0 and AVR core 1.8.8, five runs each. “Cold” means an empty build folder and no cached core, so the whole Arduino core is compiled too:
| Step | Raspberry Pi 5 (Median) | Windows PC (Median) |
|---|---|---|
| Compile, cold | 0.61 s | 4.44 s |
| Compile, warm (nothing changed) | 0.26 s | 3.85 s |
| Upload to the UNO | 2.79 s | not measured |
The Raspberry Pi 5 compiles faster than my PC. The PC’s arduino-cli belongs to my Arduino IDE installation, which has ESP32, STM32, and RP2040 cores and many libraries installed, and it scans them all on every build; Windows also starts processes more slowly than Linux. The Pi has only the AVR core. Either way, an AVR sketch builds in about a second on the Pi, and the upload (2.8 s, which includes the board reset and the bootloader handshake) takes longer than the compile.
Arduino IDE on Raspberry Pi 5
If you work on the Pi’s desktop, you can use the graphical Arduino IDE. Here is what’s available for the Raspberry Pi 5 with 64-bit Raspberry Pi OS today:
| Option | Version | Status on Raspberry Pi |
|---|---|---|
| sudo apt install arduino | 1.8.19 (Debian Trixie) | Works, tested in this tutorial |
| Arduino legacy IDE, Linux ARM 64 bits | 1.8.19 (arduino.cc) | Official tarball, same version |
| Arduino IDE 2 | 2.3.11 | No Linux ARM build (release files; issue #107 still open) |
| Unofficial Arduino IDE 2 ARM builds | 2.2.0 and older (2023) | Community builds, not maintained by Arduino |
Many older tutorials say sudo apt install arduino installs an outdated 1.6 version. That’s no longer true: on Raspberry Pi OS Trixie the package is Arduino IDE 1.8.19, the last release of the classic IDE, the same version Arduino offers as its legacy download. Install it with:
|
1 |
sudo apt install arduino |
It downloads 74.7MB (with the Java runtime and the AVR toolchain) and uses about 450MB of disk space. Start it from the Raspberry Pi menu under Programming, open your sketch, and then:
#1
Open Tools > Board and select Arduino UNO (or your board).
#2
Open Tools > Port and select /dev/ttyACM0 (Arduino UNO). The IDE also lists /dev/ttyAMA10, which is the Pi’s debug UART.

#3
Click Upload. The status bar says Done uploading and the bottom right corner shows the board and port.

The IDE reads the same ~/.arduino15 folder as arduino-cli, so both can be installed side by side. I took these screenshots on the Pi’s own desktop. For headless work over SSH, arduino-cli is faster to set up and easier to automate.
Raspberry Pi Arduino Serial Communication Over USB
With the Arduino programmed, the same USB cable carries serial data. On the Pi side, the Arduino is the file /dev/ttyACM0, and any language that can open a serial port can talk to it. I’ll show each example in Python with pyserial and in C++ with LibSerial.
- Python: pyserial is already installed on Raspberry Pi OS as the python3-serial package (version 3.5). Don’t pip install pyserial into the system Python: on current Raspberry Pi OS that fails with error: externally-managed-environment (PEP 668). If you need a newer version, use a virtual environment.
- C++: LibSerial is a maintained C++ serial library in the Raspberry Pi OS package lists ( libserial-dev 1.0.0). It handles the termios settings, timeouts, and line reading that you’d otherwise write yourself with the low-level termios API. Install it with sudo apt install libserial-dev (47KB).
All the Arduino sketches here print READY at the end of setup(). Opening the serial port restarts the Arduino, and waiting for that line is the reliable way to know the sketch is running; the DTR section below explains why.
Example 1: Read Arduino Serial Data on Raspberry Pi
In the following example project, the Arduino UNO sends one line every 500ms with a counter and the value of analog input A0, and the Raspberry Pi reads and prints the lines. In other words, Arduino (Tx) -> Raspberry Pi (Rx).
Here is the Arduino code for this example ( Arduino_Serial_Send.ino):
Arduino Code (Arduino_Serial_Send)
|
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 |
/* * LAB Name: Arduino Serial Send To Raspberry Pi Over USB * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ // The UNO prints one line every 500ms: a counter and the A0 reading. // The Raspberry Pi reads these lines from /dev/ttyACM0. unsigned long Counter = 0; void setup() { Serial.begin(115200); Serial.println("READY"); // Tells the Pi the sketch is running (after the DTR reset) } void loop() { int A0_Value = analogRead(A0); Serial.print("count="); Serial.print(Counter++); Serial.print(",a0="); Serial.println(A0_Value); delay(500); } |
Python Code (read_arduino.py)
|
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 |
"""read_arduino.py - read the lines an Arduino prints over USB serial on a Raspberry Pi. Author: Khaled Magdy, www.DeepBlueMbedded.com Sketch on the UNO: Arduino_Serial_Send """ import sys import serial # python3-serial (pyserial), already on Raspberry Pi OS PORT = sys.argv[1] if len(sys.argv) > 1 else "/dev/ttyACM0" with serial.Serial(PORT, 115200, timeout=3) as uno: # Opening the port resets the UNO (DTR). Skip any old lines still buffered in the USB chip # and wait for the READY line the sketch prints after the reset, instead of sleeping. for _ in range(20): if uno.readline().strip() == b"READY": break else: sys.exit("No READY line: is Arduino_Serial_Send uploaded, and is the baud rate 115200?") print("UNO says: READY") try: while True: line = uno.readline().decode(errors="replace").strip() if not line: print("timeout: no line in 3 s") continue fields = dict(item.split("=") for item in line.split(",")) print(f"count {int(fields['count']):5d} A0 {int(fields['a0']):4d}") except KeyboardInterrupt: print("stopped") |
The script skips anything until the READY line, then splits each line into its fields. This is the real output on my Raspberry Pi 5 (stopped with Ctrl+C):
C++ Code (read_arduino.cpp)
|
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 |
// read_arduino.cpp - read the lines an Arduino prints over USB serial on a Raspberry Pi (LibSerial) // Author: Khaled Magdy, www.DeepBlueMbedded.com // Sketch on the UNO: Arduino_Serial_Send // Build: g++ -std=c++17 read_arduino.cpp -o read_arduino $(pkg-config --cflags --libs libserial) #include <libserial/SerialPort.h> #include <iostream> #include <string> using namespace LibSerial; // Opening the port resets the UNO (DTR): skip old buffered lines until the sketch prints READY bool WaitReady(SerialPort& uno) { std::string line; for (int i = 0; i < 20; i++) { try { uno.ReadLine(line, '\n', 3000); } catch (const ReadTimeout&) { continue; } if (line.rfind("READY", 0) == 0) return true; } return false; } int main(int argc, char* argv[]) { const std::string port = argc > 1 ? argv[1] : "/dev/ttyACM0"; SerialPort uno; try { uno.Open(port); } catch (const OpenFailed& e) { std::cerr << "Could not open " << port << ": " << e.what() << "\n"; return 1; } uno.SetBaudRate(BaudRate::BAUD_115200); if (!WaitReady(uno)) { std::cerr << "No READY line from the Arduino\n"; return 1; } std::cout << "UNO says: READY\n"; std::string line; while (true) { try { uno.ReadLine(line, '\n', 3000); std::cout << line; } catch (const ReadTimeout&) { std::cout << "timeout: no line in 3 s\n"; } } } |
Install LibSerial, then compile and run the C++ version:
Example 2: Send Commands From Raspberry Pi to Arduino (LED Control)
In this example, the Raspberry Pi sends one character per command and the Arduino switches its on-board LED (D13): '1' turns it on, '0' turns it off, and 't' toggles it. The Arduino answers each command with the new LED state, so the Pi knows the command arrived. In other words, Raspberry Pi (Tx) -> Arduino (Rx), with a reply.
Arduino Code (Arduino_Serial_Commands)
|
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 |
/* * LAB Name: Arduino Serial Commands From Raspberry Pi (LED Control) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ // The Raspberry Pi sends one character per command over USB serial: // '1' = LED on, '0' = LED off, 't' = toggle. The UNO answers with the new LED state. #define LED_PIN LED_BUILTIN // D13, the on-board "L" LED void setup() { pinMode(LED_PIN, OUTPUT); Serial.begin(115200); Serial.println("READY"); } void loop() { if (Serial.available() > 0) { char Cmd = Serial.read(); if (Cmd == '1') { digitalWrite(LED_PIN, HIGH); } else if (Cmd == '0') { digitalWrite(LED_PIN, LOW); } else if (Cmd == 't') { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); } else { return; } // Ignore '\n', '\r' and anything else Serial.println(digitalRead(LED_PIN) ? "LED=ON" : "LED=OFF"); } } |
Python Code (led_commands.py)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
"""led_commands.py - switch the Arduino UNO's on-board LED from the Raspberry Pi over USB serial. Author: Khaled Magdy, www.DeepBlueMbedded.com Sketch on the UNO: Arduino_Serial_Commands """ import sys import time import serial PORT = sys.argv[1] if len(sys.argv) > 1 else "/dev/ttyACM0" with serial.Serial(PORT, 115200, timeout=3) as uno: # Wait for READY after the DTR reset (old buffered lines are skipped) for _ in range(20): if uno.readline().strip() == b"READY": break else: sys.exit("No READY line from the Arduino") print("UNO says: READY") for cmd in "1010t": uno.write(cmd.encode()) reply = uno.readline().decode().strip() print(f"sent '{cmd}' -> {reply}") time.sleep(1) |
C++ Code (led_commands.cpp)
|
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 |
// led_commands.cpp - switch the Arduino UNO's on-board LED from the Raspberry Pi (LibSerial) // Author: Khaled Magdy, www.DeepBlueMbedded.com // Sketch on the UNO: Arduino_Serial_Commands // Build: g++ -std=c++17 led_commands.cpp -o led_commands $(pkg-config --cflags --libs libserial) #include <libserial/SerialPort.h> #include <chrono> #include <iostream> #include <string> #include <thread> using namespace LibSerial; int main(int argc, char* argv[]) { SerialPort uno(argc > 1 ? argv[1] : "/dev/ttyACM0", BaudRate::BAUD_115200); std::string line; do { // Skip old lines until READY (after the DTR reset) uno.ReadLine(line, '\n', 3000); } while (line.rfind("READY", 0) != 0); std::cout << "UNO says: READY\n"; for (char cmd : std::string("1010t")) { uno.WriteByte(cmd); uno.ReadLine(line, '\n', 1000); std::cout << "sent '" << cmd << "' -> " << line; std::this_thread::sleep_for(std::chrono::seconds(1)); } } |
This is the real hardware testing result for this example on my Raspberry Pi 5 and Arduino UNO, the Python version first and then the C++ version:
Notice the TX and RX LEDs next to the “L” LED: they flash with every command and reply.
Example 3: Raspberry Pi Arduino Serial Protocol (Command and Reply)
Single characters are fine for a few commands. For anything more, send one text command per line and expect exactly one reply line. Text is easy to debug in a serial monitor, and a newline marks where each message ends. In this example the Arduino understands PING, LED 0|1, GET A0, and GET COUNT, replies with OK ..., and answers anything else with ERR ....
Arduino Code (Arduino_Serial_Protocol)
|
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 |
/* * LAB Name: Arduino Serial Line Protocol With Raspberry Pi (Command & Reply) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ // One command per line, one reply per line: // PING -> OK PONG // LED 1|0 -> OK LED 1|0 // GET A0 -> OK A0 <0-1023> // GET COUNT -> OK COUNT <commands handled> // anything else -> ERR <reason> #define LED_PIN LED_BUILTIN #define LINE_MAX 32 char Line[LINE_MAX]; uint8_t LineLen = 0; unsigned long Count = 0; void HandleLine(char* cmd) { Count++; if (strcmp(cmd, "PING") == 0) { Serial.println("OK PONG"); } else if (strncmp(cmd, "LED ", 4) == 0 && (cmd[4] == '0' || cmd[4] == '1') && cmd[5] == '\0') { digitalWrite(LED_PIN, cmd[4] == '1'); Serial.print("OK LED "); Serial.println(cmd[4]); } else if (strcmp(cmd, "GET A0") == 0) { Serial.print("OK A0 "); Serial.println(analogRead(A0)); } else if (strcmp(cmd, "GET COUNT") == 0) { Serial.print("OK COUNT "); Serial.println(Count); } else { Serial.println("ERR UNKNOWN"); } } void setup() { pinMode(LED_PIN, OUTPUT); Serial.begin(115200); Serial.println("READY"); } void loop() { while (Serial.available() > 0) { char c = Serial.read(); if (c == '\r') { continue; } // Accept "\r\n" line endings too if (c == '\n') { Line[LineLen] = '\0'; if (LineLen > 0) { HandleLine(Line); } LineLen = 0; } else if (LineLen < LINE_MAX - 1) { Line[LineLen++] = c; } else { LineLen = 0; // Line too long: drop it Serial.println("ERR TOO LONG"); } } } |
On the Pi, a small class wraps the protocol: it waits for READY once, then command() sends a line and returns the reply, or raises an error on ERR or a timeout:
Python Code (uno_protocol.py)
|
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 |
"""uno_protocol.py - a small command/reply line protocol between a Raspberry Pi and an Arduino. Author: Khaled Magdy, www.DeepBlueMbedded.com Sketch on the UNO: Arduino_Serial_Protocol """ import sys import time import serial class Uno: def __init__(self, port="/dev/ttyACM0", baud=115200, timeout=1.0): self.ser = serial.Serial(port, baud, timeout=timeout) self.wait_ready() def wait_ready(self, seconds=5.0): """Wait for the READY line the sketch prints after the DTR reset. Lines buffered before the reset (old output still in the USB chip) are skipped.""" end = time.monotonic() + seconds while time.monotonic() < end: if self.ser.readline().strip() == b"READY": return raise RuntimeError(f"no READY line from the Arduino within {seconds} s") def command(self, text): """Send one command line, return the reply text after 'OK '. Raise on ERR or timeout.""" self.ser.write((text + "\n").encode()) reply = self.ser.readline().decode(errors="replace").strip() if not reply: raise TimeoutError(f"no reply to {text!r}") if not reply.startswith("OK "): raise RuntimeError(f"{text!r} -> {reply}") return reply[3:] def close(self): self.ser.close() if __name__ == "__main__": uno = Uno(sys.argv[1] if len(sys.argv) > 1 else "/dev/ttyACM0") try: print("PING ->", uno.command("PING")) print("LED 1 ->", uno.command("LED 1")) print("GET A0 ->", uno.command("GET A0")) print("LED 0 ->", uno.command("LED 0")) print("GET COUNT ->", uno.command("GET COUNT")) try: uno.command("LED 2") except RuntimeError as e: print("error ->", e) finally: uno.close() |
C++ Code (uno_protocol.cpp)
|
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 |
// uno_protocol.cpp - command/reply line protocol between a Raspberry Pi and an Arduino (LibSerial) // Author: Khaled Magdy, www.DeepBlueMbedded.com // Sketch on the UNO: Arduino_Serial_Protocol // Build: g++ -std=c++17 uno_protocol.cpp -o uno_protocol $(pkg-config --cflags --libs libserial) #include <libserial/SerialPort.h> #include <iostream> #include <stdexcept> #include <string> using namespace LibSerial; class Uno { public: explicit Uno(const std::string& port) : ser_(port, BaudRate::BAUD_115200) { // Wait for READY after the DTR reset; skip old lines still buffered in the USB chip std::string line; for (int i = 0; i < 20; i++) { try { ser_.ReadLine(line, '\n', 3000); } catch (const ReadTimeout&) { continue; } if (trim(line) == "READY") return; } throw std::runtime_error("no READY line from the Arduino"); } // Send one command line, return the text after "OK ". Throws on ERR or timeout. std::string command(const std::string& text) { ser_.Write(text + "\n"); std::string reply; try { ser_.ReadLine(reply, '\n', 1000); } catch (const ReadTimeout&) { throw std::runtime_error("no reply to '" + text + "'"); } reply = trim(reply); if (reply.rfind("OK ", 0) != 0) throw std::runtime_error("'" + text + "' -> " + reply); return reply.substr(3); } private: static std::string trim(std::string s) { while (!s.empty() && (s.back() == '\n' || s.back() == '\r')) s.pop_back(); return s; } SerialPort ser_; }; int main(int argc, char* argv[]) { Uno uno(argc > 1 ? argv[1] : "/dev/ttyACM0"); std::cout << "PING -> " << uno.command("PING") << "\n"; std::cout << "LED 1 -> " << uno.command("LED 1") << "\n"; std::cout << "GET A0 -> " << uno.command("GET A0") << "\n"; std::cout << "LED 0 -> " << uno.command("LED 0") << "\n"; std::cout << "GET COUNT -> " << uno.command("GET COUNT") << "\n"; try { uno.command("LED 2"); } catch (const std::runtime_error& e) { std::cout << "error -> " << e.what() << "\n"; } } |
The sketch keeps at most 31 characters per line and rejects longer lines, so a broken message can never overflow its buffer. To extend it, add a branch in HandleLine() and a matching call on the Pi.
Arduino Resets When the Serial Port Opens (DTR)
Every time a program opens /dev/ttyACM0, the Arduino UNO restarts. Linux raises the port’s DTR (data terminal ready) line when the port opens, the 16U2 passes it on, and a 100nF capacitor turns that edge into a short pulse on the 328P’s RESET pin. This is how the Arduino IDE starts the bootloader for an upload without you pressing the reset button. The side effect: the sketch starts over, and the bootloader waits for an upload before it runs your code.
I measured the time from opening the port to the sketch’s READY line, five times, with usb_bench.py from the download. Then I turned the port’s HUPCL setting off with stty -hupcl and opened the port twice more:
- With the default settings, the UNO restarted on every open and printed READY 1.57 seconds later (1565.8 to 1569.7 ms).
- With -hupcl, the first open after the stty command still found the board restarting (stty itself opens the port), but the next open got a data line after 0.23 s with no reset: the counter kept running.
- That’s also why the arduino-cli monitor earlier showed old lines first: the 16U2 keeps the last bytes the sketch sent while no program had the port open, and delivers them right after the open, before the reset.
So there are two correct ways to handle it:
- Wait for a ready line (my examples do this): print READY at the end of setup() and, on the Pi, discard lines until it arrives. It works on every board and needs no settings. A fixed time.sleep(2) also works on the UNO, but it guesses, and it doesn’t throw away the old lines.
- Stop the reset when the Arduino must keep running between connections: run stty -F /dev/ttyACM0 -hupcl once (it lasts until the next reboot or replug), or keep one program holding the port open. For a permanent hardware fix, a 10µF capacitor between RESET and GND blocks the pulse, but then uploads need a manual reset.
Setting dtr=False in pyserial before opening the port does not prevent the reset on Linux, because the kernel raises DTR during the open itself. My first test happened to read an old buffered line, and the second one waited for the reset like any other open:
Arduino Serial Baud Rate on Raspberry Pi: How Fast Does USB Go?
The USB cable itself runs at 12Mbit/s, but the data still passes through the UART between the 16U2 and the 328P, at the baud rate you choose in Serial.begin() (the Pi’s baud setting is passed to the 16U2). To find the real limit, the bench sketch sent a counting byte pattern as fast as it could at each baud rate, about 2 seconds’ worth, and the Pi checked that every byte arrived in order:

| Baud Rate | Bytes Sent | Bytes Received | Throughput | Result |
|---|---|---|---|---|
| 9,600 | 2,000 | 2,000 | 1.0 kB/s | No errors |
| 19,200 | 3,840 | 3,840 | 1.9 kB/s | No errors |
| 38,400 | 7,680 | 7,680 | 3.8 kB/s | No errors |
| 57,600 | 11,520 | 11,520 | 5.9 kB/s | No errors |
| 115,200 | 23,040 | 23,040 | 11.7 kB/s | No errors |
| 230,400 | 46,080 | 46,080 | 22.2 kB/s | No errors |
| 250,000 | 50,000 | 50,000 | 24.9 kB/s | No errors |
| 460,800 | 92,160 | 92,157 | 36.8 kB/s | 3 lost, 3 breaks |
| 500,000 | 100,000 | 99,998 | 33.3 kB/s | 2 lost, 2 breaks |
| 921,600 | 184,320 | 102,912 | 41.1 kB/s | 44% lost |
| 1,000,000 | 200,000 | 113,215 | 37.7 kB/s | 43% lost |
| 2,000,000 | 200,000 | 18,240 | 9.1 kB/s | 91% lost |
- Every rate up to 250000 baud was error-free, and the throughput matched the wire speed (baud / 10, because each byte takes 10 bits with the start and stop bits).
- 57600 and 115200 came out about 2% faster than nominal: at 16MHz the AVR’s baud rate divider can’t hit those rates exactly. Both chips run from 16MHz and round the same way, so the genuine UNO doesn’t mind. 230400 is the same story with a 3.5% error.
- From 460800 baud, bytes started to go missing. The data rate stopped at about 33-41 kB/s whatever the baud rate, and at 1 Mbaud and 2 Mbaud most of the data was lost. The 16U2’s firmware buffers incoming UART bytes in a small ring buffer and can’t move them to USB faster than that.
- Use 115200 for most projects and 250000 if you need more. Higher rates need flow control in your own protocol (the Pi asks, the Arduino answers), not a faster baud rate.
Command-to-Reply Latency: Python vs C++
For control loops, the delay of one exchange matters more than the throughput. I sent one byte to the Arduino in echo mode and timed how long it took to come back, 1,000 times per setting:
| Baud Rate | Python (Median) | C++ (Median) | Worst (Python / C++) |
|---|---|---|---|
| 9,600 | 4.00 ms | 4.44 ms | 4.9 / 7.1 ms |
| 115,200 | 4.00 ms | 4.06 ms | 4.9 / 4.9 ms |
| 1,000,000 | 4.00 ms | 4.00 ms | 4.9 / 4.9 ms |
The round trip is about 4ms at every baud rate and in both languages. The cause is the 16U2’s USB-serial firmware: it collects bytes from the UART and sends them to the Pi when its buffer is nearly full or when a timer overflows, every 4.096ms (Timer0 with a /256 prescaler at 16MHz). A single reply waits for that timer. So, don’t expect more than about 250 command-reply exchanges per second over the UNO’s USB port, and send several values per message instead of one per round trip. Language doesn’t matter here: Python is as fast as C++ for this job.
Parts List
| 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 | Amazon | AliExpress |
| 1 | USB A-to-B Cable | – | – |
Raspberry Pi Arduino USB Troubleshooting
/dev/ttyACM0 Permission Denied
The user isn’t in the dialout group (I ran the script as the user nobody to show it). Add your user with sudo usermod -aG dialout $USER, then log out and back in. Don’t run your serial programs with sudo.
avrdude: not in sync / programmer is not responding
The upload can’t talk to the bootloader. The first attempt above selects the wrong board (a Nano with the old bootloader, which uses a different upload speed), and the second uses the wrong port ( /dev/ttyAMA10, the Pi’s own UART). Check the FQBN with arduino-cli board list and the port with ls /dev/ttyACM*. Older avrdude versions print this as stk500_recv(): programmer is not responding.
Device or Resource Busy
Another program holds the port in exclusive mode, typically a serial monitor that’s still open. Close it ( fuser /dev/ttyACM0 shows which process has the port) and try again. Linux doesn’t lock serial ports by default: two programs that don’t ask for exclusive access can open the port together and steal each other’s data, so close the monitor before you run your own script.
Garbage or Zeros Instead of Text (Wrong Baud Rate)
The baud rate on the Pi doesn’t match Serial.begin() in the sketch. Here the sketch sends at 115200 and the Pi listens at 9600, so every byte arrives as 0x00; other combinations give random characters. Use the same value on both sides.
/dev/ttyACM0 Becomes /dev/ttyACM1
If the Arduino is unplugged and plugged back in while a program still has /dev/ttyACM0 open, the new connection gets /dev/ttyACM1 (I simulated the replug in software). The /dev/serial/by-id/usb-Arduino... link always points to the right device, so use it in scripts that must survive a replug, or close the port and reopen it after a disconnect.
ModemManager Grabs the Port
On some Linux distributions, ModemManager probes every new ttyACM device as a possible modem, which delays or breaks uploads right after you plug the board in. ModemManager isn’t installed on Raspberry Pi OS Trixie (checked with dpkg -l modemmanager), so this doesn’t happen on the Pi. If you installed it yourself, remove it or stop it with sudo systemctl stop ModemManager.
Raspberry Pi With Arduino FAQ
Can I install Arduino IDE 2 on a Raspberry Pi 5?
Not officially. Arduino IDE 2.3.11 has Linux builds for x86-64 only. Use arduino-cli (the engine of IDE 2, with an official ARM64 build) or Arduino IDE 1.8.19 from sudo apt install arduino.
Does this work on a Raspberry Pi 4 or Raspberry Pi Zero 2 W?
Yes, the same commands and code apply on 64-bit Raspberry Pi OS. On a 32-bit OS, download the armhf (ARMv7) package of arduino-cli instead of arm64. Compile times will be longer than on the Raspberry Pi 5.
Can the Raspberry Pi power the Arduino over USB?
Yes. The UNO alone draws a few tens of milliamps. Power motors, servos, and LED strips from their own supply, because the Pi 5’s USB ports share a 600mA limit unless the power supply reports 5A.
Do I need a level shifter for USB?
No. USB has its own signal levels, and the UNO’s 16U2 converts them. Level shifters are only needed for the GPIO links: UART, I2C, and SPI (Part 2, Part 3, and Part 4).
Does an ESP32 or Arduino UNO R4 work the same way?
The serial side does: the board appears as /dev/ttyACM0 or /dev/ttyUSB0 depending on its USB chip, and the Python and C++ code is the same. For uploads, install the board’s core ( arduino-cli core install esp32:esp32 needs its board manager URL first) and use its FQBN. Native USB boards and other USB chips don’t share the 16U2’s 4ms timer, so their latency and maximum speed differ.
Can I use the Arduino Cloud Editor on the Raspberry Pi?
The Cloud Editor runs in the browser and uploads through the Arduino Cloud Agent, a program that has to run on the Pi. arduino-cli does the same job locally, without an account.
Raspberry Pi With Arduino Tutorial Series
This tutorial is the first part of our Raspberry Pi With Arduino tutorial series. Each part connects the same Raspberry Pi 5 and Arduino UNO with a different link, with complete Python and C++ examples:
| Part | Tutorial | What You’ll Build |
|---|---|---|
| 1 | Raspberry Pi With Arduino: USB Serial and Programming (this tutorial) | Program the UNO from the Pi (arduino-cli, Arduino IDE), USB serial in Python and C++ |
| 2 | Raspberry Pi With Arduino: UART Communication | 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 USB Examples
The download contains the four Arduino sketches, every Raspberry Pi example in Python and C++, and the benchmark programs behind the measurements (reset timing, latency, and baud rate sweep), with a README that lists each command.
Download Raspberry Pi With Arduino USB 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 an Arduino UNO to a Raspberry Pi 5 with a USB cable, programmed it from the Pi with arduino-cli and Arduino IDE 1.8.19, and exchanged data in both directions with Python and C++. The measurements show what to expect from this link: the Pi compiles an AVR sketch in under a second, the UNO restarts for 1.57 s whenever the port opens, one command and reply take about 4ms, and the UNO’s USB chip carries data without errors up to 250000 baud.
This was Part 1 of the Raspberry Pi With Arduino series. The next parts connect the two boards through the GPIO pins with a level shifter, over UART, I2C, and SPI. For the Arduino side of serial communication, see my Arduino Serial Communication tutorial, and for the Pi’s pins, the Raspberry Pi GPIO tutorial.
