In this tutorial, we’ll make a Raspberry Pi with Arduino work together over I2C: the Raspberry Pi 5 is the I2C master, and an Arduino UNO is an I2C slave at address 0x08. You’ll learn how to wire the two boards safely (and what the UNO’s own pull-ups do to a 3.3v Raspberry Pi), how the Arduino Wire library’s onReceive and onRequest handlers work, and how to turn the UNO into a register device that the Raspberry Pi reads like any I2C sensor. The Raspberry Pi side is written twice, in Python (smbus2) and C++ (Linux i2c-dev).
We’ll answer the question: can a 3.3v Raspberry Pi 5 and a 5v Arduino UNO share an I2C bus safely, and how does the Raspberry Pi read data back from the Arduino? You’ll see four complete examples (sending bytes, reading them back, a register protocol with a repeated START, and controlling the UNO’s LED from a potentiometer it reads), an oscilloscope test of clock stretching on the Raspberry Pi 5, and error counts at 100kHz and 400kHz. 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 (Arduino IDE 2), and a BSS138 level shifter.
This tutorial assumes your Raspberry Pi is set up with Raspberry Pi OS, reachable over SSH, and has I2C enabled. If it isn’t, follow the Raspberry Pi Setup Guide first, and enable I2C as shown in my Raspberry Pi I2C tutorial, which also covers the I2C basics this tutorial builds on.
Raspberry Pi With Arduino I2C Communication
To connect a Raspberry Pi to an Arduino over I2C, wire the Pi’s SDA (GPIO2, pin 3) and SCL (GPIO3, pin 5) to the Arduino UNO’s A4 (SDA) and A5 (SCL) through a 3.3v to 5v I2C level shifter, with a common ground. Make the UNO an I2C slave with Wire.begin(0x08), handle incoming bytes in Wire.onReceive() and requests in Wire.onRequest(), and talk to it from the Pi with smbus2:
Arduino Code example (Arduino UNO I2C slave at 0x08, prints what it receives and echoes it back)
|
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 |
/* * LAB Name: Arduino I2C Slave Echo (Raspberry Pi Master) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ // The Raspberry Pi writes up to 32 bytes to address 0x08: the UNO prints them on Serial. // The Raspberry Pi reads from 0x08: the UNO sends the last message back (echo). #include <Wire.h> #define I2C_ADDRESS 0x08 volatile uint8_t msg[32]; // Last message received from the Pi volatile uint8_t msgLen = 0; volatile bool newMsg = false; // Set by the handler, cleared by loop() void receiveEvent(int howMany) // Runs inside the TWI interrupt: keep it short { uint8_t n = 0; while (Wire.available() && n < sizeof(msg)) { msg[n++] = Wire.read(); } msgLen = n; newMsg = true; } void requestEvent() // Runs inside the TWI interrupt while SCL is held low { Wire.write((const uint8_t*)msg, msgLen); } void setup() { Serial.begin(115200); Wire.begin(I2C_ADDRESS); // Join the bus as a slave at 0x08 Wire.onReceive(receiveEvent); Wire.onRequest(requestEvent); Serial.println(F("UNO I2C slave ready at 0x08")); } void loop() { if (newMsg) // Print from loop(), never from the handler { uint8_t copy[32], len; noInterrupts(); len = msgLen; for (uint8_t i = 0; i < len; i++) copy[i] = msg[i]; newMsg = false; interrupts(); Serial.print(F("Received ")); Serial.print(len); Serial.print(F(" bytes: ")); for (uint8_t i = 0; i < len; i++) Serial.write(copy[i]); Serial.println(); } } |
Python Code example (Raspberry Pi I2C master, sends 6 bytes and reads them back)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
"""i2c_read.py - send bytes to the Arduino UNO, then read them back (echo sketch). Author: Khaled Magdy, www.DeepBlueMbedded.com """ from smbus2 import SMBus, i2c_msg UNO_ADDRESS = 0x08 with SMBus(1) as bus: out = b"Pi5:42" bus.i2c_rdwr(i2c_msg.write(UNO_ADDRESS, out)) # the UNO stores the message back = i2c_msg.read(UNO_ADDRESS, len(out)) # START, 0x08 R, 6 bytes, STOP bus.i2c_rdwr(back) data = bytes(back) print(f"Sent: {out} Read back: {data} Match: {data == out}") |
The rest of this tutorial explains the wiring and the pull-up problem, the Wire slave rules, a register protocol for real projects, clock stretching on the Raspberry Pi 5, and how fast the link runs without errors.
I2C vs SPI vs UART Between a Raspberry Pi and an Arduino
A Raspberry Pi and an Arduino can talk over four links. This tutorial is about I2C; 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 (on the UNO’s TX) | Yes (5v pull-ups) | Yes |
| Who starts a transfer | Either side | Either side | Pi (master) | Pi (master) only |
| Several Arduinos | One per USB port | One per UART | Up to 112 by address | One CS pin each |
| Speed in practice | 115,200 baud typical | 115,200 baud typical | 100–400kHz | Up to a few MHz |
| Best for | Programming + data on one cable | Simple text commands | Several devices on two wires, sensor-style registers | Fast, fixed-size frames |
I2C is the link to pick when the Arduino should look like one more sensor on the Raspberry Pi’s bus: two wires, an address, and registers. Its limits are speed and the 5v pull-up problem, which the next section solves. 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 I2C Wiring: Level Shifter or Direct?
Note: Use an I2C level shifter between a 5v Arduino UNO and a Raspberry Pi. The Raspberry Pi’s GPIO pins are 3.3v only and aren’t 5v tolerant, per the Raspberry Pi documentation, and the UNO expects 5v logic levels on its I2C pins.
Many guides wire the UNO straight to the Raspberry Pi with the argument that the UNO board has no I2C pull-up resistors, so only the Pi’s 1.8kΩ pull-ups to 3.3v set the bus level. Two facts from the datasheet and the Arduino source say otherwise:
- Wire.begin() turns on the ATmega328P’s internal pull-ups. The AVR core’s twi_init() does it on purpose (“activate internal pullups for twi”, twi.c), and they are 20–50kΩ to 5v (ATmega328P datasheet, Table 30-1). Against the Pi’s 1.8kΩ to 3.3v, that divider lifts the idle bus to roughly 3.36–3.44v, above the Pi’s 3.3v supply, with a small current flowing into the Pi’s 3.3v rail through its pull-ups. It rarely damages anything, but it’s outside what the Pi is specified for.
- The UNO needs 3.5v for a guaranteed HIGH. The ATmega328P’s I2C inputs are specified at VIH = 0.7 × VCC = 3.5v at 5v (datasheet, Table 29-14), and a 3.3v bus never reaches it. It often works on the bench because the real threshold is lower than the guaranteed one, but there’s no noise margin left, and errors show up with longer wires or higher speeds.
A bidirectional level shifter solves both. 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. Its LV side stays at the Raspberry Pi’s 3.3v, its HV side swings the UNO’s full 5v, and either side can pull the line low, which is what I2C’s open-drain lines need. On my bench, the Raspberry Pi side of the shifter idles at 3.31v (SDA) and 3.33v (SCL), right at the Pi’s own 3.3v rail, measured on the oscilloscope at GPIO2 and GPIO3.
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 | – | – |
| 1 | BSS138 4-Channel I2C Logic Level Shifter | – | – |
| 1 | 10kΩ Potentiometer | – | – |
| 1 | LED (5mm) + 330Ω Resistor | – | – |
| 1 | Breadboard | Amazon | AliExpress |
| 1 | Jumper Wires (Female-Male + Male-Male) | Amazon | AliExpress |

The Pi’s GPIO2 (SDA) and GPIO3 (SCL) go through the shifter to the UNO’s SDA (A4) and SCL (A5); the UNO R3 also brings them out next to AREF. The shifter’s LV side takes 3.3v from the Pi, its HV side takes 5V from the UNO, and both GND pins tie the grounds together. On the UNO, D9 drives an LED through a 330Ω resistor, and A0 reads a 10kΩ potentiometer between 5V and GND.
Power and Ground
Power each board from its own USB supply: the Pi from its USB-C supply, and the UNO from your PC (that’s also how you upload sketches and watch its Serial Monitor). Don’t connect the Pi’s 5v pin to the UNO’s 5V pin; the only connections between the boards are SDA, SCL, and ground. On this shifter the LV and HV GND pins are one net, so the Pi’s GND (pin 6) and the UNO’s GND meet there. Without that common ground, the Pi gets no answer at all (see Troubleshooting).
Raspberry Pi i2cdetect Finds the Arduino at 0x08
Upload the echo sketch from the code example to the UNO, then scan the bus from the Raspberry Pi. The UNO answers at the address you passed to Wire.begin():
|
1 |
i2cdetect -y 1 |
The scan itself reaches the UNO’s sketch: i2cdetect probes each address with a zero-byte write, so the echo sketch’s onReceive runs with howMany = 0 and prints “Received 0 bytes” (see the Serial Monitor in Example 1). Guard your handler against empty writes, as the register sketch does with if (howMany < 1) return;.
Pick any address from 0x08 to 0x77. Addresses 0x00–0x07 and 0x78–0x7F are reserved by the I2C specification (general call, CBUS, high-speed mode, 10-bit addressing), which is why i2cdetect doesn’t even scan them; my Raspberry Pi I2C tutorial explains the scan in detail. If you add sensors to the same bus, give the UNO an address none of them uses.
Arduino Wire Slave Explained: onReceive and onRequest
The Arduino Wire library turns the UNO into an I2C slave with one call, Wire.begin(address), and two handlers. The master (the Raspberry Pi) starts every transfer; the UNO only reacts:
- Wire.onReceive(handler): the handler runs after the Pi has written bytes to the UNO, at the STOP or at a repeated START. Its argument is the byte count, and Wire.read() returns the bytes.
- Wire.onRequest(handler): the handler runs when the Pi starts a read from the UNO, right after the address byte. Whatever it passes to Wire.write() goes back to the Pi.

Rules for Code Inside the Handlers
Both handlers run inside the ATmega328P’s TWI interrupt (twi.c in the AVR core calls them from ISR(TWI_vect)). While onRequest() runs, the UNO holds SCL low and the whole bus waits. So:
- No Serial.print() and no delay() in a handler. Set a flag and print from loop(), as both sketches here do. Serial output is interrupt-driven too, and its 64-byte buffer can fill inside the handler; then Serial.print() waits for room while the UNO holds the bus.
- Mark shared variables volatile, and copy multi-byte values in loop() with interrupts off ( noInterrupts() / interrupts()), or the handler can see half of an update.
- Keep them short: copy bytes in, copy bytes out. Do the real work (analogWrite, sensor reads) in loop().
- One Wire.write() buffer per request: several Wire.write() calls in onRequest() append to the same buffer (AVR core 1.8.x).
The 32-Byte Wire Buffer Limit
The AVR Wire library has one 32-byte buffer per direction: #define BUFFER_LENGTH 32 in Wire.h and TWI_BUFFER_LENGTH 32 in twi.h. That sets three limits for a UNO slave:
- A write from the Pi can carry at most 32 bytes. The UNO ACKs bytes 1–32 and NACKs byte 33, so the Pi’s write fails. On the Raspberry Pi 5 this NACK on the last byte is not reported: a 33-byte write returned no error at all, and the UNO’s Serial Monitor showed “Received 32 bytes”. The 33rd byte was silently lost.
- A single Wire.write(buf, n) with n over 32 in onRequest() is rejected completely: twi_transmit() refuses the whole block, yet Wire.write() still returns n (AVR core 1.8.x source). Keep each reply at 32 bytes or less.
- If the Pi reads more bytes than onRequest() wrote, the UNO stops driving SDA after its last byte and the Pi reads 0xFF for the rest. Reading 8 bytes after a 6-byte message returned b’Pi5:42\xff\xff’ on my bench.
For longer messages, split them into chunks of up to 32 bytes, or let the Pi read a register map piece by piece, as in Example 3.
Example 1: Send Bytes From the Raspberry Pi to the Arduino
Upload the Arduino_I2C_Slave_Echo sketch from the code example to the UNO and open the Serial Monitor at 115200 baud. The Raspberry Pi writes a 9-byte text message in one I2C transaction; the UNO’s onReceive handler stores it, and loop() prints it.
Python Code example (Raspberry Pi sends a text message to the Arduino)
|
1 2 3 4 5 6 7 8 9 10 11 |
"""i2c_send.py - send a text message from the Raspberry Pi to the Arduino UNO over I2C. Author: Khaled Magdy, www.DeepBlueMbedded.com """ from smbus2 import SMBus, i2c_msg UNO_ADDRESS = 0x08 # Wire.begin(0x08) in the UNO sketch with SMBus(1) as bus: # /dev/i2c-1 = GPIO2 (SDA), GPIO3 (SCL) text = b"Hello UNO" bus.i2c_rdwr(i2c_msg.write(UNO_ADDRESS, text)) # START, 0x08 W, 9 bytes, STOP print(f"Sent {len(text)} bytes: {text.decode()}") |
smbus2’s i2c_msg.write() with i2c_rdwr() sends raw I2C bytes. The SMBus-style calls ( write_byte(), write_i2c_block_data()) work too, but they add a command byte in front; that’s exactly what Example 3 uses as the register number.
C++ Code example (Raspberry Pi sends a text message to the Arduino)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// i2c_send.cpp - send a text message from the Raspberry Pi to the Arduino UNO over I2C // Build: g++ -std=c++17 -O2 i2c_send.cpp -o i2c_send // Author: Khaled Magdy, www.DeepBlueMbedded.com #include <cstdio> #include <cstring> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <linux/i2c-dev.h> int main() { int fd = open("/dev/i2c-1", O_RDWR); // GPIO2 (SDA), GPIO3 (SCL) if (fd < 0 || ioctl(fd, I2C_SLAVE, 0x08) < 0) { perror("i2c"); return 1; } const char text[] = "Hello UNO"; ssize_t n = write(fd, text, strlen(text)); // START, 0x08 W, 9 bytes, STOP if (n != (ssize_t)strlen(text)) { perror("write"); return 1; } std::printf("Sent %zd bytes: %s\n", n, text); close(fd); } |
In C++, ioctl(fd, I2C_SLAVE, 0x08) sets the address once, and a plain write() sends one transaction. Build and run it on the Pi:
|
1 2 |
g++ -std=c++17 -O2 i2c_send.cpp -o i2c_send ./i2c_send |

Example 2: Read Bytes From the Arduino on the Raspberry Pi
Reading is the part most Raspberry Pi to Arduino I2C guides skip. In an I2C read, the Pi clocks the bytes out of the UNO: it sends the address with the read bit, the UNO’s onRequest handler loads its reply with Wire.write(), and the Pi ACKs each byte until the last one, which it NACKs. The echo sketch answers with the last message it received.
Python Code example (Raspberry Pi writes 6 bytes, then reads them back from the Arduino)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
"""i2c_read.py - send bytes to the Arduino UNO, then read them back (echo sketch). Author: Khaled Magdy, www.DeepBlueMbedded.com """ from smbus2 import SMBus, i2c_msg UNO_ADDRESS = 0x08 with SMBus(1) as bus: out = b"Pi5:42" bus.i2c_rdwr(i2c_msg.write(UNO_ADDRESS, out)) # the UNO stores the message back = i2c_msg.read(UNO_ADDRESS, len(out)) # START, 0x08 R, 6 bytes, STOP bus.i2c_rdwr(back) data = bytes(back) print(f"Sent: {out} Read back: {data} Match: {data == out}") |
C++ Code example (Raspberry Pi writes 6 bytes, then reads them back from the Arduino)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// i2c_read.cpp - send bytes to the Arduino UNO, then read them back (echo sketch) // Build: g++ -std=c++17 -O2 i2c_read.cpp -o i2c_read // Author: Khaled Magdy, www.DeepBlueMbedded.com #include <cstdio> #include <cstring> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <linux/i2c-dev.h> int main() { int fd = open("/dev/i2c-1", O_RDWR); if (fd < 0 || ioctl(fd, I2C_SLAVE, 0x08) < 0) { perror("i2c"); return 1; } const char out[] = "Pi5:42"; char back[sizeof(out)] = {0}; if (write(fd, out, strlen(out)) != (ssize_t)strlen(out)) { perror("write"); return 1; } if (read(fd, back, strlen(out)) != (ssize_t)strlen(out)) { perror("read"); return 1; } // START, 0x08 R, 6 bytes, STOP std::printf("Sent: %s Read back: %s Match: %s\n", out, back, strcmp(out, back) == 0 ? "True" : "False"); close(fd); } |
The Pi decides how many bytes to read; the UNO can’t know in advance. If you ask for more than the UNO wrote, the extra bytes come back as 0xFF (see Troubleshooting). That’s why real projects use a protocol with fixed sizes, the next example.
Example 3: Arduino I2C Register Protocol With Repeated START
I2C sensors all work the same way: the master writes a register number, then reads bytes starting at that register. Give the UNO the same behavior and the Raspberry Pi reads it with the same calls it uses for a BME280 or an MPU6050. Here’s the register map of the Arduino_I2C_Slave_Registers sketch and the two frames it understands:

Arduino Code example (Arduino UNO as an I2C register device)
|
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 |
/* * LAB Name: Arduino I2C Slave With Registers (Raspberry Pi Master: LED, PWM, A0, Uptime) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ // The UNO behaves like an I2C sensor with a register map at address 0x08: // Write: [REG, VALUE, VALUE...] -> values go to REG, REG+1, ... // Read : [REG] then repeated START + read -> bytes come from REG, REG+1, ... // // 0x00 WHO_AM_I R 0xA5 // 0x01 LED R/W 0 = off, 1 = on (on-board LED, D13) // 0x02 PWM R/W 0..255 duty on D9 // 0x10 A0 R 2 bytes, high byte first (0..1023) // 0x12 UPTIME_MS R 4 bytes, millis(), most significant byte first // 0x16 RX_COUNT R 2 bytes, number of write transactions received #include <Wire.h> #define I2C_ADDRESS 0x08 #define PWM_PIN 9 #define REG_WHO_AM_I 0x00 #define REG_LED 0x01 #define REG_PWM 0x02 #define REG_A0 0x10 #define REG_UPTIME 0x12 #define REG_RX_COUNT 0x16 #define REG_COUNT 0x18 volatile uint8_t regs[REG_COUNT]; volatile uint8_t regPtr = 0; // Register pointer, set by the first byte of every write volatile bool outputsChanged = false; volatile uint16_t rxCount = 0; void receiveEvent(int howMany) // TWI interrupt: store bytes, no Serial, no delay { if (howMany < 1) return; regPtr = Wire.read(); // First byte = register number while (Wire.available()) // Any further bytes = values to write { uint8_t v = Wire.read(); if (regPtr == REG_LED || regPtr == REG_PWM) { regs[regPtr] = v; outputsChanged = true; } regPtr++; // Auto-increment, like most I2C sensors } rxCount++; regs[REG_RX_COUNT] = rxCount >> 8; regs[REG_RX_COUNT + 1] = rxCount & 0xFF; } void requestEvent() // TWI interrupt: SCL is stretched until this returns { if (regPtr >= REG_COUNT) { Wire.write(0xFF); return; } uint32_t t = millis(); // Fresh uptime for every read regs[REG_UPTIME] = t >> 24; regs[REG_UPTIME + 1] = t >> 16; regs[REG_UPTIME + 2] = t >> 8; regs[REG_UPTIME + 3] = t; // The slave can't know how many bytes the master wants: offer the rest of the map. // The master NACKs the last byte it needs; the unsent bytes are dropped. Wire.write((const uint8_t*)®s[regPtr], REG_COUNT - regPtr); } void setup() { Serial.begin(115200); pinMode(LED_BUILTIN, OUTPUT); pinMode(PWM_PIN, OUTPUT); regs[REG_WHO_AM_I] = 0xA5; Wire.begin(I2C_ADDRESS); Wire.onReceive(receiveEvent); Wire.onRequest(requestEvent); Serial.println(F("UNO I2C register slave ready at 0x08")); } void loop() { uint16_t a0 = analogRead(A0); // 10-bit ADC, the Raspberry Pi has none noInterrupts(); // Both bytes must change together regs[REG_A0] = a0 >> 8; regs[REG_A0 + 1] = a0 & 0xFF; bool changed = outputsChanged; uint8_t led = regs[REG_LED], pwm = regs[REG_PWM]; outputsChanged = false; interrupts(); if (changed) // Apply and log outside the interrupt { digitalWrite(LED_BUILTIN, led ? HIGH : LOW); analogWrite(PWM_PIN, pwm); Serial.print(F("LED=")); Serial.print(led); Serial.print(F(" PWM=")); Serial.println(pwm); } } |
The first byte of every write is the register pointer; any further bytes are values, written to consecutive registers. onRequest() sends from the pointer to the end of the map, and the Pi’s NACK sets how many of those bytes it reads. Multi-byte values are high byte first, and the uptime is copied into the map inside onRequest(), so all four bytes belong to the same moment.
Repeated START vs Two Transactions
A register read can go out in two ways. With a repeated START (Sr), the Pi writes the register and turns the bus around without releasing it: one transaction, and no other master can step in between. With two transactions, the Pi writes the register, sends a STOP, then starts a new read. Both work with Wire, because the AVR core runs onReceive at a repeated START exactly as at a STOP ( TW_SR_STOP in twi.c), so the pointer is set before onRequest runs.
Python Code example (read registers with an SMBus call, a repeated START, and two transactions)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
"""read_register.py - read the UNO's registers three ways: SMBus call, repeated START, two transactions. Author: Khaled Magdy, www.DeepBlueMbedded.com """ from smbus2 import SMBus, i2c_msg UNO = 0x08 REG_WHO_AM_I, REG_UPTIME = 0x00, 0x12 with SMBus(1) as bus: # 1) SMBus "read byte data": write the register, repeated START, read one byte who = bus.read_byte_data(UNO, REG_WHO_AM_I) print(f"WHO_AM_I = 0x{who:02X}") # 2) One I2C transaction with a repeated START (i2c_rdwr) wr, rd = i2c_msg.write(UNO, [REG_UPTIME]), i2c_msg.read(UNO, 4) bus.i2c_rdwr(wr, rd) print(f"Uptime (Sr) = {int.from_bytes(bytes(rd), 'big')} ms") # 3) Two transactions: write the register + STOP, then a new START + read bus.i2c_rdwr(i2c_msg.write(UNO, [REG_UPTIME])) rd = i2c_msg.read(UNO, 4) bus.i2c_rdwr(rd) print(f"Uptime (P + S) = {int.from_bytes(bytes(rd), 'big')} ms") |
C++ Code example (read registers with I2C_RDWR and with two transactions)
|
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 |
// uno_i2c.hpp - register access to the Arduino UNO I2C slave over /dev/i2c-1 (i2c-dev ioctls) // Author: Khaled Magdy, www.DeepBlueMbedded.com #pragma once #include <cstdint> #include <cstdio> #include <stdexcept> #include <string> #include <vector> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> constexpr uint8_t UNO_ADDRESS = 0x08; constexpr uint8_t REG_WHO_AM_I = 0x00; constexpr uint8_t REG_LED = 0x01; constexpr uint8_t REG_PWM = 0x02; constexpr uint8_t REG_A0 = 0x10; constexpr uint8_t REG_UPTIME = 0x12; constexpr uint8_t REG_RX_COUNT = 0x16; class UnoI2C { public: explicit UnoI2C(const char* dev = "/dev/i2c-1", uint8_t addr = UNO_ADDRESS) : addr_(addr) { fd_ = open(dev, O_RDWR); if (fd_ < 0) throw std::runtime_error(std::string("Could not open ") + dev); } ~UnoI2C() { if (fd_ >= 0) close(fd_); } // Write the register number, repeated START, read `count` bytes: one I2C_RDWR call std::vector<uint8_t> readRegs(uint8_t reg, uint16_t count) { std::vector<uint8_t> data(count); i2c_msg msgs[2] = { { addr_, 0, 1, ® }, { addr_, I2C_M_RD, count, data.data() }, }; i2c_rdwr_ioctl_data xfer = { msgs, 2 }; if (ioctl(fd_, I2C_RDWR, &xfer) < 0) { perror("I2C_RDWR"); throw std::runtime_error("read failed"); } return data; } void writeRegs(uint8_t reg, std::vector<uint8_t> values) { values.insert(values.begin(), reg); i2c_msg msg = { addr_, 0, static_cast<uint16_t>(values.size()), values.data() }; i2c_rdwr_ioctl_data xfer = { &msg, 1 }; if (ioctl(fd_, I2C_RDWR, &xfer) < 0) { perror("I2C_RDWR"); throw std::runtime_error("write failed"); } } uint16_t readU16(uint8_t reg) { auto d = readRegs(reg, 2); return (d[0] << 8) | d[1]; } uint32_t readU32(uint8_t reg) { auto d = readRegs(reg, 4); return (uint32_t(d[0]) << 24) | (uint32_t(d[1]) << 16) | (uint32_t(d[2]) << 8) | d[3]; } private: int fd_ = -1; uint16_t addr_; }; |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// read_register.cpp - read the UNO's registers with a repeated START and with two transactions // Build: g++ -std=c++17 -O2 read_register.cpp -o read_register // Author: Khaled Magdy, www.DeepBlueMbedded.com #include "uno_i2c.hpp" int main() { try { UnoI2C uno; std::printf("WHO_AM_I = 0x%02X\n", uno.readRegs(REG_WHO_AM_I, 1)[0]); std::printf("Uptime (Sr) = %u ms\n", uno.readU32(REG_UPTIME)); // one I2C_RDWR, repeated START int fd = open("/dev/i2c-1", O_RDWR); // two plain transactions if (fd < 0 || ioctl(fd, I2C_SLAVE, UNO_ADDRESS) < 0) { perror("i2c"); return 1; } uint8_t reg = REG_UPTIME, d[4]; if (write(fd, ®, 1) != 1 || read(fd, d, 4) != 4) { perror("i2c"); return 1; } std::printf("Uptime (P + S) = %u ms\n", (uint32_t(d[0]) << 24) | (uint32_t(d[1]) << 16) | (uint32_t(d[2]) << 8) | d[3]); close(fd); } catch (const std::exception& e) { std::fprintf(stderr, "%s\n", e.what()); return 1; } } |
Here is what the bus looks like in each case, on my oscilloscope with I2C decoding on (CH1 yellow = SDA, CH3 = SCL, at the Raspberry Pi’s pins):
In the repeated-START read, the bus is never released between the register byte and the read: one transaction. As two transactions, the Pi sends a STOP after the register byte and starts the read 134µs later (the second ioctl call from Python), and the UNO still answers with the right register, because the pointer survives between transactions. In both reads, notice that SDA’s LOW level sits a little higher whenever the UNO drives it: the UNO’s LOW reaches the Pi through the BSS138, so you can tell from the trace who is talking.
The Python helper class uno_i2c.py wraps the repeated-START read and the write; Example 4 uses it:
|
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 |
"""uno_i2c.py - register access to the Arduino UNO I2C slave (Arduino_I2C_Slave_Registers). Author: Khaled Magdy, www.DeepBlueMbedded.com """ from smbus2 import SMBus, i2c_msg UNO_ADDRESS = 0x08 REG_WHO_AM_I = 0x00 REG_LED = 0x01 REG_PWM = 0x02 REG_A0 = 0x10 REG_UPTIME = 0x12 REG_RX_COUNT = 0x16 class UnoI2C: def __init__(self, bus=1, address=UNO_ADDRESS): self.bus = SMBus(bus) self.address = address def read_regs(self, reg, count): """Write the register number, then a repeated START and read `count` bytes.""" wr = i2c_msg.write(self.address, [reg]) rd = i2c_msg.read(self.address, count) self.bus.i2c_rdwr(wr, rd) # one transaction: START W reg Sr R data STOP return bytes(rd) def write_regs(self, reg, *values): self.bus.i2c_rdwr(i2c_msg.write(self.address, [reg, *values])) def read_u16(self, reg): return int.from_bytes(self.read_regs(reg, 2), "big") def read_u32(self, reg): return int.from_bytes(self.read_regs(reg, 4), "big") def close(self): self.bus.close() |
Example 4: Control the Arduino LED and Read A0 From the Raspberry Pi
The Raspberry Pi has no analog inputs; the UNO has a 10-bit ADC (one of the reasons to use both boards). In this example the Pi reads the potentiometer on the UNO’s A0 every 50ms, sets the LED’s PWM duty on D9 to the same position (0–1023 → 0–255), and turns the on-board LED on in the upper half. Both outputs go out in one 3-byte write, [0x01, LED, PWM], thanks to the auto-increment.
Python Code example (Raspberry Pi reads the Arduino’s A0 and sets its LED and PWM)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
"""arduino_led_pot.py - read the UNO's A0 (potentiometer) and set its LED brightness from the Raspberry Pi. Author: Khaled Magdy, www.DeepBlueMbedded.com """ import time from uno_i2c import UnoI2C, REG_WHO_AM_I, REG_LED, REG_PWM, REG_A0 uno = UnoI2C() try: if uno.read_regs(REG_WHO_AM_I, 1)[0] != 0xA5: raise SystemExit("No UNO register slave at 0x08") last = None while True: a0 = uno.read_u16(REG_A0) # 0..1023 from the UNO's 10-bit ADC duty = a0 >> 2 # 0..255 for analogWrite() led = 1 if a0 > 511 else 0 # on-board LED on in the upper half if (duty, led) != last: uno.write_regs(REG_LED, led, duty) # LED (0x01) and PWM (0x02) in one write last = (duty, led) print(f"A0 = {a0:4d} ({a0 * 5.0 / 1023:.2f} V) -> PWM = {duty:3d} LED = {led}") time.sleep(0.05) except KeyboardInterrupt: uno.write_regs(REG_LED, 0, 0) # leave the LEDs off finally: uno.close() |
C++ Code example (Raspberry Pi reads the Arduino’s A0 and sets its LED and PWM)
|
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 |
// arduino_led_pot.cpp - read the UNO's A0 (potentiometer) and set its LED brightness from the Raspberry Pi // Build: g++ -std=c++17 -O2 arduino_led_pot.cpp -o arduino_led_pot // Author: Khaled Magdy, www.DeepBlueMbedded.com #include "uno_i2c.hpp" #include <chrono> #include <csignal> #include <thread> static volatile std::sig_atomic_t stop = 0; int main() { std::signal(SIGINT, [](int) { stop = 1; }); try { UnoI2C uno; if (uno.readRegs(REG_WHO_AM_I, 1)[0] != 0xA5) { std::fprintf(stderr, "No UNO register slave at 0x08\n"); return 1; } int lastDuty = -1, lastLed = -1; while (!stop) { uint16_t a0 = uno.readU16(REG_A0); // 0..1023 from the UNO's 10-bit ADC int duty = a0 >> 2; // 0..255 for analogWrite() int led = a0 > 511 ? 1 : 0; if (duty != lastDuty || led != lastLed) { uno.writeRegs(REG_LED, { uint8_t(led), uint8_t(duty) }); // 0x01 LED, 0x02 PWM lastDuty = duty; lastLed = led; std::printf("A0 = %4u (%.2f V) -> PWM = %3d LED = %d\n", a0, a0 * 5.0 / 1023, duty, led); std::fflush(stdout); } std::this_thread::sleep_for(std::chrono::milliseconds(50)); } uno.writeRegs(REG_LED, { 0, 0 }); // leave the LEDs off } catch (const std::exception& e) { std::fprintf(stderr, "%s\n", e.what()); return 1; } } |
Raspberry Pi 5 I2C Clock Stretching With an Arduino
A slave may hold SCL low to make the master wait: that’s clock stretching, and the ATmega328P does it on every byte its interrupt has to handle (“While the TWINT Flag is set, the SCL low period is stretched”, ATmega328P datasheet). The longest stretch comes in onRequest(), because the UNO runs your handler before it can send the first byte.
This used to be a real problem. The BCM2835 I2C controller in older Raspberry Pi models has a known clock-stretching bug (Advamation’s analysis, raspberrypi/linux issue #254): it ignores a stretch at certain points of the transfer, and the data gets corrupted, which is why old tutorials lower the bus speed or avoid Arduino slaves. The Raspberry Pi 5 uses a different controller, the Synopsys DesignWare I2C block in the RP1 chip (RP1 peripherals datasheet). Here is what it does with the UNO:
The UNO’s interrupt holds SCL LOW for about 20µs right after the address of the read, instead of the usual 5µs LOW of a 100kHz clock, while onRequest() fills the buffer (the register sketch sends 6 bytes). With the bench sketch, whose onRequest() copies 32 bytes, the LOW grew to about 50µs. The Raspberry Pi 5 waited every time: 0 errors in 100,000 transactions across both speeds.
To find the limit, the bench sketch adds a delay of 0.1ms to 25.5ms inside onRequest(), set over I2C from the Pi, and the Pi reads the WHO_AM_I register after each setting. A 1ms stretch is no problem for the Raspberry Pi 5:
At 12ms, the Pi aborts the transfer:
| Extra delay in onRequest() | SCL held low (measured) | Read result on the Pi |
|---|---|---|
| None (register sketch) | ≈ 20µs (normal LOW 5µs) | 0xA5, OK |
| 1ms | ≈ 1.04ms | 0xA5, OK |
| 2ms / 5ms / 10ms | 0xA5, OK | |
| 10.5ms | OSError: [Errno 121] Remote I/O error | |
| 12ms | ≈ 12.0ms | Errno 121, then SDA stuck LOW |
| 20ms | Errno 121, then SDA stuck LOW |
So the Raspberry Pi 5 handles clock stretching correctly, unlike the BCM2835 models, up to about 10ms per stretch. Beyond that, the RP1 controller gives up with Errno 121, and the UNO is left in the middle of its byte, holding SDA LOW: every following transfer fails (Errno 5, and the kernel logs “SDA stuck at low”) until the UNO is reset. Normal Wire handlers take microseconds, far below the limit; the lesson is to never put delay() or slow code in onRequest().
Raspberry Pi Arduino I2C Speed: 100kHz vs 400kHz
The Raspberry Pi 5’s I2C bus runs at 100kHz by default; dtparam=i2c_arm_baudrate=400000 in /boot/firmware/config.txt (and a reboot) sets 400kHz, as shown in my Raspberry Pi I2C tutorial. The ATmega328P is specified up to 400kHz. To see what that buys and what it costs, I ran 10,000 echo transactions (write 16 random bytes, read them back, compare) at each setting, and timed one 2-byte register read 2,000 times in Python and C++ ( bench/i2c_bench.py and i2c_bench.cpp in the download):
| Setting | Errors / transactions | One register read, Python (median) | One register read, C++ (median) |
|---|---|---|---|
| 100kHz (default) | 0 / 10,000 Python, 0 / 10,000 C++ | 569µs | 565µs |
| 400kHz | 0 / 10,000 Python, 0 / 70,000 C++ | 228µs | 224µs |

Both speeds ran without a single error through the BSS138, so the UNO is a good 400kHz citizen, unlike the PCF8574 LCD backpack in my I2C LCD tutorial, which is rated for 100kHz only and NACKed at 400kHz through the same shifter. 400kHz cuts one register read from about 570µs to about 225µs, 2.5 times faster. Python and C++ are within 5µs of each other: the time goes to the bus and the UNO’s interrupts, not to the language, so pick the language for the rest of your program.
Several Arduinos (or Sensors) on One I2C Bus
Every device on the bus needs its own address, and that’s all: give each Arduino a different Wire.begin() address (0x08, 0x09, 0x0A…) and wire all SDA pins together and all SCL pins together. The Raspberry Pi then picks the Arduino by address in every call, exactly as it picks sensors. Three rules keep a mixed bus healthy:
- 5v devices on the HV side, 3.3v devices on the LV side of one shifter. Several UNOs and 5v modules can share the HV side; 3.3v sensors (a BMP280, for example) connect straight to the Pi’s GPIO2 and GPIO3.
- The slowest device sets the bus speed. The UNO ran error-free at 400kHz, but a PCF8574 LCD backpack is rated for 100kHz only (see my Raspberry Pi I2C LCD tutorial); with both on one bus, stay at 100kHz.
- Every pull-up adds up. Each 5v module and each UNO’s internal pull-ups sit in parallel on the HV side. Two or three are fine; with many modules, remove the extra pull-up resistors from the modules.
Each Arduino on the bus also clock-stretches during its own handlers, which only delays the transfers addressed to it.
Raspberry Pi Arduino I2C Troubleshooting
The Arduino Doesn’t Show Up in i2cdetect
Check, in this order: the common ground (without it the Pi sees nothing), SDA and SCL not swapped, the shifter powered on both sides (LV from the Pi’s 3.3v, HV from the UNO’s 5V), the sketch running (an i2cdetect scan during the UNO’s 1.6s reset shows an empty bus), and the address in Wire.begin(). The address must be 0x08 to 0x77; Wire accepts reserved addresses, but i2cdetect doesn’t scan them.
OSError: [Errno 121] Remote I/O error
Errno 121 is Linux’s EREMOTEIO: nobody ACKed the address. It’s the same causes as above, a wrong address in the Python code (here 0x09 instead of 0x08), or the UNO busy resetting. It also appears when the UNO stretches the clock for more than about 10ms (see the clock-stretching section).
Reads Return 0xFF or Old Data
0xFF means the UNO wasn’t driving SDA: you read more bytes than onRequest() wrote, onRequest() wasn’t registered, or the register pointer is past the end of the map. Old data usually means the register pointer isn’t where you think: every write moves it (auto-increment), so set the register in the same transaction as the read (repeated START). A write that’s longer than you meant can also overwrite registers: on my bench, a 33-byte test write to register 0x00 landed in LED, PWM and the bench registers that followed.
More Than 32 Bytes
Keep every write at 32 bytes or less, including the register byte. On the Raspberry Pi 5 the 33rd byte isn’t an error, it’s silently dropped. To move more data, split it into 32-byte chunks with a register address per chunk.
Serial.print() Inside onReceive or onRequest
The echo sketch’s onReceive() only copies bytes and sets a flag; loop() prints. That’s the pattern to keep. Printing inside a handler delays the ACK of the next byte and, once the 64-byte Serial buffer is full, waits for the UART with the I2C bus stretched, which can push a transfer into the Pi’s 10ms limit.
The Arduino Resets When Its Serial Port Opens
Opening the UNO’s USB serial port (the Serial Monitor, a terminal program, or a script) asserts DTR, and the UNO’s auto-reset circuit restarts the sketch. For about 1.6s the UNO isn’t on the bus, and the Pi’s transfers fail with Errno 121. In Part 1 of this series, the sketch was back 1.57s after every port open. On my bench, the UNO stopped answering the Pi for 1.565s each time its port opened; the Pi’s reads failed with Errno 121 until the sketch was back. Open the Serial Monitor before you start the Pi program, or retry a failed read after a short pause.
Raspberry Pi Arduino I2C FAQ
Can the Raspberry Pi be an I2C slave?
Not on the Raspberry Pi 5 with Raspberry Pi OS. The RP1’s I2C controller supports slave mode in hardware (RP1 peripherals datasheet, section 3.5), but the kernel driver doesn’t offer it: i2cdetect -F 1 reports “Target mode: no” on my Raspberry Pi 5. Make the Arduino the slave, as in this tutorial.
Can I connect the Arduino to the Raspberry Pi without a level shifter?
It works on many UNOs, but it’s outside both chips’ specifications: Wire.begin() pulls the bus toward 5v through the ATmega328P’s internal pull-ups, and the UNO needs 3.5v for a guaranteed HIGH. A BSS138 level shifter costs less than a dollar per channel and removes both problems, so every example here uses one.
Does a 3.3v Arduino need a level shifter?
No. A board that runs at 3.3v (an Arduino Pro Mini 3.3v, Arduino Due, or Nano 33) can connect pin to pin with a common ground, because its pull-ups and input thresholds are already at 3.3v.
Can an ESP32 be the I2C slave instead?
Yes, with the same onReceive and onRequest handlers, but the ESP32 Arduino core adds Wire.slaveWrite() to pre-fill the reply buffer (Espressif’s I2C documentation). It’s a 3.3v board, so no level shifter is needed.
Should I use I2C or SPI between a Raspberry Pi and an Arduino?
Use I2C when the Arduino shares the bus with other I2C devices or when you want two wires and sensor-style registers; use SPI when you need speed and fixed-size frames. For plain text commands, USB serial needs no wiring at all.
Raspberry Pi With Arduino Tutorial Series
This tutorial is the third 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 | Serial over the GPIO pins with a level shifter, Python and C++ |
| 3 | Raspberry Pi With Arduino: I2C Communication (this tutorial) | 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 I2C Examples
The download contains the two Arduino sketches, every Raspberry Pi example in Python and C++, and the bench sketch and programs behind the measurements, with a README that lists each command.
Download Raspberry Pi With Arduino I2C 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 I2C through a BSS138 level shifter, explained why the shifter matters, made the UNO an I2C slave with the Wire library’s onReceive and onRequest handlers, and turned it into a register device that the Pi reads with a repeated START, in Python and C++.
This was Part 3 of the Raspberry Pi With Arduino series: Part 1 covers USB serial and uploading sketches, Part 2 the GPIO UART link, and Part 4 the faster SPI link. For two Arduinos talking over I2C, see my Arduino I2C slave tutorial; for the Raspberry Pi’s I2C pins, bus speed and scanning, the Raspberry Pi I2C tutorial; and for the UART alternative, the Raspberry Pi UART tutorial.
